repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/internal/Buffers.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.base.internal; import org.bitcoinj.base.VarInt; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import static org.bitcoinj.base.internal.Preconditions.check; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * Utility methods for common operations on Bitcoin P2P message buffers. */ public class Buffers { /** * Read given number of bytes from the buffer. * * @param buf buffer to read from * @param length number of bytes to read * @return bytes read * @throws BufferUnderflowException if the read value extends beyond the remaining bytes of the buffer */ public static byte[] readBytes(ByteBuffer buf, int length) throws BufferUnderflowException { // defensive check against cheap memory exhaustion attack check(length <= buf.remaining(), BufferUnderflowException::new); byte[] b = new byte[length]; buf.get(b); return b; } /** * First read a {@link VarInt} from the buffer and use it to determine the number of bytes to be read. Then read * that many bytes into the byte array to be returned. This construct is frequently used by Bitcoin protocols. * * @param buf buffer to read from * @return read bytes * @throws BufferUnderflowException if the read value extends beyond the remaining bytes of the buffer */ public static byte[] readLengthPrefixedBytes(ByteBuffer buf) throws BufferUnderflowException { VarInt length = VarInt.read(buf); check(length.fitsInt(), BufferUnderflowException::new); return readBytes(buf, length.intValue()); } /** * First write the length of the byte array as a {@link VarInt}. Then write the array contents. * * @param buf buffer to write to * @param bytes bytes to write * @return the buffer * @throws BufferOverflowException if the value doesn't fit the remaining buffer */ public static ByteBuffer writeLengthPrefixedBytes(ByteBuffer buf, byte[] bytes) throws BufferOverflowException { return buf.put(VarInt.of(bytes.length).serialize()).put(bytes); } /** * First read a {@link VarInt} from the buffer and use it to determine the number of bytes to read. Then read * that many bytes and interpret it as an UTF-8 encoded string to be returned. This construct is frequently used * by Bitcoin protocols. * * @param buf buffer to read from * @return read string * @throws BufferUnderflowException if the read value extends beyond the remaining bytes of the buffer */ public static String readLengthPrefixedString(ByteBuffer buf) throws BufferUnderflowException { return new String(readLengthPrefixedBytes(buf), StandardCharsets.UTF_8); } /** * Encode a given string using UTF-8. Then write the lnegth of the encoded bytes as a {@link VarInt}. Then write * the bytes themselves. * * @param buf buffer to write to * @param str string to write * @return the buffer * @throws BufferOverflowException if the value doesn't fit the remaining buffer */ public static ByteBuffer writeLengthPrefixedString(ByteBuffer buf, String str) throws BufferOverflowException { byte[] bytes = str.getBytes(StandardCharsets.UTF_8); return writeLengthPrefixedBytes(buf, bytes); } /** * Advance buffer position by a given number of bytes. * * @param buf buffer to skip bytes on * @param numBytes number of bytes to skip * @return the buffer * @throws BufferUnderflowException if the read value extends beyond the remaining bytes of the buffer */ public static ByteBuffer skipBytes(ByteBuffer buf, int numBytes) throws BufferUnderflowException { checkArgument(numBytes >= 0); check(numBytes <= buf.remaining(), BufferUnderflowException::new); buf.position(buf.position() + numBytes); return buf; } }
4,778
39.5
116
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/internal/FutureUtils.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.base.internal; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.function.IntFunction; import java.util.function.Supplier; import java.util.stream.Collectors; /** * Utilities for {@link CompletableFuture}. * <p> * Note: When the <b>bitcoinj</b> migration to {@code CompletableFuture} is finished this class will * either be removed or its remaining methods changed to use generic {@code CompletableFuture}s. */ public class FutureUtils { /** * Note: When the migration to {@code CompletableFuture} is complete this routine will * either be removed or changed to return a generic {@code CompletableFuture}. * @param stages A list of {@code CompletionStage}s all returning the same type * @param <T> the result type * @return A CompletableFuture that returns a list of result type */ public static <T> CompletableFuture<List<T>> allAsList( List<? extends CompletionStage<? extends T>> stages) { return FutureUtils.allAsCFList(stages); } /** * Note: When the migration to {@code CompletableFuture} is complete this routine will * either be removed or changed to return a generic {@code CompletableFuture}. * @param stages A list of {@code CompletionStage}s all returning the same type * @param <T> the result type * @return A CompletableFuture that returns a list of result type */ public static <T> CompletableFuture<List<T>> successfulAsList( List<? extends CompletionStage<? extends T>> stages) { return FutureUtils.successfulAsCFList(stages); } /** * Can be replaced with {@code CompletableFuture.failedFuture(Throwable)} in Java 9+. * @param t Exception that is causing the failure * @return a failed future containing the specified exception * @param <T> the future's return type */ public static <T> CompletableFuture<T> failedFuture(Throwable t) { CompletableFuture<T> future = new CompletableFuture<>(); future.completeExceptionally(t); return future; } /** * Subinterface of {@link Supplier} for Lambdas which throw exceptions. * Can be used for two purposes: * 1. To cast a lambda that throws an exception to a {@link Supplier} and * automatically wrapping any exceptions with {@link RuntimeException}. * 2. As a {@code FunctionalInterface} where a lambda that throws exceptions is * expected or allowed. * * @param <T> the supplied type */ @FunctionalInterface public interface ThrowingSupplier<T> extends Supplier<T> { /** * Gets a result wrapping checked Exceptions with {@link RuntimeException} * @return a result */ @Override default T get() { try { return getThrows(); } catch (final Exception e) { throw new RuntimeException(e); } } /** * Gets a result. * * @return a result * @throws Exception Any checked Exception */ T getThrows() throws Exception; } /** * Thank you Apache-licensed Spotify https://github.com/spotify/completable-futures * @param stages A list of {@code CompletionStage}s all returning the same type * @param <T> the result type * @return A generic CompletableFuture that returns a list of result type */ private static <T> CompletableFuture<List<T>> allAsCFList( List<? extends CompletionStage<? extends T>> stages) { // Convert List to Array final CompletableFuture<? extends T>[] all = listToArray(stages); // Use allOf on the Array final CompletableFuture<Void> allOf = CompletableFuture.allOf(all); // If any of the components fails, fail the whole thing stages.forEach(stage -> stage.whenComplete((r, throwable) -> { if (throwable != null) { allOf.completeExceptionally(throwable); } })); // Transform allOf from Void to List<T> return transformToListResult(allOf, all); } private static <T> CompletableFuture<List<T>> successfulAsCFList( List<? extends CompletionStage<? extends T>> stages) { // Convert List to Array final CompletableFuture<? extends T>[] all = listToArray2(stages); // Use allOf on the Array final CompletableFuture<Void> allOf = CompletableFuture.allOf(all); // Transform allOf from Void to List<T> return transformToListResult(allOf, all); } private static <T> CompletableFuture<? extends T>[] listToArray( List<? extends CompletionStage<? extends T>> stages) { // Convert List to Array final CompletableFuture<? extends T>[] all = stages.stream() .map(CompletionStage::toCompletableFuture) .toArray(genericArray(CompletableFuture[]::new)); return all; } private static <T> CompletableFuture<? extends T>[] listToArray2( List<? extends CompletionStage<? extends T>> stages) { // Convert List to Array final CompletableFuture<? extends T>[] all = stages.stream() .map(s -> s.exceptionally(throwable -> null).toCompletableFuture()) .toArray(genericArray(CompletableFuture[]::new)); return all; } private static <T> CompletableFuture<List<T>> transformToListResult(CompletableFuture<Void> allOf, CompletableFuture<? extends T>[] all) { return allOf.thenApply(ignored -> Arrays.stream(all) .map(CompletableFuture::join) .collect(Collectors.toList())); } /** * Function used to create/cast generic array to expected type. Using this function prevents us from * needing a {@code @SuppressWarnings("unchecked")} in the calling code. * @param arrayCreator Array constructor lambda taking an integer size parameter and returning array of type T * @param <T> The erased type * @param <R> The desired type * @return Array constructor lambda taking an integer size parameter and returning array of type R */ @SuppressWarnings("unchecked") static <T, R extends T> IntFunction<R[]> genericArray(IntFunction<T[]> arrayCreator) { return size -> (R[]) arrayCreator.apply(size); } }
7,091
39.295455
143
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/NioClientManager.java
/* * Copyright 2013 Google Inc. * * 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. */ package org.bitcoinj.net; import com.google.common.base.Throwables; import com.google.common.util.concurrent.AbstractExecutionThreadService; import org.bitcoinj.utils.ContextPropagatingThreadFactory; import org.bitcoinj.utils.ListenableCompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.ConnectException; import java.net.SocketAddress; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.nio.channels.spi.SelectorProvider; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Queue; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; /** * A class which manages a set of client connections. Uses Java NIO to select network events and processes them in a * single network processing thread. */ public class NioClientManager extends AbstractExecutionThreadService implements ClientConnectionManager { private static final Logger log = LoggerFactory.getLogger(NioClientManager.class); private final Selector selector; static class PendingConnect { SocketChannel sc; StreamConnection connection; SocketAddress address; CompletableFuture<SocketAddress> future = new CompletableFuture<>(); PendingConnect(SocketChannel sc, StreamConnection connection, SocketAddress address) { this.sc = sc; this.connection = connection; this.address = address; } } final Queue<PendingConnect> newConnectionChannels = new LinkedBlockingQueue<>(); // Added to/removed from by the individual ConnectionHandler's, thus must by synchronized on its own. private final Set<ConnectionHandler> connectedHandlers = Collections.synchronizedSet(new HashSet<ConnectionHandler>()); // Handle a SelectionKey which was selected private void handleKey(SelectionKey key) throws IOException { // We could have a !isValid() key here if the connection is already closed at this point if (key.isValid() && key.isConnectable()) { // ie a client connection which has finished the initial connect process // Create a ConnectionHandler and hook everything together PendingConnect data = (PendingConnect) key.attachment(); StreamConnection connection = data.connection; SocketChannel sc = (SocketChannel) key.channel(); ConnectionHandler handler = new ConnectionHandler(connection, key, connectedHandlers); try { if (sc.finishConnect()) { log.info("Connected to {}", sc.socket().getRemoteSocketAddress()); key.interestOps((key.interestOps() | SelectionKey.OP_READ) & ~SelectionKey.OP_CONNECT).attach(handler); connection.connectionOpened(); data.future.complete(data.address); } else { log.warn("Failed to connect to {}", sc.socket().getRemoteSocketAddress()); handler.closeConnection(); // Failed to connect for some reason data.future.completeExceptionally(new ConnectException("Unknown reason")); data.future = null; } } catch (Exception e) { // If e is a CancelledKeyException, there is a race to get to interestOps after finishConnect() which // may cause this. Otherwise it may be any arbitrary kind of connection failure. // Calling sc.socket().getRemoteSocketAddress() here throws an exception, so we can only log the error itself Throwable cause = Throwables.getRootCause(e); log.warn("Failed to connect with exception: {}: {}", cause.getClass().getName(), cause.getMessage(), e); handler.closeConnection(); data.future.completeExceptionally(cause); data.future = null; } } else // Process bytes read ConnectionHandler.handleKey(key); } /** * Creates a new client manager which uses Java NIO for socket management. Uses a single thread to handle all select * calls. */ public NioClientManager() { try { selector = SelectorProvider.provider().openSelector(); } catch (IOException e) { throw new RuntimeException(e); // Shouldn't ever happen } } @Override public void run() { try { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); while (isRunning()) { PendingConnect conn; while ((conn = newConnectionChannels.poll()) != null) { try { SelectionKey key = conn.sc.register(selector, SelectionKey.OP_CONNECT); key.attach(conn); } catch (ClosedChannelException e) { log.warn("SocketChannel was closed before it could be registered"); } } selector.select(); Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); keyIterator.remove(); handleKey(key); } } } catch (Exception e) { log.warn("Error trying to open/read from connection: ", e); } finally { // Go through and close everything, without letting IOExceptions get in our way for (SelectionKey key : selector.keys()) { try { key.channel().close(); } catch (IOException e) { log.warn("Error closing channel", e); } key.cancel(); if (key.attachment() instanceof ConnectionHandler) ConnectionHandler.handleKey(key); // Close connection if relevant } try { selector.close(); } catch (IOException e) { log.warn("Error closing client manager selector", e); } } } @Override public ListenableCompletableFuture<SocketAddress> openConnection(SocketAddress serverAddress, StreamConnection connection) { if (!isRunning()) throw new IllegalStateException(); // Create a new connection, give it a connection as an attachment try { SocketChannel sc = SocketChannel.open(); sc.configureBlocking(false); sc.connect(serverAddress); PendingConnect data = new PendingConnect(sc, connection, serverAddress); newConnectionChannels.offer(data); selector.wakeup(); return ListenableCompletableFuture.of(data.future); } catch (Throwable e) { return ListenableCompletableFuture.failedFuture(e); } } @Override public void triggerShutdown() { selector.wakeup(); } @Override public int getConnectedClientCount() { return connectedHandlers.size(); } @Override public void closeConnections(int n) { while (n-- > 0) { ConnectionHandler handler; synchronized (connectedHandlers) { handler = connectedHandlers.iterator().next(); } if (handler != null) handler.closeConnection(); // Removes handler from connectedHandlers before returning } } @Override protected Executor executor() { return command -> new ContextPropagatingThreadFactory("NioClientManager").newThread(command).start(); } }
8,512
40.935961
164
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/package-info.java
/* * Copyright by the original author or authors. * * 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. */ /** * Classes handling low level network management using either NIO (async io) or older style blocking sockets (useful for * using SOCKS proxies, Tor, SSL etc). The code in this package implements a simple network abstraction a little like * what the Netty library provides, but with only what bitcoinj needs. */ package org.bitcoinj.net;
957
42.545455
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/StreamConnectionFactory.java
/* * Copyright 2013 Google Inc. * * 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. */ package org.bitcoinj.net; import javax.annotation.Nullable; import java.net.InetAddress; /** * A factory which generates new {@link StreamConnection}s when a new connection is opened. */ public interface StreamConnectionFactory { /** * Returns a new handler or null to have the connection close. * @param inetAddress The client's (IP) address * @param port The remote port on the client side */ @Nullable StreamConnection getNewConnection(InetAddress inetAddress, int port); }
1,108
31.617647
91
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/AbstractTimeoutHandler.java
/* * Copyright 2013 Google Inc. * * 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. */ package org.bitcoinj.net; import java.time.Duration; /** * A base class which provides basic support for socket timeouts. It is used instead of integrating timeouts into the * NIO select thread both for simplicity and to keep code shared between NIO and blocking sockets as much as possible. * <p> * @deprecated Don't extend this class, implement {@link TimeoutHandler} using {@link SocketTimeoutTask} instead */ @Deprecated public abstract class AbstractTimeoutHandler implements TimeoutHandler { private final SocketTimeoutTask timeoutTask; public AbstractTimeoutHandler() { timeoutTask = new SocketTimeoutTask(this::timeoutOccurred); } /** * <p>Enables or disables the timeout entirely. This may be useful if you want to store the timeout value but wish * to temporarily disable/enable timeouts.</p> * * <p>The default is for timeoutEnabled to be true but timeout to be set to {@link Duration#ZERO} (ie disabled).</p> * * <p>This call will reset the current progress towards the timeout.</p> */ @Override public synchronized final void setTimeoutEnabled(boolean timeoutEnabled) { timeoutTask.setTimeoutEnabled(timeoutEnabled); } /** * <p>Sets the receive timeout, automatically killing the connection if no * messages are received for this long</p> * * <p>A timeout of 0{@link Duration#ZERO} is interpreted as no timeout.</p> * * <p>The default is for timeoutEnabled to be true but timeout to be set to {@link Duration#ZERO} (ie disabled).</p> * * <p>This call will reset the current progress towards the timeout.</p> */ @Override public synchronized final void setSocketTimeout(Duration timeout) { timeoutTask.setSocketTimeout(timeout); } /** * Resets the current progress towards timeout to 0. */ protected synchronized void resetTimeout() { timeoutTask.resetTimeout(); } protected abstract void timeoutOccurred(); }
2,611
35.277778
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/MessageWriteTarget.java
/* * Copyright 2013 Google Inc. * * 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. */ package org.bitcoinj.net; import org.bitcoinj.utils.ListenableCompletableFuture; import java.io.IOException; /** * A target to which messages can be written/connection can be closed */ public interface MessageWriteTarget { /** * Writes the given bytes to the remote server. The returned future will complete when all bytes * have been written to the OS network buffer. */ ListenableCompletableFuture<Void> writeBytes(byte[] message) throws IOException; /** * Closes the connection to the server, triggering the {@link StreamConnection#connectionClosed()} * event on the network-handling thread where all callbacks occur. */ void closeConnection(); }
1,296
33.131579
102
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/NioClient.java
/* * Copyright 2013 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. */ package org.bitcoinj.net; import com.google.common.base.Throwables; import org.bitcoinj.utils.ListenableCompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.time.Duration; /** * Creates a simple connection to a server using a {@link StreamConnection} to process data. */ public class NioClient implements MessageWriteTarget { private static final Logger log = LoggerFactory.getLogger(NioClient.class); private final Handler handler; private final NioClientManager manager = new NioClientManager(); class Handler implements TimeoutHandler, StreamConnection { private final StreamConnection upstreamConnection; private final SocketTimeoutTask timeoutTask; private MessageWriteTarget writeTarget; private boolean closeOnOpen = false; private boolean closeCalled = false; Handler(StreamConnection upstreamConnection, Duration connectTimeout) { this.upstreamConnection = upstreamConnection; this.timeoutTask = new SocketTimeoutTask(this::timeoutOccurred); setSocketTimeout(connectTimeout); setTimeoutEnabled(true); } private synchronized void timeoutOccurred() { closeOnOpen = true; connectionClosed(); } @Override public void setTimeoutEnabled(boolean timeoutEnabled) { timeoutTask.setTimeoutEnabled(timeoutEnabled); } @Override public void setSocketTimeout(Duration timeout) { timeoutTask.setSocketTimeout(timeout); } @Override public synchronized void connectionClosed() { manager.stopAsync(); if (!closeCalled) { closeCalled = true; upstreamConnection.connectionClosed(); } } @Override public synchronized void connectionOpened() { if (!closeOnOpen) upstreamConnection.connectionOpened(); } @Override public int receiveBytes(ByteBuffer buff) throws Exception { return upstreamConnection.receiveBytes(buff); } @Override public synchronized void setWriteTarget(MessageWriteTarget writeTarget) { if (closeOnOpen) writeTarget.closeConnection(); else { setTimeoutEnabled(false); this.writeTarget = writeTarget; upstreamConnection.setWriteTarget(writeTarget); } } @Override public int getMaxMessageSize() { return upstreamConnection.getMaxMessageSize(); } } /** * <p>Creates a new client to the given server address using the given {@link StreamConnection} to decode the data. * The given connection <b>MUST</b> be unique to this object. This does not block while waiting for the connection to * open, but will call either the {@link StreamConnection#connectionOpened()} or * {@link StreamConnection#connectionClosed()} callback on the created network event processing thread.</p> * @param serverAddress socket address of the server to connect to * @param parser parses data from the server * @param connectTimeout timeout for establishing a connection to the server, or ZERO for no timeout */ public NioClient(final SocketAddress serverAddress, final StreamConnection parser, final Duration connectTimeout) throws IOException { manager.startAsync(); manager.awaitRunning(); handler = new Handler(parser, connectTimeout); manager.openConnection(serverAddress, handler).whenComplete((result, t) -> { if (t != null) { log.error("Connect to {} failed: {}", serverAddress, Throwables.getRootCause(t)); } }); } @Override public void closeConnection() { handler.writeTarget.closeConnection(); } @Override public synchronized ListenableCompletableFuture<Void> writeBytes(byte[] message) throws IOException { return handler.writeTarget.writeBytes(message); } }
4,888
34.948529
121
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/BlockingClientManager.java
/* * Copyright 2013 Google Inc. * * 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. */ package org.bitcoinj.net; import com.google.common.util.concurrent.AbstractIdleService; import org.bitcoinj.utils.ListenableCompletableFuture; import javax.net.SocketFactory; import java.io.IOException; import java.net.SocketAddress; import java.time.Duration; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Objects; import java.util.Set; /** * <p>A thin wrapper around a set of {@link BlockingClient}s.</p> * * <p>Generally, using {@link NioClient} and {@link NioClientManager} should be preferred over {@link BlockingClient} * and {@link BlockingClientManager} as they scale significantly better, unless you wish to connect over a proxy or use * some other network settings that cannot be set using NIO.</p> */ public class BlockingClientManager extends AbstractIdleService implements ClientConnectionManager { private final SocketFactory socketFactory; private final Set<BlockingClient> clients = Collections.synchronizedSet(new HashSet<BlockingClient>()); private Duration connectTimeout = Duration.ofSeconds(1); public BlockingClientManager() { socketFactory = SocketFactory.getDefault(); } /** * Creates a blocking client manager that will obtain sockets from the given factory. Useful for customising how * bitcoinj connects to the P2P network. */ public BlockingClientManager(SocketFactory socketFactory) { this.socketFactory = Objects.requireNonNull(socketFactory); } @Override public ListenableCompletableFuture<SocketAddress> openConnection(SocketAddress serverAddress, StreamConnection connection) { try { if (!isRunning()) throw new IllegalStateException(); return new BlockingClient(serverAddress, connection, connectTimeout, socketFactory, clients).getConnectFuture(); } catch (IOException e) { throw new RuntimeException(e); // This should only happen if we are, eg, out of system resources } } /** * Sets the number of milliseconds to wait before giving up on a connect attempt * @param connectTimeout timeout for establishing a connection to the client */ public void setConnectTimeout(Duration connectTimeout) { this.connectTimeout = connectTimeout; } /** @deprecated use {@link #setConnectTimeout(Duration)} */ @Deprecated public void setConnectTimeoutMillis(int connectTimeoutMillis) { setConnectTimeout(Duration.ofMillis(connectTimeoutMillis)); } @Override protected void startUp() throws Exception { } @Override protected void shutDown() throws Exception { synchronized (clients) { for (BlockingClient client : clients) client.closeConnection(); } } @Override public int getConnectedClientCount() { return clients.size(); } @Override public void closeConnections(int n) { if (!isRunning()) throw new IllegalStateException(); synchronized (clients) { Iterator<BlockingClient> it = clients.iterator(); while (n-- > 0 && it.hasNext()) it.next().closeConnection(); } } }
3,839
34.229358
128
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/FilterMerger.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.net; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.core.BloomFilter; import org.bitcoinj.core.PeerFilterProvider; import org.bitcoinj.core.PeerGroup; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Random; // This code is unit tested by the PeerGroup tests. /** * <p>A reusable object that will calculate, given a list of {@link PeerFilterProvider}s, a merged * {@link BloomFilter} and earliest key time for all of them. * Used by the {@link PeerGroup} class internally.</p> * * <p>Thread safety: threading here can be complicated. Each filter provider is given a begin event, which may acquire * a lock (and is guaranteed to receive an end event). This class is mostly thread unsafe and is meant to be used from a * single thread only, PeerGroup ensures this by only accessing it from the dedicated PeerGroup thread. PeerGroup does * not hold any locks whilst this object is used, relying on the single thread to prevent multiple filters being * calculated in parallel, thus a filter provider can do things like make blocking calls into PeerGroup from a separate * thread. However the bloomFilterFPRate property IS thread safe, for convenience.</p> */ public class FilterMerger { // We use a constant tweak to avoid giving up privacy when we regenerate our filter with new keys private final int bloomFilterTweak = new Random().nextInt(); private volatile double vBloomFilterFPRate; private int lastBloomFilterElementCount; private BloomFilter lastFilter; public FilterMerger(double bloomFilterFPRate) { this.vBloomFilterFPRate = bloomFilterFPRate; } public static class Result { public BloomFilter filter; public Instant earliestKeyTime; public boolean changed; } public Result calculate(List<PeerFilterProvider> providerList) { List<PeerFilterProvider> providers = Collections.unmodifiableList(providerList); LinkedList<PeerFilterProvider> begunProviders = new LinkedList<>(); try { // All providers must be in a consistent, unchanging state because the filter is a merged one that's // large enough for all providers elements: if a provider were to get more elements in the middle of the // calculation, we might assert or calculate the filter wrongly. Most providers use a lock here but // snapshotting required state is also a legitimate strategy. for (PeerFilterProvider provider : providers) { provider.beginBloomFilterCalculation(); begunProviders.add(provider); } Result result = new Result(); result.earliestKeyTime = Instant.MAX; int elements = 0; for (PeerFilterProvider p : providers) { result.earliestKeyTime = TimeUtils.earlier(result.earliestKeyTime, p.earliestKeyCreationTime()); elements += p.getBloomFilterElementCount(); } if (elements > 0) { // We stair-step our element count so that we avoid creating a filter with different parameters // as much as possible as that results in a loss of privacy. // The constant 100 here is somewhat arbitrary, but makes sense for small to medium wallets - // it will likely mean we never need to create a filter with different parameters. lastBloomFilterElementCount = elements > lastBloomFilterElementCount ? elements + 100 : lastBloomFilterElementCount; double fpRate = vBloomFilterFPRate; // We now always use UPDATE_ALL because with segwit there is hardly any wallet that can do without. BloomFilter filter = new BloomFilter(lastBloomFilterElementCount, fpRate, bloomFilterTweak, BloomFilter.BloomUpdate.UPDATE_ALL); for (PeerFilterProvider p : providers) filter.merge(p.getBloomFilter(lastBloomFilterElementCount, fpRate, bloomFilterTweak)); result.changed = !filter.equals(lastFilter); result.filter = lastFilter = filter; } // Now adjust the earliest key time backwards by a week to handle the case of clock drift. This can occur // both in block header timestamps and if the users clock was out of sync when the key was first created // (to within a small amount of tolerance). result.earliestKeyTime = result.earliestKeyTime.minus(7, ChronoUnit.DAYS); return result; } finally { for (PeerFilterProvider provider : begunProviders) { provider.endBloomFilterCalculation(); } } } public void setBloomFilterFPRate(double bloomFilterFPRate) { this.vBloomFilterFPRate = bloomFilterFPRate; } public double getBloomFilterFPRate() { return vBloomFilterFPRate; } public BloomFilter getLastFilter() { return lastFilter; } }
5,777
45.97561
132
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/BlockingClient.java
/* * Copyright 2013 Google Inc. * * 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. */ package org.bitcoinj.net; import org.bitcoinj.core.Context; import org.bitcoinj.core.Peer; import org.bitcoinj.utils.ListenableCompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.net.SocketFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.SocketAddress; import java.nio.Buffer; import java.nio.ByteBuffer; import java.time.Duration; import java.util.Set; import java.util.concurrent.CompletableFuture; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * <p>Creates a simple connection to a server using a {@link StreamConnection} to process data.</p> * * <p>Generally, using {@link NioClient} and {@link NioClientManager} should be preferred over {@link BlockingClient} * and {@link BlockingClientManager}, unless you wish to connect over a proxy or use some other network settings that * cannot be set using NIO.</p> */ public class BlockingClient implements MessageWriteTarget { private static final Logger log = LoggerFactory.getLogger(BlockingClient.class); private static final int BUFFER_SIZE_LOWER_BOUND = 4096; private static final int BUFFER_SIZE_UPPER_BOUND = 65536; private Socket socket; private volatile boolean vCloseRequested = false; private CompletableFuture<SocketAddress> connectFuture; /** * <p>Creates a new client to the given server address using the given {@link StreamConnection} to decode the data. * The given connection <b>MUST</b> be unique to this object. This does not block while waiting for the connection to * open, but will call either the {@link StreamConnection#connectionOpened()} or * {@link StreamConnection#connectionClosed()} callback on the created network event processing thread.</p> * * @param connectTimeout The connect timeout set on the connection. ZERO is interpreted as no timeout. * @param socketFactory An object that creates {@link Socket} objects on demand, which may be customised to control * how this client connects to the internet. If not sure, use SocketFactory.getDefault() * @param clientSet A set which this object will add itself to after initialization, and then remove itself from */ public BlockingClient(final SocketAddress serverAddress, final StreamConnection connection, final Duration connectTimeout, final SocketFactory socketFactory, @Nullable final Set<BlockingClient> clientSet) throws IOException { connectFuture = new CompletableFuture<>(); // Try to fit at least one message in the network buffer, but place an upper and lower limit on its size to make // sure it doesn't get too large or have to call read too often. connection.setWriteTarget(this); socket = socketFactory.createSocket(); final Context context = Context.get(); Thread t = new Thread(() -> { Context.propagate(context); if (clientSet != null) clientSet.add(BlockingClient.this); try { socket.connect(serverAddress, Math.toIntExact(connectTimeout.toMillis())); connection.connectionOpened(); connectFuture.complete(serverAddress); InputStream stream = socket.getInputStream(); runReadLoop(stream, connection); } catch (Exception e) { if (!vCloseRequested) { log.error("Error trying to open/read from connection: {}: {}", serverAddress, e.getMessage()); connectFuture.completeExceptionally(e); } } finally { try { socket.close(); } catch (IOException e1) { // At this point there isn't much we can do, and we can probably assume the channel is closed } if (clientSet != null) clientSet.remove(BlockingClient.this); connection.connectionClosed(); } }); t.setName("BlockingClient network thread for " + serverAddress); t.setDaemon(true); t.start(); } /** * A blocking call that never returns, except by throwing an exception. It reads bytes from the input stream * and feeds them to the provided {@link StreamConnection}, for example, a {@link Peer}. */ public static void runReadLoop(InputStream stream, StreamConnection connection) throws Exception { ByteBuffer dbuf = ByteBuffer.allocateDirect(Math.min(Math.max(connection.getMaxMessageSize(), BUFFER_SIZE_LOWER_BOUND), BUFFER_SIZE_UPPER_BOUND)); byte[] readBuff = new byte[dbuf.capacity()]; while (true) { // TODO Kill the message duplication here checkState(dbuf.remaining() > 0 && dbuf.remaining() <= readBuff.length); int read = stream.read(readBuff, 0, Math.max(1, Math.min(dbuf.remaining(), stream.available()))); if (read == -1) return; dbuf.put(readBuff, 0, read); // "flip" the buffer - setting the limit to the current position and setting position to 0 ((Buffer) dbuf).flip(); // Use connection.receiveBytes's return value as a double-check that it stopped reading at the right // location int bytesConsumed = connection.receiveBytes(dbuf); checkState(dbuf.position() == bytesConsumed); // Now drop the bytes which were read by compacting dbuf (resetting limit and keeping relative // position) dbuf.compact(); } } /** * Closes the connection to the server, triggering the {@link StreamConnection#connectionClosed()} * event on the network-handling thread where all callbacks occur. */ @Override public void closeConnection() { // Closes the channel, triggering an exception in the network-handling thread triggering connectionClosed() try { vCloseRequested = true; socket.close(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public synchronized ListenableCompletableFuture<Void> writeBytes(byte[] message) throws IOException { try { OutputStream stream = socket.getOutputStream(); stream.write(message); stream.flush(); return ListenableCompletableFuture.completedFuture(null); } catch (IOException e) { log.error("Error writing message to connection, closing connection", e); closeConnection(); throw e; } } /** Returns a future that completes once connection has occurred at the socket level or with an exception if failed to connect. */ public ListenableCompletableFuture<SocketAddress> getConnectFuture() { return ListenableCompletableFuture.of(connectFuture); } }
7,701
44.845238
154
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/ClientConnectionManager.java
/* * Copyright 2013 Google Inc. * * 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. */ package org.bitcoinj.net; import com.google.common.util.concurrent.Service; import org.bitcoinj.utils.ListenableCompletableFuture; import java.net.SocketAddress; /** * <p>A generic interface for an object which keeps track of a set of open client connections, creates new ones and * ensures they are serviced properly.</p> * * <p>When the service is stopped via {@link com.google.common.util.concurrent.Service#stopAsync()}, all connections will be closed and * the appropriate connectionClosed() calls must be made.</p> */ public interface ClientConnectionManager extends Service { /** * Creates a new connection to the given address, with the given connection used to handle incoming data. Any errors * that occur during connection will be returned in the given future, including errors that can occur immediately. */ ListenableCompletableFuture<SocketAddress> openConnection(SocketAddress serverAddress, StreamConnection connection); /** Gets the number of connected peers */ int getConnectedClientCount(); /** Closes n peer connections */ void closeConnections(int n); }
1,720
38.113636
135
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/NioServer.java
/* * Copyright 2013 Google Inc. * * 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. */ package org.bitcoinj.net; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Throwables; import com.google.common.util.concurrent.AbstractExecutionThreadService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.channels.spi.SelectorProvider; import java.util.Iterator; /** * Creates a simple server listener which listens for incoming client connections and uses a {@link StreamConnection} to * process data. */ public class NioServer extends AbstractExecutionThreadService { private static final Logger log = LoggerFactory.getLogger(NioServer.class); private final StreamConnectionFactory connectionFactory; private final ServerSocketChannel sc; @VisibleForTesting final Selector selector; // Handle a SelectionKey which was selected private void handleKey(Selector selector, SelectionKey key) throws IOException { if (key.isValid() && key.isAcceptable()) { // Accept a new connection, give it a stream connection as an attachment SocketChannel newChannel = sc.accept(); newChannel.configureBlocking(false); SelectionKey newKey = newChannel.register(selector, SelectionKey.OP_READ); try { ConnectionHandler handler = new ConnectionHandler(connectionFactory, newKey); newKey.attach(handler); handler.connection.connectionOpened(); } catch (IOException e) { // This can happen if ConnectionHandler's call to get a new handler returned null log.error("Error handling new connection", Throwables.getRootCause(e).getMessage()); newKey.channel().close(); } } else { // Got a closing channel or a channel to a client connection ConnectionHandler.handleKey(key); } } /** * Creates a new server which is capable of listening for incoming connections and processing client provided data * using {@link StreamConnection}s created by the given {@link StreamConnectionFactory} * * @throws IOException If there is an issue opening the server socket or binding fails for some reason */ public NioServer(final StreamConnectionFactory connectionFactory, InetSocketAddress bindAddress) throws IOException { this.connectionFactory = connectionFactory; sc = ServerSocketChannel.open(); sc.configureBlocking(false); sc.socket().bind(bindAddress); selector = SelectorProvider.provider().openSelector(); sc.register(selector, SelectionKey.OP_ACCEPT); } @Override protected void run() throws Exception { try { while (isRunning()) { selector.select(); Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); keyIterator.remove(); handleKey(selector, key); } } } catch (Exception e) { log.error("Error trying to open/read from connection: {}", e); } finally { // Go through and close everything, without letting IOExceptions get in our way for (SelectionKey key : selector.keys()) { try { key.channel().close(); } catch (IOException e) { log.error("Error closing channel", e); } try { key.cancel(); handleKey(selector, key); } catch (IOException e) { log.error("Error closing selection key", e); } } try { selector.close(); } catch (IOException e) { log.error("Error closing server selector", e); } try { sc.close(); } catch (IOException e) { log.error("Error closing server channel", e); } } } /** * Invoked by the Execution service when it's time to stop. * Calling this method directly will NOT stop the service, call * {@link com.google.common.util.concurrent.AbstractExecutionThreadService#stopAsync()} instead. */ @Override public void triggerShutdown() { // Wake up the selector and let the selection thread break its loop as the ExecutionService !isRunning() selector.wakeup(); } }
5,398
38.123188
121
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/StreamConnection.java
/* * Copyright 2013 Google Inc. * * 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. */ package org.bitcoinj.net; import java.nio.ByteBuffer; /** * A generic handler which is used in {@link NioServer}, {@link NioClient} and {@link BlockingClient} to handle incoming * data streams. * * Used to be called StreamParser. */ public interface StreamConnection { /** Called when the connection socket is closed */ void connectionClosed(); /** Called when the connection socket is first opened */ void connectionOpened(); /** * <p>Called when new bytes are available from the remote end. This should only ever be called by the single * writeTarget associated with any given StreamConnection, multiple callers will likely confuse implementations.</p> * * Implementers/callers must follow the following conventions exactly: * <ul> * <li>buff will start with its limit set to the position we can read to and its position set to the location we * will start reading at (always 0)</li> * <li>May read more than one message (recursively) if there are enough bytes available</li> * <li>Uses some internal buffering to store message which are larger (incl their length prefix) than buff's * capacity(), ie it is up to this method to ensure we don't run out of buffer space to decode the next message. * </li> * <li>buff will end with its limit the same as it was previously, and its position set to the position up to which * bytes have been read (the same as its return value)</li> * <li>buff must be at least the size of a Bitcoin header (incl magic bytes).</li> * </ul> * * @return The amount of bytes consumed which should not be provided again */ int receiveBytes(ByteBuffer buff) throws Exception; /** * Called when this connection is attached to an upstream write target (ie a low-level connection handler). This * writeTarget should be stored and used to close the connection or write data to the socket. */ void setWriteTarget(MessageWriteTarget writeTarget); /** * Returns the maximum message size of a message on the socket. This is used in calculating size of buffers to * allocate. */ int getMaxMessageSize(); }
2,804
40.865672
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/ConnectionHandler.java
/* * Copyright 2013 Google Inc. * * 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. */ package org.bitcoinj.net; import com.google.common.base.Throwables; import org.bitcoinj.core.Message; import org.bitcoinj.utils.ListenableCompletableFuture; import org.bitcoinj.utils.Threading; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import java.io.IOException; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.channels.CancelledKeyException; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.Objects; import java.util.Set; import java.util.concurrent.locks.ReentrantLock; import static org.bitcoinj.base.internal.Preconditions.checkState; // TODO: The locking in all this class is horrible and not really necessary. We should just run all network stuff on one thread. /** * A simple NIO MessageWriteTarget which handles all the business logic of a connection (reading+writing bytes). * Used only by the NioClient and NioServer classes */ class ConnectionHandler implements MessageWriteTarget { private static final Logger log = LoggerFactory.getLogger(ConnectionHandler.class); // We lock when touching local flags and when writing data, but NEVER when calling any methods which leave this // class into non-Java classes. private final ReentrantLock lock = Threading.lock(ConnectionHandler.class); private static final int BUFFER_SIZE_LOWER_BOUND = 4096; private static final int BUFFER_SIZE_UPPER_BOUND = 65536; private static final int OUTBOUND_BUFFER_BYTE_COUNT = Message.MAX_SIZE + 24; // 24 byte message header @GuardedBy("lock") private final ByteBuffer readBuff; @GuardedBy("lock") private final SocketChannel channel; @GuardedBy("lock") private final SelectionKey key; @GuardedBy("lock") StreamConnection connection; @GuardedBy("lock") private boolean closeCalled = false; @GuardedBy("lock") private long bytesToWriteRemaining = 0; @GuardedBy("lock") private final LinkedList<BytesAndFuture> bytesToWrite = new LinkedList<>(); private static class BytesAndFuture { public final ByteBuffer bytes; public final ListenableCompletableFuture<Void> future; public BytesAndFuture(ByteBuffer bytes, ListenableCompletableFuture<Void> future) { this.bytes = bytes; this.future = future; } } private Set<ConnectionHandler> connectedHandlers; public ConnectionHandler(StreamConnectionFactory connectionFactory, SelectionKey key) throws IOException { this(connectionFactory.getNewConnection(((SocketChannel) key.channel()).socket().getInetAddress(), ((SocketChannel) key.channel()).socket().getPort()), key); if (connection == null) throw new IOException("Parser factory.getNewConnection returned null"); } private ConnectionHandler(@Nullable StreamConnection connection, SelectionKey key) { this.key = key; this.channel = Objects.requireNonNull(((SocketChannel)key.channel())); if (connection == null) { readBuff = null; return; } this.connection = connection; readBuff = ByteBuffer.allocateDirect(Math.min(Math.max(connection.getMaxMessageSize(), BUFFER_SIZE_LOWER_BOUND), BUFFER_SIZE_UPPER_BOUND)); connection.setWriteTarget(this); // May callback into us (eg closeConnection() now) connectedHandlers = null; } public ConnectionHandler(StreamConnection connection, SelectionKey key, Set<ConnectionHandler> connectedHandlers) { this(Objects.requireNonNull(connection), key); // closeConnection() may have already happened because we invoked the other c'tor above, which called // connection.setWriteTarget which might have re-entered already. In this case we shouldn't add ourselves // to the connectedHandlers set. lock.lock(); try { this.connectedHandlers = connectedHandlers; if (!closeCalled) checkState(this.connectedHandlers.add(this)); } finally { lock.unlock(); } } @GuardedBy("lock") private void setWriteOps() { // Make sure we are registered to get updated when writing is available again key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); // Refresh the selector to make sure it gets the new interestOps key.selector().wakeup(); } // Tries to write any outstanding write bytes, runs in any thread (possibly unlocked) private void tryWriteBytes() throws IOException { lock.lock(); try { // Iterate through the outbound ByteBuff queue, pushing as much as possible into the OS' network buffer. Iterator<BytesAndFuture> iterator = bytesToWrite.iterator(); while (iterator.hasNext()) { BytesAndFuture bytesAndFuture = iterator.next(); bytesToWriteRemaining -= channel.write(bytesAndFuture.bytes); if (!bytesAndFuture.bytes.hasRemaining()) { iterator.remove(); bytesAndFuture.future.complete(null); } else { setWriteOps(); break; } } // If we are done writing, clear the OP_WRITE interestOps if (bytesToWrite.isEmpty()) key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE); // Don't bother waking up the selector here, since we're just removing an op, not adding } finally { lock.unlock(); } } @Override public ListenableCompletableFuture<Void> writeBytes(byte[] message) throws IOException { boolean andUnlock = true; lock.lock(); try { // Network buffers are not unlimited (and are often smaller than some messages we may wish to send), and // thus we have to buffer outbound messages sometimes. To do this, we use a queue of ByteBuffers and just // append to it when we want to send a message. We then let tryWriteBytes() either send the message or // register our SelectionKey to wakeup when we have free outbound buffer space available. if (bytesToWriteRemaining + message.length > OUTBOUND_BUFFER_BYTE_COUNT) throw new IOException("Outbound buffer overflowed"); // Just dump the message onto the write buffer and call tryWriteBytes // TODO: Kill the needless message duplication when the write completes right away final ListenableCompletableFuture<Void> future = new ListenableCompletableFuture<>(); bytesToWrite.offer(new BytesAndFuture(ByteBuffer.wrap(Arrays.copyOf(message, message.length)), future)); bytesToWriteRemaining += message.length; setWriteOps(); return future; } catch (IOException e) { lock.unlock(); andUnlock = false; log.warn("Error writing message to connection, closing connection", e); closeConnection(); throw e; } catch (CancelledKeyException e) { lock.unlock(); andUnlock = false; log.warn("Error writing message to connection, closing connection", e); closeConnection(); throw new IOException(e); } finally { if (andUnlock) lock.unlock(); } } // May NOT be called with lock held @Override public void closeConnection() { checkState(!lock.isHeldByCurrentThread()); try { channel.close(); } catch (IOException e) { throw new RuntimeException(e); } connectionClosed(); } private void connectionClosed() { boolean callClosed = false; lock.lock(); try { callClosed = !closeCalled; closeCalled = true; } finally { lock.unlock(); } if (callClosed) { checkState(connectedHandlers == null || connectedHandlers.remove(this)); connection.connectionClosed(); } } // Handle a SelectionKey which was selected // Runs unlocked as the caller is single-threaded (or if not, should enforce that handleKey is only called // atomically for a given ConnectionHandler) public static void handleKey(SelectionKey key) { ConnectionHandler handler = ((ConnectionHandler)key.attachment()); try { if (handler == null) return; if (!key.isValid()) { handler.closeConnection(); // Key has been cancelled, make sure the socket gets closed return; } if (key.isReadable()) { // Do a socket read and invoke the connection's receiveBytes message int read = handler.channel.read(handler.readBuff); if (read == 0) return; // Was probably waiting on a write else if (read == -1) { // Socket was closed key.cancel(); handler.closeConnection(); return; } // "flip" the buffer - setting the limit to the current position and setting position to 0 ((Buffer) handler.readBuff).flip(); // Use connection.receiveBytes's return value as a check that it stopped reading at the right location int bytesConsumed = Objects.requireNonNull(handler.connection).receiveBytes(handler.readBuff); checkState(handler.readBuff.position() == bytesConsumed); // Now drop the bytes which were read by compacting readBuff (resetting limit and keeping relative // position) handler.readBuff.compact(); } if (key.isWritable()) handler.tryWriteBytes(); } catch (Exception e) { // This can happen eg if the channel closes while the thread is about to get killed // (ClosedByInterruptException), or if handler.connection.receiveBytes throws something Throwable t = Throwables.getRootCause(e); log.warn("Error handling SelectionKey: {} {}", t.getClass().getName(), t.getMessage() != null ? t.getMessage() : "", e); handler.closeConnection(); } } }
11,151
42.5625
165
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/TimeoutHandler.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.net; import java.time.Duration; /** * Provides basic support for socket timeouts. It is used instead of integrating timeouts into the * NIO select thread both for simplicity and to keep code shared between NIO and blocking sockets as much as possible. */ public interface TimeoutHandler { /** * <p>Enables or disables the timeout entirely. This may be useful if you want to store the timeout value but wish * to temporarily disable/enable timeouts.</p> * * <p>The default is for timeoutEnabled to be true but timeout to be set to 0 (ie disabled).</p> * * <p>This call will reset the current progress towards the timeout.</p> */ void setTimeoutEnabled(boolean timeoutEnabled); /** * <p>Sets the receive timeout, automatically killing the connection if no * messages are received for this long</p> * * <p>A timeout of {@link Duration#ZERO} is interpreted as no timeout.</p> * * <p>The default is for timeoutEnabled to be true but timeout to be set to {@link Duration#ZERO} (ie disabled).</p> * * <p>This call will reset the current progress towards the timeout.</p> */ void setSocketTimeout(Duration timeout); }
1,846
37.479167
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/SocketTimeoutTask.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.net; import java.time.Duration; import java.util.Timer; import java.util.TimerTask; /** * Component that implements the timeout capability of {@link TimeoutHandler}. */ public class SocketTimeoutTask implements TimeoutHandler { // TimerTask and timeout value which are added to a timer to kill the connection on timeout private final Runnable actualTask; private TimerTask timeoutTask; private Duration timeout = Duration.ZERO; private boolean timeoutEnabled = true; // A timer which manages expiring channels as their timeouts occur (if configured). private static final Timer timeoutTimer = new Timer("AbstractTimeoutHandler timeouts", true); public SocketTimeoutTask(Runnable actualTask) { this.actualTask = actualTask; } /** * <p>Enables or disables the timeout entirely. This may be useful if you want to store the timeout value but wish * to temporarily disable/enable timeouts.</p> * * <p>The default is for timeoutEnabled to be true but timeout to be set to {@link Duration#ZERO} (ie disabled).</p> * * <p>This call will reset the current progress towards the timeout.</p> */ @Override public synchronized final void setTimeoutEnabled(boolean timeoutEnabled) { this.timeoutEnabled = timeoutEnabled; resetTimeout(); } /** * <p>Sets the receive timeout, automatically killing the connection if no * messages are received for this long</p> * * <p>A timeout of {@link Duration#ZERO} is interpreted as no timeout.</p> * * <p>The default is for timeoutEnabled to be true but timeout to be set to {@link Duration#ZERO} (ie disabled).</p> * * <p>This call will reset the current progress towards the timeout.</p> */ @Override public synchronized final void setSocketTimeout(Duration timeout) { this.timeout = timeout; resetTimeout(); } /** * Resets the current progress towards timeout to 0. * @deprecated This will be made private once {@link AbstractTimeoutHandler} is removed. */ @Deprecated synchronized void resetTimeout() { if (timeoutTask != null) timeoutTask.cancel(); if (timeout.isZero() || !timeoutEnabled) return; // TimerTasks are not reusable, so we create a new one each time timeoutTask = timerTask(actualTask); timeoutTimer.schedule(timeoutTask, timeout.toMillis()); } // Create TimerTask from Runnable private static TimerTask timerTask(Runnable r) { return new TimerTask() { @Override public void run() { r.run(); } }; } }
3,350
33.90625
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/discovery/package-info.java
/* * Copyright by the original author or authors. * * 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. */ /** * Classes that know how to discover peers in the P2P network using DNS or HTTP. */ package org.bitcoinj.net.discovery;
738
35.95
80
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/discovery/MultiplexingDiscovery.java
/* * Copyright 2014 Mike Hearn * Copyright 2015 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. */ package org.bitcoinj.net.discovery; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Services; import org.bitcoinj.core.VersionMessage; import org.bitcoinj.net.discovery.DnsDiscovery.DnsSeedDiscovery; import org.bitcoinj.utils.ContextPropagatingThreadFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetSocketAddress; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import static org.bitcoinj.base.BitcoinNetwork.REGTEST; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** * MultiplexingDiscovery queries multiple PeerDiscovery objects, optionally shuffles their responses and then returns the results, * thus selecting randomly between them and reducing the influence of any particular seed. Any that don't respond * within the timeout are ignored. Backends are queried in parallel or serially. Backends may block. */ public class MultiplexingDiscovery implements PeerDiscovery { private static final Logger log = LoggerFactory.getLogger(MultiplexingDiscovery.class); protected final List<PeerDiscovery> seeds; protected final NetworkParameters netParams; private volatile ExecutorService vThreadPool; private final boolean parallelQueries; private final boolean shufflePeers; /** * Builds a suitable set of peer discoveries. Will query them in parallel before producing a merged response. * @param params Network to use. * @param services Required services as a bitmask, e.g. {@link Services#NODE_NETWORK}. */ public static MultiplexingDiscovery forServices(NetworkParameters params, long services) { return forServices(params, services, true, true); } /** * Builds a suitable set of peer discoveries. * @param params Network to use. * @param services Required services as a bitmask, e.g. {@link Services#NODE_NETWORK}. * @param parallelQueries When true, seeds are queried in parallel * @param shufflePeers When true, queried peers are shuffled */ public static MultiplexingDiscovery forServices(NetworkParameters params, long services, boolean parallelQueries, boolean shufflePeers) { List<PeerDiscovery> discoveries = new ArrayList<>(); String[] dnsSeeds = params.getDnsSeeds(); if (dnsSeeds != null) for (String dnsSeed : dnsSeeds) discoveries.add(new DnsSeedDiscovery(params, dnsSeed)); return new MultiplexingDiscovery(params, discoveries, parallelQueries, shufflePeers); } /** * Will query the given seeds in parallel before producing a merged response. */ public MultiplexingDiscovery(NetworkParameters params, List<PeerDiscovery> seeds) { this(params, seeds, true, true); } private MultiplexingDiscovery(NetworkParameters params, List<PeerDiscovery> seeds, boolean parallelQueries, boolean shufflePeers) { checkArgument(!seeds.isEmpty() || params.network() == REGTEST); this.netParams = params; this.seeds = seeds; this.parallelQueries = parallelQueries; this.shufflePeers = shufflePeers; } @Override public List<InetSocketAddress> getPeers(final long services, final Duration timeout) throws PeerDiscoveryException { vThreadPool = createExecutor(); try { List<Callable<List<InetSocketAddress>>> tasks = new ArrayList<>(); if (parallelQueries) { for (final PeerDiscovery seed : seeds) { tasks.add(() -> seed.getPeers(services, timeout)); } } else { tasks.add(() -> { List<InetSocketAddress> peers = new LinkedList<>(); for (final PeerDiscovery seed : seeds) peers.addAll(seed.getPeers(services, timeout)); return peers; }); } final List<Future<List<InetSocketAddress>>> futures = vThreadPool.invokeAll(tasks, timeout.toMillis(), TimeUnit.MILLISECONDS); List<InetSocketAddress> addrs = new ArrayList<>(); for (int i = 0; i < futures.size(); i++) { Future<List<InetSocketAddress>> future = futures.get(i); if (future.isCancelled()) { log.warn("Seed {}: timed out", parallelQueries ? seeds.get(i) : "any"); continue; // Timed out. } final List<InetSocketAddress> inetAddresses; try { inetAddresses = future.get(); } catch (ExecutionException e) { log.warn("Seed {}: failed to look up: {}", parallelQueries ? seeds.get(i) : "any", e.getMessage()); continue; } addrs.addAll(inetAddresses); } if (addrs.size() == 0) throw new PeerDiscoveryException("No peer discovery returned any results in " + timeout.toMillis() + " ms. Check internet connection?"); if (shufflePeers) Collections.shuffle(addrs); vThreadPool.shutdownNow(); return addrs; } catch (InterruptedException e) { throw new PeerDiscoveryException(e); } finally { vThreadPool.shutdown(); } } protected ExecutorService createExecutor() { return Executors.newFixedThreadPool(seeds.size(), new ContextPropagatingThreadFactory("Multiplexing discovery")); } @Override public void shutdown() { ExecutorService tp = vThreadPool; if (tp != null) tp.shutdown(); } }
6,738
41.383648
138
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/discovery/SeedPeers.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.net.discovery; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.core.NetworkParameters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * SeedPeers stores a pre-determined list of Bitcoin node addresses. These nodes are selected based on being * active on the network for a long period of time. The intention is to be a last resort way of finding a connection * to the network, in case IRC and DNS fail. The list comes from the Bitcoin C++ source code. */ public class SeedPeers implements PeerDiscovery { private final List<InetSocketAddress> seedAddrs; private int pnseedIndex; private static final Logger log = LoggerFactory.getLogger(SeedPeers.class); /** * Supports finding peers by IP addresses/ports * * @param seedAddrs IP addresses/ports of seeds. */ public SeedPeers(InetSocketAddress[] seedAddrs) { this.seedAddrs = Arrays.asList(seedAddrs); } /** * Supports finding peers by IP addresses * * @param params Network parameters to be used for port information. * @deprecated use {@link SeedPeers#SeedPeers(InetSocketAddress[])} */ @Deprecated public SeedPeers(NetworkParameters params) { this(params.getAddrSeeds(), params); } /** * Supports finding peers by IP addresses * * @param seedAddrInts IP addresses for seed addresses. * @param params Network parameters to be used for port information. * @deprecated use {@link SeedPeers#SeedPeers(InetSocketAddress[])} */ @Deprecated public SeedPeers(int[] seedAddrInts, NetworkParameters params) { this.seedAddrs = new LinkedList<>(); if (seedAddrInts == null) return; for (int seedAddrInt : seedAddrInts) { try { InetSocketAddress seedAddr = new InetSocketAddress(convertAddress(seedAddrInt), params.getPort()); this.seedAddrs.add(seedAddr); } catch (UnknownHostException x) { // swallow } } } /** * Acts as an iterator, returning the address of each node in the list sequentially. * Once all the list has been iterated, null will be returned for each subsequent query. * * @return InetSocketAddress - The address/port of the next node. */ @Nullable public InetSocketAddress getPeer() { return nextPeer(); } @Nullable private InetSocketAddress nextPeer() { if (pnseedIndex >= seedAddrs.size()) return null; return seedAddrs.get(pnseedIndex++); } /** * Returns all the Bitcoin nodes within the list. * * @param services ignored * @param timeout ignored * @return the pre-determined list of peers */ @Override public List<InetSocketAddress> getPeers(long services, Duration timeout) { if (services != 0) log.info("Pre-determined peers cannot be filtered by services: {}", services); return Collections.unmodifiableList(seedAddrs); } @Override public void shutdown() { } private static InetAddress convertAddress(int seed) throws UnknownHostException { byte[] v4addr = ByteBuffer.allocate(4).putInt(seed).array(); // Big-Endian return InetAddress.getByAddress(v4addr); } }
4,281
32.193798
116
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/discovery/PeerDiscovery.java
/* * Copyright 2011 John Sample. * Copyright 2015 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. */ package org.bitcoinj.net.discovery; import org.bitcoinj.core.Services; import org.bitcoinj.core.VersionMessage; import java.net.InetSocketAddress; import java.time.Duration; import java.util.List; import java.util.concurrent.TimeUnit; /** * A PeerDiscovery object is responsible for finding addresses of other nodes in the Bitcoin P2P network. Note that * the addresses returned may or may not be accepting connections. */ public interface PeerDiscovery { // TODO: Flesh out this interface a lot more. /** * Queries for addresses. This method may block. * @param services required services as a bitmask, e.g. {@link Services#NODE_NETWORK} * @param timeout query timeout * @return found addresses */ List<InetSocketAddress> getPeers(long services, Duration timeout) throws PeerDiscoveryException; /** * @deprecated use {@link #getPeers(long, Duration)} */ @Deprecated default List<InetSocketAddress> getPeers(long services, long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException { return getPeers(services, Duration.ofMillis(timeoutUnit.toMillis(timeoutValue))); } /** Stops any discovery in progress when we want to shut down quickly. */ void shutdown(); }
1,894
34.092593
132
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/discovery/DnsDiscovery.java
/* * Copyright 2011 John Sample * 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. */ package org.bitcoinj.net.discovery; import org.bitcoinj.base.internal.PlatformUtils; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Services; import org.bitcoinj.core.VersionMessage; import org.bitcoinj.utils.ContextPropagatingThreadFactory; import org.bitcoinj.utils.DaemonThreadFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * <p>Supports peer discovery through DNS.</p> * * <p>Failure to resolve individual host names will not cause an Exception to be thrown. * However, if all hosts passed fail to resolve a PeerDiscoveryException will be thrown during getPeers(). * </p> * * <p>DNS seeds do not attempt to enumerate every peer on the network. {@link DnsDiscovery#getPeers(long, long, TimeUnit)} * will return up to 30 random peers from the set of those returned within the timeout period. If you want more peers * to connect to, you need to discover them via other means (like addr broadcasts).</p> */ public class DnsDiscovery extends MultiplexingDiscovery { private static final Logger log = LoggerFactory.getLogger(DnsDiscovery.class); /** * Supports finding peers through DNS A records. Community run DNS entry points will be used. * * @param netParams Network parameters to be used for port information. */ public DnsDiscovery(NetworkParameters netParams) { this(netParams.getDnsSeeds(), netParams); } /** * Supports finding peers through DNS A records. * * @param dnsSeeds Host names to be examined for seed addresses. * @param params Network parameters to be used for port information. */ public DnsDiscovery(String[] dnsSeeds, NetworkParameters params) { super(params, buildDiscoveries(params, dnsSeeds)); } private static List<PeerDiscovery> buildDiscoveries(NetworkParameters params, String[] seeds) { List<PeerDiscovery> discoveries = new ArrayList<>(); if (seeds != null) for (String seed : seeds) discoveries.add(new DnsSeedDiscovery(params, seed)); return discoveries; } @Override protected ExecutorService createExecutor() { // Attempted workaround for reported bugs on Linux in which gethostbyname does not appear to be properly // thread safe and can cause segfaults on some libc versions. if (PlatformUtils.isLinux()) return Executors.newSingleThreadExecutor(new ContextPropagatingThreadFactory("DNS seed lookups")); else return Executors.newFixedThreadPool(seeds.size(), new DaemonThreadFactory("DNS seed lookups")); } /** Implements discovery from a single DNS host. */ public static class DnsSeedDiscovery implements PeerDiscovery { private final String hostname; private final NetworkParameters params; public DnsSeedDiscovery(NetworkParameters params, String hostname) { this.hostname = hostname; this.params = params; } @Override public List<InetSocketAddress> getPeers(long services, Duration timeout) throws PeerDiscoveryException { InetAddress[] response = null; if (services != 0) { String hostnameWithServices = "x" + Long.toHexString(services) + "." + hostname; log.info("Requesting {} peers from {}", Services.of(services).toString(), hostnameWithServices); try { response = InetAddress.getAllByName(hostnameWithServices); log.info("Got {} peers from {}", response.length, hostnameWithServices); } catch (UnknownHostException e) { log.info("Seed {} doesn't appear to support service bit filtering: {}", hostname, e.getMessage()); } } if (response == null || response.length == 0) { log.info("Requesting all peers from {}", hostname); try { response = InetAddress.getAllByName(hostname); log.info("Got {} peers from {}", response.length, hostname); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } List<InetSocketAddress> result = new ArrayList<>(response.length); for (InetAddress r : response) result.add(new InetSocketAddress(r, params.getPort())); return result; } @Override public void shutdown() { } @Override public String toString() { return hostname; } } }
5,561
39.014388
122
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/net/discovery/PeerDiscoveryException.java
/* * Copyright 2011 Google Inc. * * 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. */ package org.bitcoinj.net.discovery; public class PeerDiscoveryException extends Exception { private static final long serialVersionUID = -2863411151549391392L; public PeerDiscoveryException() { super(); } public PeerDiscoveryException(String message) { super(message); } public PeerDiscoveryException(Throwable arg0) { super(arg0); } public PeerDiscoveryException(String message, Throwable arg0) { super(message, arg0); } }
1,092
27.763158
75
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/AppDataDirectory.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.utils; import org.bitcoinj.base.internal.PlatformUtils; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; /** * Find/create App Data Directory in correct platform-specific location. * This class is based on the conventions used in Bitcoin Core which * uses the following locations: * <dl> * <dt>Windows</dt><dd>{@code ${APPDATA}/.bitcoin}</dd> * <dt>macOS</dt><dd>{@code ${HOME}/Library/Application Support/Bitcoin}</dd> * <dt>Linux</dt><dd>{@code ${HOME}/.bitcoin}</dd> * </dl> * Note that {@code appName} is converted to lower-case on Windows and Linux/Unix. */ public class AppDataDirectory { /** * Get and create if necessary the Path to the application data directory. * * @param appName The name of the current application * @return Path to the application data directory */ public static Path get(String appName) { final Path applicationDataDirectory = getPath(appName); try { Files.createDirectories(applicationDataDirectory); } catch (IOException ioe) { throw new RuntimeException("Couldn't find/create AppDataDirectory", ioe); } return applicationDataDirectory; } /** * Return the Path to the application data directory without making * sure it exists or creating it. (No disk I/O) * * @param appName The name of the current application * @return Path to the application data directory */ public static Path getPath(String appName) { final Path applicationDataDirectory; if (PlatformUtils.isWindows()) { applicationDataDirectory = pathOf(System.getenv("APPDATA"), appName.toLowerCase()); } else if (PlatformUtils.isMac()) { applicationDataDirectory = pathOf(System.getProperty("user.home"),"Library/Application Support", appName); } else if (PlatformUtils.isLinux()) { applicationDataDirectory = pathOf(System.getProperty("user.home"), "." + appName.toLowerCase()); } else { // Unknown, assume unix-like applicationDataDirectory = pathOf(System.getProperty("user.home"), "." + appName.toLowerCase()); } return applicationDataDirectory; } /** * Create a {@code Path} by joining path strings. Same functionality as Path.of() in JDK 11+ * @param first A base path string * @param additional additional components to add * @return the joined {@code Path} */ private static Path pathOf(String first, String... additional) { return FileSystems.getDefault().getPath(first, additional); } }
3,329
36
118
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/BtcFormat.java
/* * Copyright 2014 Adam Mackler * * 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. */ package org.bitcoinj.utils; import com.google.common.base.Strings; import org.bitcoinj.base.Coin; import org.bitcoinj.utils.BtcAutoFormat.Style; import java.math.BigDecimal; import java.math.BigInteger; import java.text.AttributedCharacterIterator; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.FieldPosition; import java.text.Format; import java.text.NumberFormat; import java.text.ParseException; import java.text.ParsePosition; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.math.RoundingMode.HALF_UP; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; import static org.bitcoinj.utils.BtcAutoFormat.Style.CODE; import static org.bitcoinj.utils.BtcAutoFormat.Style.SYMBOL; /** * <p>Instances of this class format and parse locale-specific numerical * representations of Bitcoin monetary values.</p> * * <p>A primary goal of this class is to minimize the danger of * human-misreading of monetary values due to mis-counting the number * of zeros (or, more generally, of decimal places) in the number that * represents a Bitcoin monetary value. Some of the features offered for doing this * are:</p> * * <ol> * <li>automatic adjustment of denominational units in which a * value is represented so as to lessen the number of adjacent zeros, * <li>use of locale-specific decimal-separators to group digits in * the integer portion of formatted numbers, * <li>fine control over the number and grouping of fractional decimal places, and * <li>access to character information that allows for vertical * alignment of tabular columns of formatted values.</ol> * * <h2>Basic Usage</h2> * * <p>Basic usage is very simple:</p> * * <ol> * <li>Construct a new formatter object using one of the factory methods. * <li>Format a value by passing it as an argument to the * {@link BtcFormat#format(Object)} method. * <li>Parse a value by passing a {@code String}-type * representation of it to the {@link BtcFormat#parse(String)} method.</ol> * * <p>For example, depending on your locale, values might be formatted * and parsed as follows:</p> * * <blockquote><pre> * BtcFormat f = BtcFormat.getInstance(); * String c = f.format(Coin.COIN); <strong>// "BTC 1.00"</strong> * String k = f.format(Coin.COIN.multiply(1000)); <strong>// "BTC 1,000.00"</strong> * String m = f.format(Coin.COIN.divide(1000)); <strong>// "mBTC 1.00"</strong> * Coin all = f.parseObject("M฿ 21"); <strong>// All the money in the world</strong> * </pre></blockquote> * * <h2>Auto-Denomination versus Fixed-Denomination</h2> * * <p>There are two provided concrete classes, one that automatically denominates values to * be formatted, {@link BtcAutoFormat}, and another that formats any value in units of a * fixed, specified denomination, {@link BtcFixedFormat}.</p> * * <h3>Automatic Denomination</h3> * * <p>Automatic denomination means that the formatter adjusts the denominational units in which a * formatted number is expressed based on the monetary value that number represents. An * auto-denominating formatter is defined by its style, specified by one of the enumerated * values of {@link BtcAutoFormat.Style}. There are two styles constants: {@link * BtcAutoFormat.Style#CODE} (the default), and {@link BtcAutoFormat.Style#SYMBOL}. The * difference is that the {@code CODE} style uses an internationally-distinct currency * code, such as {@code "BTC"}, to indicate the units of denomination, while the * {@code SYMBOL} style uses a possibly-ambiguous currency symbol such as * {@code "฿"}.</p> * * <p>The denomination used when formatting will be either bitcoin, millicoin * or microcoin, depending on the value being represented, chosen so as to minimize the number * of consecutive zeros displayed without losing precision. For example, depending on the * locale, a value of one bitcoin might be formatted as {@code ฿1.00} where a value * exceeding that by one satoshi would be {@code µ฿1,000,000.01}</p> * * <h3>Fixed Denomination</h3> * * <p>Fixed denomination means that the same denomination of units is used for every value that is * formatted or parsed by a given formatter instance. A fixed-denomination formatter is * defined by its scale, which is the number of places one must shift the decimal point in * increasing precision to convert the representation of a given quantity of bitcoins into a * representation of the same value denominated in the formatter's units. For example, a scale * value of {@code 3} specifies a denomination of millibitcoins, because to represent * {@code 1.0000 BTC}, or one bitcoin, in millibitcoins, one shifts the decimal point * three places, that is, to {@code 1000.0 mBTC}.</p> * * <h2>Construction</h2> * * <p>There are two ways to obtain an instance of this class:</p> * * <ol> * <li>Use one of the factory methods; or * <li>Use a {@link BtcFormat.Builder} object.</ol> * * <p>The factory methods are appropriate for basic use where the default * configuration is either used or modified. The {@link Builder} * class provides more control over the configuration, and gives * access to some features not available through the factory methods, * such as using custom formatting patterns and currency symbols.</p> * * <h3>Factory Methods</h3> * * <p>Although formatting and parsing is performed by one of the concrete * subclasses, you can obtain formatters using the various static factory * methods of this abstract base class {@link BtcFormat}. There * are a variety of overloaded methods that allow you to obtain a * formatter that behaves according to your needs.</p> * * <p>The primary distinction is between automatic- and * fixed-denomination formatters. By default, the * {@code getInstance()} method with no arguments returns a new, * automatic-denominating {@link BtcAutoFormat} instance for your * default locale that will display exactly two fractional decimal * places and a currency code. For example, if you happen to be in * the USA:</p> * * <blockquote><pre> * BtcFormat f = BtcFormat.getInstance(); * String s = f.format(Coin.COIN); <strong>// "BTC 1.00"</strong> * </pre></blockquote> * * <p>The first argument to {@code getInstance()} can determine * whether you get an auto- or fixed-denominating formatter. If the * type of the first argument is an {@code int}, then the value * of that {@code int} will be interpreted as the decimal-place scale of * the {@link BtcFixedFormat} instance that is returned, and thus will * determine its denomination. For example, if you want to format * values in units of microbitcoins:</p> * * <blockquote><pre>BtcFormat m = BtcFormat.getInstance(6); * String s = m.format(Coin.COIN); <strong>// "1,000,000.00"</strong> * </pre></blockquote> * * <p>This class provides several constants bound to common scale values:</p> * * <blockquote><pre>BtcFormat milliFormat = BtcFormat.getInstance(MILLICOIN_SCALE);</pre></blockquote> * * <p>Alternatively, if the type of the first argument to * {@code getInstance()} is one of the enumerated values of the * {@link BtcAutoFormat.Style} type, either {@link BtcAutoFormat.Style#CODE} or * {@link BtcAutoFormat.Style#SYMBOL}, then you will get a {@link BtcAutoFormat} * instance that uses either a currency code or symbol, respectively, * to indicate the results of its auto-denomination.</p> * * <blockquote><pre> * BtcFormat s = BtcFormat.getInstance(SYMBOL); * Coin value = Coin.parseCoin("0.1234"); * String mil = s.format(value); <strong>// "₥฿123.40"</strong> * String mic = s.format(value.divide(1000)); <strong>// "µ฿123.40"</strong> * </pre></blockquote> * * <p>An alternative way to specify whether you want an auto- or fixed-denomination formatter * is to use one of the factory methods that is named to indicate that characteristics of the * new instance returned. For fixed-denomination formatters, these methods are {@link * #getCoinInstance()}, {@link #getMilliInstance()}, and {@link #getMicroInstance()}. These * three methods are equivalent to invoking {@code getInstance()} with a first argument of * {@code 0}, {@code 3} and {@code 6}, respectively. For auto-denominating * formatters the relevant factory methods are {@link #getCodeInstance()} and {@link * #getSymbolInstance()}, which are equivalent to {@code getInstance(Style.CODE)}, and * {@code getInstance(Style.SYMBOL)}.</p> * * <p>Regardless of how you specify whether your new formatter is to be of automatic- or * fixed-denomination, the next (and possibly first) parameter to each of the factory methods * is an optional {@link Locale} value.</p> * * <p>For example, here we construct four instances for the same locale that each format * differently the same one-bitcoin value:</p> * * <blockquote><pre> * <strong>// Next line returns "1,00 BTC"</strong> * BtcFormat.getInstance(Locale.GERMANY).format(Coin.COIN); * <strong>// Next line returns "1,00 ฿"</strong> * BtcFormat.getInstance(SYMBOL, Locale.GERMANY).format(Coin.COIN); * <strong>// Next line returns "1.000,00"</strong> * BtcFormat.getMilliInstance(Locale.GERMANY).format(Coin.COIN); * <strong>// Next line returns "10.000,00"</strong> * BtcFormat.getInstance(4, Locale.GERMANY).format(Coin.COIN); * </pre></blockquote> * * <p>Omitting such a {@link Locale} parameter will give you a * formatter for your default locale.</p> * * <p>The final (and possibly only) arguments to the factory methods serve to set the default * number of fractional decimal places that will be displayed when formatting monetary values. * In the case of an auto-denominating formatter, this can be a single {@code int} value, * which will determine the number of fractional decimal places to be used in all cases, except * where either (1) doing so would provide a place for fractional satoshis, or (2) that default * value is overridden when invoking the {@code format()} method as described below.</p> * * <p>In the case of a fixed-denomination formatter, you can pass any number of * {@code int} values. The first will determine the minimum number of fractional decimal * places, and each following {@code int} value specifies the size of an optional group of * decimal-places to be displayed only if useful for expressing precision. As with auto-denominating * formatters, numbers will never be formatted with a decimal place that represents a * fractional quantity of satoshis, and these defaults can be overridden by arguments to the * {@code format()} method. See below for examples.</p> * * <h3>The {@link Builder} Class</h3> * * <p>A new {@link BtcFormat.Builder} instance is returned by the {@link #builder()} method. Such * an object has methods that set the configuration parameters of a {@link BtcFormat} * object. Its {@link Builder#build()} method constructs and returns a {@link BtcFormat} instance * configured according to those settings.</p> * * <p>In addition to setter-methods that correspond to the factory-method parameters explained * above, a {@link Builder} also allows you to specify custom formatting and parsing * patterns and currency symbols and codes. For example, rather than using the default * currency symbol, which has the same unicode character point as the national currency symbol of * Thailand, some people prefer to use a capital letter "B" with a vertical overstrike.</p> * * <blockquote><pre> * BtcFormat.Builder builder = BtcFormat.builder(); * builder.style(SYMBOL); * builder.symbol("B&#x5c;u20e6"); <strong>// unicode char "double vertical stroke overlay"</strong> * BtcFormat f = builder.build(); * String out = f.format(COIN); <strong>// "B⃦1.00" depending on locale</strong> * </pre></blockquote> * * The {@link Builder} methods are chainable. So, for example, if you are * deferential to ISO 4217, you might construct a formatter in a single line this way: * * <blockquote><pre> * BtcFormat f = BtcFormat.builder().style(CODE).code("XBT").build(); * String out = f.format(COIN); <strong>// "XBT 1.00"</strong> * </pre></blockquote> * * <p>See the documentation of the {@link BtcFormat.Builder} class for details.</p> * * <h2>Formatting</h2> * * <p>You format a Bitcoin monetary value by passing it to the {@link BtcFormat#format(Object)} * method. This argument can be either a {@link Coin}-type object or a * numerical object such as {@link Long} or {@link BigDecimal}. * Integer-based types such as {@link BigInteger} are interpreted as representing a * number of satoshis, while a {@link BigDecimal} is interpreted as representing a * number of bitcoins. A value having a fractional amount of satoshis is rounded to the * nearest whole satoshi at least, and possibly to a greater unit depending on the number of * fractional decimal-places displayed. The {@code format()} method will not accept an * argument whose type is {@link String}, {@link Float} nor {@link Double}.</p> * * <p>Subsequent to the monetary value to be formatted, the {@link #format(Object)} method also * accepts as arguments optional {@code int} values that specify the number of decimal * places to use to represent the fractional portion of the number. This overrides the * default, and enables a single formatter instance to be reused, formatting different values * that require different numbers of fractional decimal places. These parameters have the same * meaning as those that set the default values in the factory methods as described above. * Namely, a single {@code int} value determines the minimum number of fractional decimal * places that will be used in all cases, to a precision limit of satoshis. Instances of * {@link BtcFixedFormat} also accept a variable-length sequence of additional {@code int} * values, each of which specifies the size of a group of fractional decimal-places to be used * in addition to all preceding places, only if useful to express precision, and only to a * maximum precision of satoshis. For example:</p> * * <blockquote><pre> * BtcFormat f = BtcFormat.getCoinInstance(); * Coin value = COIN.add(Coin.valueOf(5)); <strong>// 100000005 satoshis</strong> * f.format(value, 2); <strong>// "1.00"</strong> * f.format(value, 3); <strong>// "1.000"</strong> * f.format(value, 2, 3); <strong>// "1.00" three more zeros doesn't help </strong> * f.format(value, 2, 3, 3); <strong>// "1.00000005" </strong> * f.format(value, 2, 3, 4); <strong>// "1.00000005" fractions of satoshis have no place</strong> * f.format(value, 2, 3, 2); <strong>// "1.0000001" rounds to nearest usable place</strong> * </pre></blockquote> * * <p>Note that if using all the fractional decimal places in a specified group would give a * place to fractions of satoshis, then the size of that group will be reduced to a maximum * precision of satoshis. Either all or none of the allowed decimal places of that group will * still be applied as doing so is useful for expressing the precision of the value being * formatted.</p> * * <p>Several convenient constants of repeating group-size sequences are provided: * {@link BtcFixedFormat#REPEATING_PLACES}, {@link * BtcFixedFormat#REPEATING_DOUBLETS} and {@link * BtcFixedFormat#REPEATING_TRIPLETS}. These signify repeating groups * of one, two and three decimals places, respectively. For example, * to display only as many fractional places as useful in order to * prevent hanging zeros on the least-significant end of formatted * numbers:</p> * * <blockquote><pre> * format(value, 0, REPEATING_PLACES); * </pre></blockquote> * * <p>When using an automatically-denominating formatter, you might * want to know what denomination was chosen. You can get the * currency-units indicator, as well as any other field in the * formatted output, by using a {@link FieldPosition} instance * constructed using an appropriate constant from the {@link * NumberFormat.Field} class:</p> * * <blockquote><pre> * BtcFormat de = BtcFormat.getInstance(Locale.GERMANY); * FieldPosition currField = new FieldPosition(NumberFormat.Field.CURRENCY); * <strong>// next line formats the value as "987.654.321,23 µBTC"</strong> * String output = de.format(valueOf(98765432123L), new StringBuffer(), currField); * <strong>// next line sets variable currencyCode to "µBTC"</strong> * String currencyCode = output.substring(currField.getBeginIndex(), currField.getEndIndex())); * </pre></blockquote> * * <p>When using a fixed-denomination formatter whose scale can be expressed as a standard * "metric" prefix, you can invoke the {@code code()} and {@code symbol()} methods to * obtain a {@link String} whose value is the appropriate currency code or symbol, * respectively, for that formatter.</p> * * <blockquote><pre> * BtcFixedFormat kilo = (BtcFixedFormat)BtcFormat(-3); <strong>// scale -3 for kilocoins</strong> * Coin value = Coin.parseCoin("1230"); * <strong>// variable coded will be set to "kBTC 1.23"</strong> * String coded = kilo.code() + " " + kilo.format(value); * <strong>// variable symbolic will be set to "k฿1.23"</strong> * String symbolic = kilo.symbol() + kilo.format(value); * BtcFormat(4).code(); <strong>// unnamed denomination has no code; raises exception</strong> * </pre></blockquote> * * <h3>Formatting for Tabular Columns</h3> * * <p>When displaying tables of monetary values, you can lessen the * risk of human misreading-error by vertically aligning the decimal * separator of those values. This example demonstrates one way to do that:</p> * * <blockquote><pre> * <strong>// The elements of this array are the values we will format:</strong> * Coin[] rows = {MAX_MONEY, MAX_MONEY.subtract(SATOSHI), Coin.parseCoin("1234"), * COIN, COIN.divide(1000), * valueOf(10000), valueOf(1000), valueOf(100), * SATOSHI}; * BtcFormat f = BtcFormat.getCoinInstance(2, REPEATING_PLACES); * FieldPosition fp = new FieldPosition(DECIMAL_SEPARATOR); <strong>// see java.text.NumberFormat.Field</strong> * String[] output = new String[rows.length]; * int[] indexes = new int[rows.length]; * int maxIndex = 0; * for (int i = 0; i &lt; rows.length; i++) { * output[i] = f.format(rows[i], new StringBuffer(), fp).toString(); * indexes[i] = fp.getBeginIndex(); * if (indexes[i] &gt; maxIndex) maxIndex = indexes[i]; * } * for (int i = 0; i &lt; output.length; i++) { * System.out.println(repeat(" ", (maxIndex - indexes[i])) + output[i]); * } * </pre></blockquote> * * Assuming you are using a monospaced font, and depending on your * locale, the foregoing will print the following: * * <blockquote><pre> * 21,000,000.00 * 20,999,999.99999999 * 1,234.00 * 1.00 * 0.001 * 0.0001 * 0.00001 * 0.000001 * 0.00000001 * </pre></blockquote> * * <p>If you need to vertically-align columns printed in a proportional font, * then see the documentation for the {@link NumberFormat} class * for an explanation of how to do that.</p> * * <h2>Parsing</h2> * * <p>The {@link #parse(String)} method accepts a {@link String} argument, and returns a * {@link Coin}-type value. The difference in parsing behavior between instances of {@link * BtcFixedFormat} and {@link BtcAutoFormat} is analogous to the difference in formatting * behavior between instances of those classes. Instances of {@link BtcAutoFormat} recognize * currency codes and symbols in the {@link String} being parsed, and interpret them as * indicators of the units in which the number being parsed is denominated. On the other hand, * instances of {@link BtcFixedFormat} by default recognize no codes nor symbols, but rather * interpret every number as being denominated in the units that were specified when * constructing the instance doing the parsing. This default behavior of {@link * BtcFixedFormat} can be overridden by setting a parsing pattern that includes a currency sign * using the {@link BtcFormat.Builder#pattern()} method.</p> * * <p>The {@link BtcAutoFormat#parse(String)} method of {@link BtcAutoFormat} (and of * {@link BtcAutoFormat} configured with applicable non-default pattern) will recognize a * variety of currency symbols and codes, including all standard international (metric) * prefixes from micro to mega. For example, denominational units of microcoins may be * specified by {@code µ฿}, {@code u฿}, {@code µB⃦}, {@code µɃ}, * {@code µBTC} or other appropriate permutations of those characters. Additionally, if * either or both of a custom currency code or symbol is configured using {@link * BtcFormat.Builder#code} or {@link BtcFormat.Builder#code}, then such code or symbol will * be recognized in addition to those recognized by default.</p> * * <p>Instances of this class that recognize currency signs will recognize both currency * symbols and codes, regardless of which that instance uses for formatting. However, if the * style is {@code CODE} (and unless overridden by a custom pattern) then a space character must * separate the units indicator from the number. When parsing with a {@code SYMBOL}-style * {@code BtcFormat} instance, on the other hand, whether or not the units indicator must * be separated by a space from the number is determined by the locale. The {@link * BtcFormat#pattern()} method returns a representation of the pattern that * can be examined to determine whether a space must separate currency signs from numbers in * parsed {@link String}s.</p> * * <p>When parsing, if the currency-units indicator is absent, then a {@link BtcAutoFormat} * instance will infer a denomination of bitcoins while a {@link BtcFixedFormat} will infer the * denomination in which it expresses formatted values. Note: by default (unless overridden by * a custom pattern), if the locale or style requires a space to separate the number from the * units indicator, that space must be present in the String to be parsed, even if the units * indicator is absent.</p> * * <p>The {@code parse()} method returns an instance of the * {@link Coin} class. Therefore, attempting to parse a value greater * than the maximum that a {@code Coin} object can represent will * raise a {@code ParseException}, as will any other detected * parsing error.</p> * * <h2>Limitations</h2> * * <h3>Parsing</h3> * * <p>Parsing is performed by an underlying {@link NumberFormat} object. While this * delivers the benefit of recognizing locale-specific patterns, some have criticized other * aspects of its behavior. For example, see <a * href="http://www.ibm.com/developerworks/library/j-numberformat/">this article by Joe Sam * Shirah</a>. In particular, explicit positive-signs are not recognized. If you are parsing * input from end-users, then you should consider whether you would benefit from any of the * work-arounds mentioned in that article.</p> * * <h3>Exotic Locales</h3> * * <p>This class is not well-tested in locales that use non-ascii * character sets, especially those where writing proceeds from * right-to-left. Helpful feedback in that regard is appreciated.</p> * * <h2>Thread-Safety</h2> * * <p>Instances of this class are immutable.</p> * * @see Format * @see NumberFormat * @see DecimalFormat * @see DecimalFormatSymbols * @see FieldPosition * @see Coin */ public abstract class BtcFormat extends Format { /* CONCURRENCY NOTES * * There is one mutable member of this class, the `DecimalFormat` object bound to variable * `numberFormat`. The relevant methods invoked on it are: setMinimumFractionDigits(), * setMaximumFractionDigits(), and setDecimalFormatSymbols(), along with the respective * getter methods corresponding to each. The first two methods are used to set the number * of fractional decimal places displayed when formatting, which is reflected in the * patterns returned by the public pattern() and localizedPattern() methods. The last * method sets the value of that object's member `DecimalFormatSymbols` object for * formatting and parsing, which is also reflected in the aforementioned patterns. The * patterns, which are the passed-through return values of the DecimalFormat object's * toPattern() and toLocalizedPattern() methods, and the value of the DecimalFormat * object's DecimalFormatSymbols member are among the values compared between instances of * this class in determining the return values of the `equals()` and `hashCode()` methods. * * From the foregoing, you can understand that immutability is achieved as follows: access * to the variable `numberFormat` referent's fraction-digits and format-symbols fields are * synchronized on that DecimalFormat object. The state of those fraction-digits limits * and decimal-format symbols must be returned to a static state after being changed for * formatting or parsing since the user can see them reflected in the return values of * above-mentioned methods and because `equals()` and `hashCode()` use them for * comparisons. */ /** The conventional international currency code for bitcoins: "BTC" */ private static final String COIN_CODE = "BTC"; /** The default currency symbols for bitcoins */ private static final String COIN_SYMBOL = "฿"; /** An alternative currency symbol to use in locales where the default symbol is used for the national currency. */ protected static final String COIN_SYMBOL_ALT = "Ƀ"; protected final DecimalFormat numberFormat; // warning: mutable protected final int minimumFractionDigits; protected final List<Integer> decimalGroups; /* Scale is the number of decimal-places difference from same value in bitcoins */ /** A constant useful for specifying a denomination of bitcoins, the {@code int} value * {@code 0}. */ public static final int COIN_SCALE = 0; /** A constant useful for specifying a denomination of millibitcoins, the {@code int} * value {@code 3}. */ public static final int MILLICOIN_SCALE = 3; /** A constant useful for specifying a denomination of microbitcoins, the {@code int} * value {@code 6}. */ public static final int MICROCOIN_SCALE = 6; /** Return the number of decimal places by which any value denominated in the * units indicated by the given scale differs from that same value denominated in satoshis */ private static int offSatoshis(int scale) { return Coin.SMALLEST_UNIT_EXPONENT - scale; } private static Locale defaultLocale() { return Locale.getDefault(); } /** * <p>This class constructs new instances of {@link BtcFormat}, allowing for the * configuration of those instances before they are constructed. After obtaining a * {@code Builder} object from the {@link BtcFormat#builder()} method, invoke the * necessary setter methods to obtain your desired configuration. Finally, the {@link * #build()} method returns a new {@code BtcFormat} object that has the specified * configuration. * * <p>All the setter methods override defaults. Invoking {@code build()} without invoking any * of the setting methods is equivalent to invoking {@link BtcFormat#getInstance()} with no arguments. * * <p>Each setter methods returns the same instance on which it is invoked, * thus these methods can be chained. * * <p>Instances of this class are <strong>not</strong> thread-safe. */ public static class Builder { private enum Variant { AUTO { @Override BtcFormat newInstance(Builder b) { return getInstance(b.style, b.locale, b.minimumFractionDigits); }}, FIXED, UNSET; BtcFormat newInstance(Builder b) { return getInstance(b.scale, b.locale, b.minimumFractionDigits, b.fractionGroups); } } // Parameters are initialized to default or unset values private Variant variant = Variant.UNSET; private Locale locale = defaultLocale(); private int minimumFractionDigits = 2; private int[] fractionGroups = {}; private Style style = BtcAutoFormat.Style.CODE; private int scale = 0; private String symbol = "",code = "",pattern = "",localizedPattern = ""; private Builder() {} /** Specify the new {@code BtcFormat} is to be automatically-denominating. * The argument determines which of either codes or symbols the new {@code BtcFormat} * will use by default to indicate the denominations it chooses when formatting values. * * <p>Note that the {@code Style} argument specifies the * <em>default</em> style, which is overridden by invoking * either {@link #pattern(String)} or {@link #localizedPattern(String)}. * * @throws IllegalArgumentException if {@link #scale(int)} has * previously been invoked on this instance.*/ public Builder style(BtcAutoFormat.Style val) { if (variant == Variant.FIXED) throw new IllegalStateException("You cannot invoke both style() and scale()"); variant = Variant.AUTO; style = val; return this; } /** Specify the number of decimal places in the fraction part of formatted numbers. * This is equivalent to the {@link #minimumFractionDigits(int)} method, but named * appropriately for the context of generating {@link BtcAutoFormat} instances. * * <p>If neither this method nor {@code minimumFactionDigits()} is invoked, the default value * will be {@code 2}. */ public Builder fractionDigits(int val) { return minimumFractionDigits(val); } /** Specify a fixed-denomination of units to use when formatting and parsing values. * The argument specifies the number of decimal places, in increasing * precision, by which each formatted value will differ from that same value * denominated in bitcoins. For example, a denomination of millibitcoins is specified * with a value of {@code 3}. * * <p>The {@code BtcFormat} class provides appropriately named * {@code int}-type constants for the three common values, {@link BtcFormat#COIN_SCALE}, * {@link BtcFormat#MILLICOIN_SCALE} {@link BtcFormat#MICROCOIN_SCALE}. * * <p>If neither this method nor {@link #style(BtcAutoFormat.Style)} is invoked on a * {@link Builder}, then the {@link BtcFormat} will default to a * fixed-denomination of bitcoins, equivalent to invoking this method with an argument * of {@code 0}. */ public Builder scale(int val) { if (variant == Variant.AUTO) throw new IllegalStateException("You cannot invoke both scale() and style()"); variant = Variant.FIXED; scale = val; return this; } /** Specify the minimum number of decimal places in the fraction part of formatted values. * This method is equivalent to {@link #fractionDigits(int)}, but named appropriately for * the context of generating a fixed-denomination formatter. * * <p>If neither this method nor {@code fractionDigits()} is invoked, the default value * will be {@code 2}. */ public Builder minimumFractionDigits(int val) { minimumFractionDigits = val; return this; } /** Specify the sizes of a variable number of optional decimal-place groups in the * fraction part of formatted values. A group of each specified size will be used in * addition to all previously applied decimal places only if doing so is useful for * expressing precision. The size of each group is limited to a maximum precision of * satoshis. * * <p>If this method is not invoked, then the number of fractional decimal places will * be limited to the value passed to {@link #minimumFractionDigits}, or {@code 2} * if that method is not invoked. */ public Builder fractionGroups(int... val) { fractionGroups = val; return this; } /** Specify the {@link Locale} for formatting and parsing. * If this method is not invoked, then the runtime default locale will be used. */ public Builder locale(Locale val) { locale = val; return this; } /** Specify a currency symbol to be used in the denomination-unit indicators * of formatted values. This method only sets the symbol, but does not cause * it to be used. You must also invoke either {@code style(SYMBOL)}, or else apply * a custom pattern that includes a single currency-sign character by invoking either * {@link #pattern(String)} or {@link #localizedPattern(String)}. * * <p>Specify only the base symbol. The appropriate prefix will be applied according * to the denomination of formatted and parsed values. */ public Builder symbol(String val) { symbol = val; return this; } /** Specify a custom currency code to be used in the denomination-unit indicators * of formatted values. This method only sets the code, but does not cause * it to be used. You must also invoke either {@code style(CODE)}, or else apply * a custom pattern that includes a double currency-sign character by invoking either * {@link #pattern(String)} or {@link #localizedPattern(String)}. * * <p>Specify only the base code. The appropriate prefix will be applied according * to the denomination of formatted and parsed values. */ public Builder code(String val) { code = val; return this; } /** Use the given pattern when formatting and parsing. The format of this pattern is * identical to that used by the {@link DecimalFormat} class. * * <p>If the pattern lacks a negative subpattern, then the formatter will indicate * negative values by placing a minus sign immediately preceding the number part of * formatted values. * * <p>Note that while the pattern format specified by the {@link * java.text.DecimalFormat} class includes a mechanism for setting the number of * fractional decimal places, that part of the pattern is ignored. Instead, use the * {@link #fractionDigits(int)}, {@link #minimumFractionDigits(int)} and {@link * #fractionGroups(int...)} methods. * * <p>Warning: if you set a pattern that includes a currency-sign for a * fixed-denomination formatter that uses a non-standard scale, then an exception will * be raised when you try to format a value. The standard scales include all for * which a metric prefix exists from micro to mega. * * <p>Note that by applying a pattern you override the configured formatting style of * {@link BtcAutoFormat} instances. */ public Builder pattern(String val) { if (!Strings.isNullOrEmpty(localizedPattern)) throw new IllegalStateException("You cannot invoke both pattern() and localizedPattern()"); pattern = val; return this; } /** Use the given localized-pattern for formatting and parsing. The format of this * pattern is identical to the patterns used by the {@link DecimalFormat} * class. * * <p>The pattern is localized according to the locale of the {@code BtcFormat} * instance, the symbols for which can be examined by inspecting the {@link * java.text.DecimalFormatSymbols} object returned by {@link BtcFormat#symbols()}. * So, for example, if you are in Germany, then the non-localized pattern of * <pre>"#,##0.###"</pre> would be localized as <pre>"#.##0,###"</pre> * * <p>If the pattern lacks a negative subpattern, then the formatter will indicate * negative values by placing a minus sign immediately preceding the number part of * formatted values. * * <p>Note that while the pattern format specified by the {@link * java.text.DecimalFormat} class includes a mechanism for setting the number of * fractional decimal places, that part of the pattern is ignored. Instead, use the * {@link #fractionDigits(int)}, {@link #minimumFractionDigits(int)} and {@link * #fractionGroups(int...)} methods. * * <p>Warning: if you set a pattern that includes a currency-sign for a * fixed-denomination formatter that uses a non-standard scale, then an exception will * be raised when you try to format a value. The standard scales include all for * which a metric prefix exists from micro to mega. * * <p>Note that by applying a pattern you override the configured formatting style of * {@link BtcAutoFormat} instances. */ public Builder localizedPattern(String val) { if (!Strings.isNullOrEmpty(pattern)) throw new IllegalStateException("You cannot invoke both pattern() and localizedPattern()."); localizedPattern = val; return this; } /** Return a new {@link BtcFormat} instance. The object returned will be configured according * to the state of this {@code Builder} instance at the time this method is invoked. */ public BtcFormat build() { BtcFormat f = variant.newInstance(this); if (!Strings.isNullOrEmpty(symbol) || !Strings.isNullOrEmpty(code)) { synchronized(f.numberFormat) { DecimalFormatSymbols defaultSigns = f.numberFormat.getDecimalFormatSymbols(); setSymbolAndCode(f.numberFormat, !Strings.isNullOrEmpty(symbol) ? symbol : defaultSigns.getCurrencySymbol(), !Strings.isNullOrEmpty(code) ? code : defaultSigns.getInternationalCurrencySymbol() ); }} if (!Strings.isNullOrEmpty(localizedPattern) || !Strings.isNullOrEmpty(pattern)) { int places = f.numberFormat.getMinimumFractionDigits(); if (!Strings.isNullOrEmpty(localizedPattern)) f.numberFormat.applyLocalizedPattern(negify(localizedPattern)); else f.numberFormat.applyPattern(negify(pattern)); f.numberFormat.setMinimumFractionDigits(places); f.numberFormat.setMaximumFractionDigits(places); } return f; } } /** Return a new {@link Builder} object. See the documentation of that class for usage details. */ public static Builder builder() { return new Builder(); } /** This single constructor is invoked by the overriding subclass constructors. */ protected BtcFormat(DecimalFormat numberFormat, int minDecimals, List<Integer> groups) { checkArgument(minDecimals >= 0, () -> "there can be no fewer than zero fractional decimal places"); this.numberFormat = numberFormat; this.numberFormat.setParseBigDecimal(true); this.numberFormat.setRoundingMode(HALF_UP); this.minimumFractionDigits = minDecimals; this.numberFormat.setMinimumFractionDigits(this.minimumFractionDigits); this.numberFormat.setMaximumFractionDigits(this.minimumFractionDigits); this.decimalGroups = groups; synchronized (this.numberFormat) { setSymbolAndCode( this.numberFormat, (this.numberFormat.getDecimalFormatSymbols().getCurrencySymbol().contains(COIN_SYMBOL)) ? COIN_SYMBOL_ALT : COIN_SYMBOL, COIN_CODE );} } /** * Return a new instance of this class using all defaults. The returned formatter will * auto-denominate values so as to minimize zeros without loss of precision and display a * currency code, for example "{@code BTC}", to indicate that denomination. The * returned object will uses the default locale for formatting the number and placement of * the currency-code. Two fractional decimal places will be displayed in all formatted numbers. */ public static BtcFormat getInstance() { return getInstance(defaultLocale()); } /** * Return a new auto-denominating instance that will indicate units using a currency * symbol, for example, {@code "฿"}. Formatting and parsing will be done * according to the default locale. */ public static BtcFormat getSymbolInstance() { return getSymbolInstance(defaultLocale()); } /** * Return a new auto-denominating instance that will indicate units using a currency * code, for example, {@code "BTC"}. Formatting and parsing will be done * according to the default locale. */ public static BtcFormat getCodeInstance() { return getCodeInstance(defaultLocale()); } /** * Return a new symbol-style auto-formatter with the given number of fractional decimal * places. Denominational units will be indicated using a currency symbol, for example, * {@code "฿"}. The returned object will format the fraction-part of numbers using * the given number of decimal places, or fewer as necessary to avoid giving a place to * fractional satoshis. Formatting and parsing will be done according to the default * locale. */ public static BtcFormat getSymbolInstance(int fractionPlaces) { return getSymbolInstance(defaultLocale(), fractionPlaces); } /** * Return a new code-style auto-formatter with the given number of fractional decimal * places. Denominational units will be indicated using a currency code, for example, * {@code "BTC"}. The returned object will format the fraction-part of numbers using * the given number of decimal places, or fewer as necessary to avoid giving a place to * fractional satoshis. Formatting and parsing will be done according to the default * locale. */ public static BtcFormat getCodeInstance(int minDecimals) { return getCodeInstance(defaultLocale(), minDecimals); } /** * Return a new code-style auto-formatter for the given locale. The returned object will * select denominational units based on each value being formatted, and will indicate those * units using a currency code, for example, {@code "mBTC"}. */ public static BtcFormat getInstance(Locale locale) { return getCodeInstance(locale); } /** * Return a new code-style auto-formatter for the given locale. The returned object will * select denominational units based on each value being formatted, and will indicate those * units using a currency code, for example, {@code "mBTC"}. */ public static BtcFormat getCodeInstance(Locale locale) { return getInstance(CODE, locale); } /** * Return a new code-style auto-formatter for the given locale with the given number of * fraction places. The returned object will select denominational units based on each * value being formatted, and will indicate those units using a currency code, for example, * {@code "mBTC"}. The returned object will format the fraction-part of numbers using * the given number of decimal places, or fewer as necessary to avoid giving a place to * fractional satoshis. */ public static BtcFormat getInstance(Locale locale, int minDecimals) { return getCodeInstance(locale, minDecimals); } /** * Return a new code-style auto-formatter for the given locale with the given number of * fraction places. The returned object will select denominational units based on each * value being formatted, and will indicate those units using a currency code, for example, * {@code "mBTC"}. The returned object will format the fraction-part of numbers using * the given number of decimal places, or fewer as necessary to avoid giving a place to * fractional satoshis. */ public static BtcFormat getCodeInstance(Locale locale, int minDecimals) { return getInstance(CODE, locale, minDecimals); } /** * Return a new symbol-style auto-formatter for the given locale. The returned object will * select denominational units based on each value being formatted, and will indicate those * units using a currency symbol, for example, {@code "µ฿"}. */ public static BtcFormat getSymbolInstance(Locale locale) { return getInstance(SYMBOL, locale); } /** * Return a new symbol-style auto-formatter for the given locale with the given number of * fraction places. The returned object will select denominational units based on each * value being formatted, and will indicate those units using a currency symbol, for example, * {@code "µ฿"}. The returned object will format the fraction-part of numbers using * the given number of decimal places, or fewer as necessary to avoid giving a place to * fractional satoshis. */ public static BtcFormat getSymbolInstance(Locale locale, int fractionPlaces) { return getInstance(SYMBOL, locale, fractionPlaces); } /** * Return a new auto-denominating formatter. The returned object will indicate the * denominational units of formatted values using either a currency symbol, such as, * {@code "฿"}, or code, such as {@code "mBTC"}, depending on the value of * the argument. Formatting and parsing will be done according to the default locale. */ public static BtcFormat getInstance(Style style) { return getInstance(style, defaultLocale()); } /** * Return a new auto-denominating formatter with the given number of fractional decimal * places. The returned object will indicate the denominational units of formatted values * using either a currency symbol, such as, {@code "฿"}, or code, such as * {@code "mBTC"}, depending on the value of the first argument. The returned object * will format the fraction-part of numbers using the given number of decimal places, or * fewer as necessary to avoid giving a place to fractional satoshis. Formatting and * parsing will be done according to the default locale. */ public static BtcFormat getInstance(Style style, int fractionPlaces) { return getInstance(style, defaultLocale(), fractionPlaces); } /** * Return a new auto-formatter with the given style for the given locale. * The returned object that will auto-denominate each formatted value, and * will indicate that denomination using either a currency code, such as * {@code "BTC"}, or symbol, such as {@code "฿"}, depending on the value * of the first argument. * <p>The number of fractional decimal places in formatted number will be two, or fewer * as necessary to avoid giving a place to fractional satoshis. */ public static BtcFormat getInstance(Style style, Locale locale) { return getInstance(style, locale, 2); } /** * Return a new auto-formatter for the given locale with the given number of fraction places. * The returned object will automatically-denominate each formatted * value, and will indicate that denomination using either a currency code, * such as {@code "mBTC"}, or symbol, such as {@code "฿"}, * according to the given style argument. It will format each number * according to the given locale. * * <p>The third parameter is the number of fractional decimal places to use for each * formatted number, reduced as necessary when formatting to avoid giving a place to * fractional satoshis. */ public static BtcFormat getInstance(Style style, Locale locale, int fractionPlaces) { return new BtcAutoFormat(locale, style, fractionPlaces); } /** * Return a new coin-denominated formatter. The returned object will format and parse * values according to the default locale, and will format numbers with two fractional * decimal places, rounding values as necessary. */ public static BtcFormat getCoinInstance() { return getCoinInstance(defaultLocale()); } private static List<Integer> boxAsList(int[] elements) throws IllegalArgumentException { List<Integer> list = new ArrayList<>(elements.length); for (int e : elements) { checkArgument(e > 0, () -> "size of decimal group must be at least one."); list.add(e); } return list; } /** * Return a new coin-denominated formatter with the specified fraction-places. The * returned object will format and parse values according to the default locale, and will * format the fraction part of numbers with at least two decimal places. The sizes of * additional groups of decimal places can be specified by a variable number of * {@code int} arguments. Each optional decimal-place group will be applied only if * useful for expressing precision, and will be only partially applied if necessary to * avoid giving a place to fractional satoshis. */ public static BtcFormat getCoinInstance(int minFractionPlaces, int... groups) { return getInstance(COIN_SCALE, defaultLocale(), minFractionPlaces, boxAsList(groups)); } /** * Return a new coin-denominated formatter for the given locale. The returned object will * format the fractional part of numbers with two decimal places, rounding as necessary. */ public static BtcFormat getCoinInstance(Locale locale) { return getInstance(COIN_SCALE, locale, 2); } /** * Return a newly-constructed instance for the given locale that will format * values in terms of bitcoins, with the given minimum number of fractional * decimal places. Optionally, repeating integer arguments can be passed, each * indicating the size of an additional group of fractional decimal places to be * used as necessary to avoid rounding, to a limiting precision of satoshis. */ public static BtcFormat getCoinInstance(Locale locale, int scale, int... groups) { return getInstance(COIN_SCALE, locale, scale, boxAsList(groups)); } /** * Return a new millicoin-denominated formatter. The returned object will format and * parse values for the default locale, and will format the fractional part of numbers with * two decimal places, rounding as necessary. */ public static BtcFormat getMilliInstance() { return getMilliInstance(defaultLocale()); } /** * Return a new millicoin-denominated formatter for the given locale. The returned object * will format the fractional part of numbers with two decimal places, rounding as * necessary. */ public static BtcFormat getMilliInstance(Locale locale) { return getInstance(MILLICOIN_SCALE, locale, 2); } /** * Return a new millicoin-denominated formatter with the specified fractional decimal * placing. The returned object will format and parse values according to the default * locale, and will format the fractional part of numbers with the given minimum number of * fractional decimal places. Optionally, repeating integer arguments can be passed, each * indicating the size of an additional group of fractional decimal places to be used as * necessary to avoid rounding, to a limiting precision of satoshis. */ public static BtcFormat getMilliInstance(int scale, int... groups) { return getInstance(MILLICOIN_SCALE, defaultLocale(), scale, boxAsList(groups)); } /** * Return a new millicoin-denominated formatter for the given locale with the specified * fractional decimal placing. The returned object will format the fractional part of * numbers with the given minimum number of fractional decimal places. Optionally, * repeating integer arguments can be passed, each indicating the size of an additional * group of fractional decimal places to be used as necessary to avoid rounding, to a * limiting precision of satoshis. */ public static BtcFormat getMilliInstance(Locale locale, int scale, int... groups) { return getInstance(MILLICOIN_SCALE, locale, scale, boxAsList(groups)); } /** * Return a new microcoin-denominated formatter for the default locale. The returned object * will format the fractional part of numbers with two decimal places, rounding as * necessary. */ public static BtcFormat getMicroInstance() { return getMicroInstance(defaultLocale()); } /** * Return a new microcoin-denominated formatter for the given locale. The returned object * will format the fractional part of numbers with two decimal places, rounding as * necessary. */ public static BtcFormat getMicroInstance(Locale locale) { return getInstance(MICROCOIN_SCALE, locale); } /** * Return a new microcoin-denominated formatter with the specified fractional decimal * placing. The returned object will format and parse values according to the default * locale, and will format the fractional part of numbers with the given minimum number of * fractional decimal places. Optionally, repeating integer arguments can be passed, each * indicating the size of an additional group of fractional decimal places to be used as * necessary to avoid rounding, to a limiting precision of satoshis. */ public static BtcFormat getMicroInstance(int scale, int... groups) { return getInstance(MICROCOIN_SCALE, defaultLocale(), scale, boxAsList(groups)); } /** * Return a new microcoin-denominated formatter for the given locale with the specified * fractional decimal placing. The returned object will format the fractional part of * numbers with the given minimum number of fractional decimal places. Optionally, * repeating integer arguments can be passed, each indicating the size of an additional * group of fractional decimal places to be used as necessary to avoid rounding, to a * limiting precision of satoshis. */ public static BtcFormat getMicroInstance(Locale locale, int scale, int... groups) { return getInstance(MICROCOIN_SCALE, locale, scale, boxAsList(groups)); } /** * Return a new fixed-denomination formatter with the specified fractional decimal * placing. The first argument specifies the denomination as the size of the * shift from coin-denomination in increasingly-precise decimal places. The returned object will format * and parse values according to the default locale, and will format the fractional part of * numbers with the given minimum number of fractional decimal places. Optionally, * repeating integer arguments can be passed, each indicating the size of an additional * group of fractional decimal places to be used as necessary to avoid rounding, to a * limiting precision of satoshis. */ public static BtcFormat getInstance(int scale, int minDecimals, int... groups) { return getInstance(scale, defaultLocale(), minDecimals, boxAsList(groups)); } /** * Return a new fixed-denomination formatter. The argument specifies the denomination as * the size of the shift from coin-denomination in increasingly-precise decimal places. * The returned object will format and parse values according to the default locale, and * will format the fractional part of numbers with two decimal places, or fewer as * necessary to avoid giving a place to fractional satoshis. */ public static BtcFormat getInstance(int scale) { return getInstance(scale, defaultLocale()); } /** * Return a new fixed-denomination formatter for the given locale. The first argument * specifies the denomination as the size of the shift from coin-denomination in * increasingly-precise decimal places. The returned object will format and parse values * according to the locale specified by the second argument, and will format the fractional * part of numbers with two decimal places, or fewer as necessary to avoid giving a place * to fractional satoshis. */ public static BtcFormat getInstance(int scale, Locale locale) { return getInstance(scale, locale, 2); } /** * Return a new fixed-denomination formatter for the given locale, with the specified * fractional decimal placing. The first argument specifies the denomination as the size * of the shift from coin-denomination in increasingly-precise decimal places. The third * parameter is the minimum number of fractional decimal places to use, followed by * optional repeating integer parameters each specifying the size of an additional group of * fractional decimal places to use as necessary to avoid rounding, down to a maximum * precision of satoshis. */ public static BtcFormat getInstance(int scale, Locale locale, int minDecimals, int... groups) { return getInstance(scale, locale, minDecimals, boxAsList(groups)); } /** * Return a new fixed-denomination formatter for the given locale, with the specified * fractional decimal placing. The first argument specifies the denomination as the size * of the shift from coin-denomination in increasingly-precise decimal places. The third * parameter is the minimum number of fractional decimal places to use. The third argument * specifies the minimum number of fractional decimal places in formatted numbers. The * last argument is a {@code List} of {@link Integer} values, each of which * specifies the size of an additional group of fractional decimal places to use as * necessary to avoid rounding, down to a maximum precision of satoshis. */ public static BtcFormat getInstance(int scale, Locale locale, int minDecimals, List<Integer> groups) { return new BtcFixedFormat(locale, scale, minDecimals, groups); } // ****** FORMATTING ***** /** * Formats a bitcoin monetary value and returns an {@link AttributedCharacterIterator}. * By iterating, you can examine what fields apply to each character. This can be useful * since a character may be part of more than one field, for example a grouping separator * that is also part of the integer field. * * @see AttributedCharacterIterator */ @Override public AttributedCharacterIterator formatToCharacterIterator(Object obj) { synchronized(numberFormat) { DecimalFormatSymbols anteSigns = numberFormat.getDecimalFormatSymbols(); BigDecimal units = denominateAndRound(inSatoshis(obj), minimumFractionDigits, decimalGroups); List<Integer> anteDigits = setFormatterDigits(numberFormat, units.scale(), units.scale()); AttributedCharacterIterator i = numberFormat.formatToCharacterIterator(units); numberFormat.setDecimalFormatSymbols(anteSigns); setFormatterDigits(numberFormat, anteDigits.get(0), anteDigits.get(1)); return i; }} /** * Formats a bitcoin value as a number and possibly a units indicator and appends the * resulting text to the given string buffer. The type of monetary value argument can be * any one of any of the following classes: {@link Coin}, * {@link Integer}, {@link Long}, {@link BigInteger}, * {@link BigDecimal}. Numeric types that can represent only an integer are interpreted * as that number of satoshis. The value of a {@link BigDecimal} is interpreted as that * number of bitcoins, rounded to the nearest satoshi as necessary. * * @return the {@link StringBuffer} passed in as {@code toAppendTo} */ @Override public StringBuffer format(Object qty, StringBuffer toAppendTo, FieldPosition pos) { return format(qty, toAppendTo, pos, minimumFractionDigits, decimalGroups); } /** * Formats a bitcoin value as a number and possibly a units indicator to a * {@link String}.The type of monetary value argument can be any one of any of the * following classes: {@link Coin}, {@link Integer}, {@link Long}, * {@link BigInteger}, {@link BigDecimal}. Numeric types that can represent only * an integer are interpreted as that number of satoshis. The value of a * {@link BigDecimal} is interpreted as that number of bitcoins, rounded to the * nearest satoshi as necessary. * * @param minDecimals The minimum number of decimal places in the fractional part of the formatted number * @param fractionGroups The sizes of optional additional fractional decimal-place groups * @throws IllegalArgumentException if the number of fraction places is negative. */ public String format(Object qty, int minDecimals, int... fractionGroups) { return format(qty, new StringBuffer(), new FieldPosition(0), minDecimals, boxAsList(fractionGroups)).toString(); } /** * Formats a bitcoin value as a number and possibly a units indicator and appends the * resulting text to the given string buffer. The type of monetary value argument can be * any one of any of the following classes: {@link Coin}, * {@link Integer}, {@link Long}, {@link BigInteger}, * {@link BigDecimal}. Numeric types that can represent only an integer are interpreted * as that number of satoshis. The value of a {@link BigDecimal} is interpreted as that * number of bitcoins, rounded to the nearest satoshi as necessary. * * @param minDecimals The minimum number of decimal places in the fractional part of the formatted number * @param fractionGroups The sizes of optional additional fractional decimal-place groups * @throws IllegalArgumentException if the number of fraction places is negative. */ public StringBuffer format(Object qty, StringBuffer toAppendTo, FieldPosition pos, int minDecimals, int... fractionGroups) { return format(qty, toAppendTo, pos, minDecimals, boxAsList(fractionGroups)); } private StringBuffer format(Object qty, StringBuffer toAppendTo, FieldPosition pos, int minDecimals, List<Integer> fractionGroups) { checkArgument(minDecimals >= 0, () -> "there can be no fewer than zero fractional decimal places"); synchronized (numberFormat) { DecimalFormatSymbols anteSigns = numberFormat.getDecimalFormatSymbols(); BigDecimal denominatedUnitCount = denominateAndRound(inSatoshis(qty), minDecimals, fractionGroups); List<Integer> antePlaces = setFormatterDigits(numberFormat, denominatedUnitCount.scale(), denominatedUnitCount.scale()); StringBuffer s = numberFormat.format(denominatedUnitCount, toAppendTo, pos); numberFormat.setDecimalFormatSymbols(anteSigns); setFormatterDigits(numberFormat, antePlaces.get(0), antePlaces.get(1)); return s; } } /** * Return the denomination for formatting the given value. The returned {@code int} * is the size of the decimal-place shift between the given Bitcoin-value denominated in * bitcoins and that same value as formatted. A fixed-denomination formatter will ignore * the arguments. * * @param satoshis The number of satoshis having the value for which the shift is calculated * @param fractionPlaces The number of decimal places available for displaying the fractional part of the denominated value * @return The size of the shift in increasingly-precise decimal places */ protected abstract int scale(BigInteger satoshis, int fractionPlaces); /** Return the denomination of this object. Fixed-denomination formatters will override * with their configured denomination, auto-formatters with coin denomination. This * determines the interpretation of parsed numbers lacking a units-indicator. */ protected abstract int scale(); /** * Takes a bitcoin monetary value that the client wants to format and returns the number of * denominational units having the equal value, rounded to the appropriate number of * decimal places. Calls the scale() method of the subclass, which may have the * side-effect of changing the currency symbol and code of the underlying `NumberFormat` * object, therefore only invoke this from a synchronized method that resets the NumberFormat. */ private BigDecimal denominateAndRound(BigInteger satoshis, int minDecimals, List<Integer> fractionGroups) { int scale = scale(satoshis, minDecimals); BigDecimal denominatedUnitCount = new BigDecimal(satoshis).movePointLeft(offSatoshis(scale)); int places = calculateFractionPlaces(denominatedUnitCount, scale, minDecimals, fractionGroups); return denominatedUnitCount.setScale(places, HALF_UP); } /** Sets the number of fractional decimal places to be displayed on the given * NumberFormat object to the value of the given integer. * @return The minimum and maximum fractional places settings that the * formatter had before this change, as an unmodifiable List. */ private static List<Integer> setFormatterDigits(DecimalFormat formatter, int min, int max) { List<Integer> ante = Collections.unmodifiableList( Arrays.asList( formatter.getMinimumFractionDigits(), formatter.getMaximumFractionDigits() ) ); formatter.setMinimumFractionDigits(min); formatter.setMaximumFractionDigits(max); return ante; } /** Return the number of fractional decimal places to be displayed when formatting * the given number of monetary units of the denomination indicated by the given decimal scale value, * where 0 = coin, 3 = millicoin, and so on. * * @param unitCount the number of monetary units to be formatted * @param scale the denomination of those units as the decimal-place shift from coins * @param minDecimals the minimum number of fractional decimal places * @param fractionGroups the sizes of option fractional decimal-place groups */ private static int calculateFractionPlaces( BigDecimal unitCount, int scale, int minDecimals, List<Integer> fractionGroups) { /* Taking into account BOTH the user's preference for decimal-place groups, AND the prohibition * against displaying a fractional number of satoshis, determine the maximum possible number of * fractional decimal places. */ int places = minDecimals; for (int group : fractionGroups) { places += group; } int max = Math.min(places, offSatoshis(scale)); places = Math.min(minDecimals,max); for (int group : fractionGroups) { /* Compare the value formatted using only this many decimal places to the * same value using as many places as possible. If there's no difference, then * there's no reason to continue adding more places. */ if (unitCount.setScale(places, HALF_UP).compareTo(unitCount.setScale(max, HALF_UP)) == 0) break; places += group; if (places > max) places = max; } return places; } /** * Takes an object representing a bitcoin quantity of any type the * client is permitted to pass us, and return a BigInteger representing the * number of satoshis having the equivalent value. */ private static BigInteger inSatoshis(Object qty) { BigInteger satoshis; // the value might be bitcoins or satoshis if (qty instanceof Long || qty instanceof Integer) satoshis = BigInteger.valueOf(((Number)qty).longValue()); else if (qty instanceof BigInteger) satoshis = (BigInteger)qty; else if (qty instanceof BigDecimal) satoshis = ((BigDecimal)qty).movePointRight(Coin.SMALLEST_UNIT_EXPONENT). setScale(0,BigDecimal.ROUND_HALF_UP).unscaledValue(); else if (qty instanceof Coin) satoshis = BigInteger.valueOf(((Coin)qty).value); else throw new IllegalArgumentException("Cannot format a " + qty.getClass().getSimpleName() + " as a Bicoin value"); return satoshis; } // ****** PARSING ***** /** * Parse a {@link String} representation of a Bitcoin monetary value. Returns a * {@link Coin} object that represents the parsed value. * @see NumberFormat */ @Override public final Object parseObject(String source, ParsePosition pos) { return parse(source, pos); } private static class ScaleMatcher { public Pattern pattern; public int scale; ScaleMatcher(Pattern p, int s) { pattern = p; scale = s; } } /* Lazy initialization; No reason to create all these objects unless needed for parsing */ // coin indicator regex String; TODO: does this need to be volatile? private volatile String ci = "(" + COIN_SYMBOL + "|" + COIN_SYMBOL_ALT + "|B⃦|" + COIN_CODE + "|XBT)"; private Pattern coinPattern; private volatile ScaleMatcher[] denoms; ScaleMatcher[] denomMatchers() { ScaleMatcher[] result = denoms; if (result == null) { synchronized(this) { result = denoms; if (result == null) { if (! coinSymbol().matches(ci)) ci = ci.replaceFirst("\\(", "(" + coinSymbol() + "|"); if (! coinCode().matches(ci)) { ci = ci.replaceFirst("\\)", "|" + coinCode() + ")"); } coinPattern = Pattern.compile(ci + "?"); result = denoms = new ScaleMatcher[]{ new ScaleMatcher(Pattern.compile("¢" + ci + "?|c" + ci), 2), // centi new ScaleMatcher(Pattern.compile("₥" + ci + "?|m" + ci), MILLICOIN_SCALE), new ScaleMatcher(Pattern.compile("([µu]" + ci + ")"), MICROCOIN_SCALE), new ScaleMatcher(Pattern.compile("(da" + ci + ")"), -1), // deka new ScaleMatcher(Pattern.compile("(h" + ci + ")"), -2), // hekto new ScaleMatcher(Pattern.compile("(k" + ci + ")"), -3), // kilo new ScaleMatcher(Pattern.compile("(M" + ci + ")"), -6) // mega }; } }} return result; } /** Set both the currency symbol and international code of the underlying {@link * java.text.NumberFormat} object to the value of the given {@link String}. * This method is invoked in the process of parsing, not formatting. * * Only invoke this from code synchronized on the value of the first argument, and don't * forget to put the symbols back otherwise equals(), hashCode() and immutability will * break. */ private static DecimalFormatSymbols setSymbolAndCode(DecimalFormat numberFormat, String sign) { return setSymbolAndCode(numberFormat, sign, sign); } /** Set the currency symbol and international code of the underlying {@link * java.text.NumberFormat} object to the values of the last two arguments, respectively. * This method is invoked in the process of parsing, not formatting. * * Only invoke this from code synchronized on value of the first argument, and don't * forget to put the symbols back otherwise equals(), hashCode() and immutability will * break. */ private static DecimalFormatSymbols setSymbolAndCode(DecimalFormat numberFormat, String symbol, String code) { checkState(Thread.holdsLock(numberFormat)); DecimalFormatSymbols fs = numberFormat.getDecimalFormatSymbols(); DecimalFormatSymbols ante = (DecimalFormatSymbols)fs.clone(); fs.setInternationalCurrencySymbol(code); fs.setCurrencySymbol(symbol); numberFormat.setDecimalFormatSymbols(fs); return ante; } /** * Set both the currency symbol and code of the underlying, mutable NumberFormat object * according to the given denominational units scale factor. This is for formatting, not parsing. * * <p>Set back to zero when you're done formatting otherwise immutability, equals() and * hashCode() will break! * * @param scale Number of places the decimal point will be shifted when formatting * a quantity of satoshis. */ protected static void prefixUnitsIndicator(DecimalFormat numberFormat, int scale) { checkState(Thread.holdsLock(numberFormat)); // make sure caller intends to reset before changing DecimalFormatSymbols fs = numberFormat.getDecimalFormatSymbols(); setSymbolAndCode(numberFormat, prefixSymbol(fs.getCurrencySymbol(), scale), prefixCode(fs.getInternationalCurrencySymbol(), scale) ); } /** Parse a {@link String} representation of a Bitcoin monetary value. If this * object's pattern includes a currency sign, either symbol or code, as by default is true * for instances of {@link BtcAutoFormat} and false for instances of {@link * BtcFixedFormat}, then denominated (i.e., prefixed) currency signs in the parsed String * will be recognized, and the parsed number will be interpreted as a quantity of units * having that recognized denomination. * <p>If the pattern includes a currency sign but no currency sign is detected in the parsed * String, then the number is interpreted as a quatity of bitcoins. * <p>If the pattern contains neither a currency symbol nor sign, then instances of {@link * BtcAutoFormat} will interpret the parsed number as a quantity of bitcoins, and instances * of {@link BtcAutoFormat} will interpret the number as a quantity of that instance's * configured denomination, which can be ascertained by invoking the {@link * BtcFixedFormat#symbol()} or {@link BtcFixedFormat#code()} method. * * <p>Consider using the single-argument version of this overloaded method unless you need to * keep track of the current parse position. * * @return a Coin object representing the parsed value * @see java.text.ParsePosition */ public Coin parse(String source, ParsePosition pos) { DecimalFormatSymbols anteSigns = null; int parseScale = COIN_SCALE; // default Coin coin = null; synchronized (numberFormat) { if (numberFormat.toPattern().contains("¤")) { for(ScaleMatcher d : denomMatchers()) { Matcher matcher = d.pattern.matcher(source); if (matcher.find()) { anteSigns = setSymbolAndCode(numberFormat, matcher.group()); parseScale = d.scale; break; } } if (parseScale == COIN_SCALE) { Matcher matcher = coinPattern.matcher(source); matcher.find(); anteSigns = setSymbolAndCode(numberFormat, matcher.group()); } } else parseScale = scale(); Number number = numberFormat.parse(source, pos); if (number != null) try { coin = Coin.valueOf( ((BigDecimal)number).movePointRight(offSatoshis(parseScale)).setScale(0, HALF_UP).longValue() ); } catch (IllegalArgumentException e) { pos.setIndex(0); } if (anteSigns != null) numberFormat.setDecimalFormatSymbols(anteSigns); } return coin; } /** Parse a {@link String} representation of a Bitcoin monetary value. If this * object's pattern includes a currency sign, either symbol or code, as by default is true * for instances of {@link BtcAutoFormat} and false for instances of {@link * BtcFixedFormat}, then denominated (i.e., prefixed) currency signs in the parsed String * will be recognized, and the parsed number will be interpreted as a quantity of units * having that recognized denomination. * <p>If the pattern includes a currency sign but no currency sign is detected in the parsed * String, then the number is interpreted as a quatity of bitcoins. * <p>If the pattern contains neither a currency symbol nor sign, then instances of {@link * BtcAutoFormat} will interpret the parsed number as a quantity of bitcoins, and instances * of {@link BtcAutoFormat} will interpret the number as a quantity of that instance's * configured denomination, which can be ascertained by invoking the {@link * BtcFixedFormat#symbol()} or {@link BtcFixedFormat#code()} method. * * @return a Coin object representing the parsed value */ public Coin parse(String source) throws ParseException { return (Coin)parseObject(source); } /****** END OF PARSING STUFF *****/ protected static String prefixCode(String code, int scale) { switch (scale) { case COIN_SCALE: return code; case 1: return "d" + code; case 2: return "c" + code; case MILLICOIN_SCALE: return "m" + code; case MICROCOIN_SCALE: return "µ" + code; case -1: return "da" + code; case -2: return "h" + code; case -3: return "k" + code; case -6: return "M" + code; default: throw new IllegalStateException("No known prefix for scale " + String.valueOf(scale)); } } protected static String prefixSymbol(String symbol, int scale) { switch (scale) { case COIN_SCALE: return symbol; case 1: return "d" + symbol; case 2: return "¢" + symbol; case MILLICOIN_SCALE: return "₥" + symbol; case MICROCOIN_SCALE: return "µ" + symbol; case -1: return "da" + symbol; case -2: return "h" + symbol; case -3: return "k" + symbol; case -6: return "M" + symbol; default: throw new IllegalStateException("No known prefix for scale " + String.valueOf(scale)); } } /** Guarantee a formatting pattern has a subpattern for negative values. This method takes * a pattern that may be missing a negative subpattern, and returns the same pattern with * a negative subpattern appended as needed. * * <p>This method accommodates an imperfection in the Java formatting code and distributed * locale data. To wit: the subpattern for negative numbers is optional and not all * locales have one. In those cases, {@link DecimalFormat} will indicate numbers * less than zero by adding a negative sign as the first character of the prefix of the * positive subpattern. * * <p>We don't like this, since we claim the negative sign applies to the number not the * units, and therefore it ought to be adjacent to the number, displacing the * currency-units indicator if necessary. */ protected static String negify(String pattern) { if (pattern.contains(";")) return pattern; else { if (pattern.contains("-")) throw new IllegalStateException("Positive pattern contains negative sign"); // the regex matches everything until the first non-quoted number character return pattern + ";" + pattern.replaceFirst("^([^#0,.']*('[^']*')?)*", "$0-"); } } /** * Return an array of all locales for which the getInstance() method of this class can * return localized instances. See {@link NumberFormat#getAvailableLocales()} */ public static Locale[] getAvailableLocales() { return NumberFormat.getAvailableLocales(); } /** Return the unprefixed currency symbol for bitcoins configured for this object. The * return value of this method is constant throughout the life of an instance. */ public String coinSymbol() { synchronized(numberFormat) { return numberFormat.getDecimalFormatSymbols().getCurrencySymbol(); }} /** Return the unprefixed international currency code for bitcoins configured for this * object. The return value of this method is constant throughough the life of an instance. */ public String coinCode() { synchronized(numberFormat) { return numberFormat.getDecimalFormatSymbols().getInternationalCurrencySymbol(); }} /** Return a representation of the pattern used by this instance for formatting and * parsing. The format is similar to, but not the same as the format recognized by the * {@link Builder#pattern} and {@link Builder#localizedPattern} methods. The pattern * returned by this method is localized, any currency signs expressed are literally, and * optional fractional decimal places are shown grouped in parentheses. */ public String pattern() { synchronized(numberFormat) { StringBuilder groups = new StringBuilder(); for (int group : decimalGroups) { groups.append("(").append(Strings.repeat("#", group)).append(")"); } DecimalFormatSymbols s = numberFormat.getDecimalFormatSymbols(); String digit = String.valueOf(s.getDigit()); String exp = s.getExponentSeparator(); String groupSep = String.valueOf(s.getGroupingSeparator()); String moneySep = String.valueOf(s.getMonetaryDecimalSeparator()); String zero = String.valueOf(s.getZeroDigit()); String boundary = String.valueOf(s.getPatternSeparator()); String minus = String.valueOf(s.getMinusSign()); String decSep = String.valueOf(s.getDecimalSeparator()); String prefixAndNumber = "(^|" + boundary+ ")" + "([^" + Matcher.quoteReplacement(digit + zero + groupSep + decSep + moneySep) + "']*('[^']*')?)*" + "[" + Matcher.quoteReplacement(digit + zero + groupSep + decSep + moneySep + exp) + "]+"; return numberFormat.toLocalizedPattern(). replaceAll(prefixAndNumber, "$0" + groups.toString()). replaceAll("¤¤", Matcher.quoteReplacement(coinCode())). replaceAll("¤", Matcher.quoteReplacement(coinSymbol())); }} /** Return a copy of the localized symbols used by this instance for formatting and parsing. */ public DecimalFormatSymbols symbols() { synchronized(numberFormat) { return numberFormat.getDecimalFormatSymbols(); }} /** Return true if the given object is equivalent to this one. * Formatters for different locales will never be equal, even * if they behave identically. */ @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof BtcFormat)) return false; BtcFormat other = (BtcFormat)o; return other.pattern().equals(pattern()) && other.symbols().equals(symbols()) && other.minimumFractionDigits == minimumFractionDigits; } /** Return a hash code value for this instance. * @see java.lang.Object#hashCode */ @Override public int hashCode() { return Objects.hash(pattern(), symbols(), minimumFractionDigits, decimalGroups); } }
85,200
52.283927
125
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/package-info.java
/* * 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. */ /** * Formatting monetary amounts, representing exchange rates, a program for loading Bitcoin Core saved block files, * a class to control how bitcoinj uses threads and misc other utility classes that don't fit anywhere else. */ package org.bitcoinj.utils;
821
42.263158
114
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/ContextPropagatingThreadFactory.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.utils; import org.bitcoinj.core.Context; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ThreadFactory; /** * A {@link ThreadFactory} that propagates a {@link Context} from the creating * thread into the new thread. This factory creates daemon threads. */ public class ContextPropagatingThreadFactory implements ThreadFactory { private static final Logger log = LoggerFactory.getLogger(ContextPropagatingThreadFactory.class); private final String name; private final int priority; public ContextPropagatingThreadFactory(String name, int priority) { this.name = name; this.priority = priority; } public ContextPropagatingThreadFactory(String name) { this(name, Thread.NORM_PRIORITY); } @Override public Thread newThread(final Runnable r) { final Context context = Context.get(); Thread thread = new Thread(() -> { try { Context.propagate(context); r.run(); } catch (Exception e) { log.error("Exception in thread", e); throw e; } }, name); thread.setPriority(priority); thread.setDaemon(true); Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler; if (handler != null) thread.setUncaughtExceptionHandler(handler); return thread; } }
2,076
31.968254
101
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/TaggableObject.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.utils; import com.google.protobuf.ByteString; import javax.annotation.Nullable; import java.util.Map; /** * <p>An object that can carry around and possibly serialize a map of strings to immutable byte arrays. Tagged objects * can have data stored on them that might be useful for an application developer. For example a wallet can store tags, * and thus this would be a reasonable place to put any important data items that the bitcoinj API does not allow for: * things like exchange rates at the time a transaction was made would currently fall into this category. Of course, * it helps interop and other developers if you introduce a real type safe API for a new feature instead of using this * so please consider that path, if you find yourself tempted to store tags!</p> * * <p>Good tag names won't conflict with other people's code, should you one day decide to merge them. Choose tag names * like "com.example:keyowner:02b7e6dc316dfaa19c5a599f63d88ffeae398759b857ca56b2f69de3e815381343" instead of * "owner" or just "o". Also, it's good practice to create constants for each string you use, to help avoid typos * in string parameters causing confusing bugs!</p> * @deprecated Applications should use another mechanism to persist application state data */ @Deprecated public interface TaggableObject { /** Returns the immutable byte array associated with the given tag name, or null if there is none. */ @Deprecated @Nullable ByteString maybeGetTag(String tag); /** * Returns the immutable byte array associated with the given tag name, or throws {@link IllegalArgumentException} * if that tag wasn't set yet. */ @Deprecated ByteString getTag(String tag); /** Associates the given immutable byte array with the string tag. See the docs for TaggableObject to learn more. */ @Deprecated void setTag(String tag, ByteString value); /** Returns a copy of all the tags held by this object. */ @Deprecated Map<String, ByteString> getTags(); }
2,658
44.067797
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/BtcFixedFormat.java
/* * Copyright 2014 Adam Mackler * * 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. */ package org.bitcoinj.utils; import org.bitcoinj.base.Coin; import java.math.BigInteger; import java.text.DecimalFormat; import java.text.Format; import java.text.NumberFormat; import java.util.List; import java.util.Locale; import java.util.Objects; import static org.bitcoinj.base.Coin.SMALLEST_UNIT_EXPONENT; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** * <p>This class, a concrete extension of {@link BtcFormat}, is distinguished in that each * instance formats and by-default parses all Bitcoin monetary values in units of a single * denomination that is specified at the time that instance is constructed.</p> * * <p>By default, neither currency codes nor symbols are included in formatted values as * output, nor recognized in parsed values as input. The can be overridden by applying a * custom pattern using either the {@link BtcFormat.Builder#localizedPattern} or * {@link BtcFormat.Builder#localizedPattern} methods, as described in the documentation for * the {@link BtcFormat.Builder} class.</p> * * <p>A more detailed explanation, including examples, is in the documentation for the * {@link BtcFormat} class, and further information beyond that is in the documentation for the * {@link Format} class, from which this class descends.</p> * @see Format * @see NumberFormat * @see DecimalFormat * @see Coin */ public final class BtcFixedFormat extends BtcFormat { /** A constant specifying the use of as many optional decimal places in the fraction part * of a formatted number as are useful for expressing precision. This value can be passed * as the final argument to a factory method or {@link #format(Object, int, int...)}. */ public static final int[] REPEATING_PLACES = {1,1,1,1,1,1,1,1,1,1,1,1,1,1}; /** A constant specifying the use of as many optional groups of <strong>two</strong> * decimal places in the fraction part of a formatted number as are useful for expressing * precision. This value can be passed as the final argument to a factory method or * {@link #format(Object, int, int...)}. */ public static final int[] REPEATING_DOUBLETS = {2,2,2,2,2,2,2}; /** A constant specifying the use of as many optional groups of <strong>three</strong> * decimal places in the fraction part of a formatted number as are useful for expressing * precision. This value can be passed as the final argument to a factory method or * {@link #format(Object, int, int...)}. */ public static final int[] REPEATING_TRIPLETS = {3,3,3,3,3}; /** The number of places the decimal point of formatted values is shifted rightward from * the same value expressed in bitcoins. */ private final int scale; /** Constructor */ protected BtcFixedFormat( Locale locale, int scale, int minDecimals, List<Integer> groups ) { super((DecimalFormat)NumberFormat.getInstance(locale), minDecimals, groups); checkArgument(scale <= SMALLEST_UNIT_EXPONENT, () -> "decimal cannot be shifted " + String.valueOf(scale) + " places"); this.scale = scale; } /** Return the decimal-place shift for this object's unit-denomination. For example, if * the denomination is millibitcoins, this method will return the value {@code 3}. As * a side-effect, prefixes the currency signs of the underlying NumberFormat object. This * method is invoked by the superclass when formatting. The arguments are ignored because * the denomination is fixed regardless of the value being formatted. */ @Override protected int scale(BigInteger satoshis, int fractionPlaces) { prefixUnitsIndicator(numberFormat, scale); return scale; } /** Return the decimal-place shift for this object's fixed unit-denomination. For example, if * the denomination is millibitcoins, this method will return the value {@code 3}. */ @Override public int scale() { return scale; } /** * Return the currency code that identifies the units in which values formatted and * (by-default) parsed by this instance are denominated. For example, if the formatter's * denomination is millibitcoins, then this method will return {@code "mBTC"}, * assuming the default base currency-code is not overridden using a * {@link BtcFormat.Builder}. */ public String code() { return prefixCode(coinCode(), scale); } /** * Return the currency symbol that identifies the units in which values formatted by this * instance are denominated. For example, when invoked on an instance denominated in * millibitcoins, this method by default returns {@code "₥฿"}, depending on the * locale. */ public String symbol() { return prefixSymbol(coinSymbol(), scale); } /** Return the fractional decimal-placing used when formatting. This method returns an * {@code int} array. The value of the first element is the minimum number of * decimal places to be used in all cases, limited to a precision of satoshis. The value * of each successive element is the size of an optional place-group that will be applied, * possibly partially, if useful for expressing precision. The actual size of each group * is limited to, and may be reduced to the limit of, a precision of no smaller than * satoshis. */ public int[] fractionPlaceGroups() { Object[] boxedArray = decimalGroups.toArray(); int len = boxedArray.length + 1; int[] array = new int[len]; array[0] = minimumFractionDigits; for (int i = 1; i < len; i++) { array[i] = (Integer) boxedArray[i-1]; } return array; } /** Return true if the given object is equivalent to this one. Formatters for different * locales will never be equal, even if they behave identically. */ @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof BtcFixedFormat)) return false; BtcFixedFormat other = (BtcFixedFormat)o; return super.equals(other) && other.scale() == scale() && other.decimalGroups.equals(decimalGroups); } /** Return a hash code value for this instance. * @see java.lang.Object#hashCode */ @Override public int hashCode() { return Objects.hash(super.hashCode(), scale); } private static String prefixLabel(int scale) { switch (scale) { case COIN_SCALE: return "Coin-"; case 1: return "Decicoin-"; case 2: return "Centicoin-"; case MILLICOIN_SCALE: return "Millicoin-"; case MICROCOIN_SCALE: return "Microcoin-"; case -1: return "Dekacoin-"; case -2: return "Hectocoin-"; case -3: return "Kilocoin-"; case -6: return "Megacoin-"; default: return "Fixed (" + String.valueOf(scale) + ") "; } } /** * Returns a brief description of this formatter. The exact details of the representation * are unspecified and subject to change, but will include some representation of the * formatting/parsing pattern and the fractional decimal place grouping. */ @Override public String toString() { return prefixLabel(scale) + "format " + pattern(); } }
7,992
44.158192
108
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/DaemonThreadFactory.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.utils; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; /** Thread factory whose threads are marked as daemon and won't prevent process exit. */ public class DaemonThreadFactory implements ThreadFactory { @Nullable private final String name; public DaemonThreadFactory(@Nullable String name) { this.name = name; } public DaemonThreadFactory() { this(null); } @Override public Thread newThread(@Nonnull Runnable runnable) { Thread thread = Executors.defaultThreadFactory().newThread(runnable); thread.setDaemon(true); if (name != null) thread.setName(name); return thread; } }
1,408
30.311111
88
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/BaseTaggableObject.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.utils; import com.google.protobuf.ByteString; import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * A simple implementation of {@link TaggableObject} that uses a hashmap that is * synchronized on this object's Java monitor. * @deprecated Applications should use another mechanism to persist application state data */ @Deprecated public class BaseTaggableObject implements TaggableObject { protected final Map<String, ByteString> tags = new HashMap<>(); @Override @Nullable @Deprecated public synchronized ByteString maybeGetTag(String tag) { return tags.get(tag); } @Override @Deprecated public ByteString getTag(String tag) { ByteString b = maybeGetTag(tag); if (b == null) throw new IllegalArgumentException("Unknown tag " + tag); return b; } @Override @Deprecated public synchronized void setTag(String tag, ByteString value) { // HashMap allows null keys and values, but we don't Objects.requireNonNull(tag); Objects.requireNonNull(value); tags.put(tag, value); } @Override @Deprecated public synchronized Map<String, ByteString> getTags() { return new HashMap<>(tags); } }
1,940
28.409091
90
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/ExchangeRate.java
/* * 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. */ package org.bitcoinj.utils; import org.bitcoinj.base.utils.Fiat; import org.bitcoinj.base.Coin; import java.math.BigInteger; import java.util.Objects; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** * An exchange rate is expressed as a ratio of a {@link Coin} and a {@link Fiat} amount. */ public class ExchangeRate { public final Coin coin; public final Fiat fiat; /** Construct exchange rate. This amount of coin is worth that amount of fiat. */ public ExchangeRate(Coin coin, Fiat fiat) { checkArgument(coin.isPositive()); checkArgument(fiat.isPositive()); checkArgument(fiat.currencyCode != null, () -> "currency code required"); this.coin = coin; this.fiat = fiat; } /** Construct exchange rate. One coin is worth this amount of fiat. */ public ExchangeRate(Fiat fiat) { this(Coin.COIN, fiat); } /** * Convert a coin amount to a fiat amount using this exchange rate. * @throws ArithmeticException if the converted fiat amount is too high or too low. */ public Fiat coinToFiat(Coin convertCoin) { // Use BigInteger because it's much easier to maintain full precision without overflowing. final BigInteger converted = BigInteger.valueOf(convertCoin.value).multiply(BigInteger.valueOf(fiat.value)) .divide(BigInteger.valueOf(coin.value)); if (converted.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0 || converted.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) < 0) throw new ArithmeticException("Overflow"); return Fiat.valueOf(fiat.currencyCode, converted.longValue()); } /** * Convert a fiat amount to a coin amount using this exchange rate. * @throws ArithmeticException if the converted coin amount is too high or too low. */ public Coin fiatToCoin(Fiat convertFiat) { checkArgument(convertFiat.currencyCode.equals(fiat.currencyCode), () -> "currency mismatch: " + convertFiat.currencyCode + " vs " + fiat.currencyCode); // Use BigInteger because it's much easier to maintain full precision without overflowing. final BigInteger converted = BigInteger.valueOf(convertFiat.value).multiply(BigInteger.valueOf(coin.value)) .divide(BigInteger.valueOf(fiat.value)); if (converted.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0 || converted.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) < 0) throw new ArithmeticException("Overflow"); try { return Coin.valueOf(converted.longValue()); } catch (IllegalArgumentException x) { throw new ArithmeticException("Overflow: " + x.getMessage()); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ExchangeRate other = (ExchangeRate) o; return Objects.equals(this.coin, other.coin) && Objects.equals(this.fiat, other.fiat); } @Override public int hashCode() { return Objects.hash(coin, fiat); } }
3,796
38.14433
115
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/BtcAutoFormat.java
/* * Copyright 2014 Adam Mackler * * 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. */ package org.bitcoinj.utils; import org.bitcoinj.base.Coin; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.Collections; import java.util.Locale; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.ZERO; import static java.math.RoundingMode.HALF_UP; import static org.bitcoinj.base.Coin.SMALLEST_UNIT_EXPONENT; /** * <p>This class, a concrete extension of {@link BtcFormat}, is distinguished by its * accommodation of multiple denominational units as follows: * * <p>When formatting Bitcoin monetary values, an instance of this class automatically adjusts * the denominational units in which it represents a given value so as to minimize the number * of consecutive zeros in the number that is displayed, and includes either a currency code or * symbol in the formatted value to indicate which denomination was chosen. * * <p>When parsing {@code String} representations of Bitcoin monetary values, instances of * this class automatically recognize units indicators consisting of currency codes and * symbols, including including those containing currency or metric prefixes such as * {@code "¢"} or {@code "c"} to indicate hundredths, and interpret each number being * parsed in accordance with the recognized denominational units. * * <p>A more detailed explanation, including examples, is in the documentation for the {@link * BtcFormat} class, and further information beyond that is in the documentation for the {@link * java.text.Format} class, from which this class descends. * @see java.text.Format * @see java.text.NumberFormat * @see java.text.DecimalFormat * @see DecimalFormatSymbols * @see Coin */ public final class BtcAutoFormat extends BtcFormat { /** * Enum for specifying the style of currency indicators that are used * when formatting, either codes or symbols. */ public enum Style { /* Notes: * 1) The odd-looking character in the replacements below, named "currency sign," is used in * the patterns recognized by Java's number formatter. A single occurrence of this * character specifies a currency symbol, while two adjacent occurrences indicate an * international currency code. * 2) The positive and negative patterns each have three parts: prefix, number, suffix. * The number characters are limited to digits, zero, decimal-separator, group-separator, and * scientific-notation specifier: [#0.,E] * All number characters besides 'E' must be single-quoted in order to appear as * literals in either the prefix or suffix. * These patterns are explained in the documentation for java.text.DecimalFormat. */ /** Constant for the formatting style that uses a currency code, e.g., "BTC". */ CODE { @Override void apply(DecimalFormat decimalFormat) { /* To switch to using codes from symbols, we replace each single occurrence of the * currency-sign character with two such characters in a row. * We also insert a space character between every occurrence of this character and * an adjacent numerical digit or negative sign (that is, between the currency-sign * and the signed-number). */ decimalFormat.applyPattern( negify(decimalFormat.toPattern()).replaceAll("¤","¤¤"). replaceAll("([#0.,E-])¤¤","$1 ¤¤"). replaceAll("¤¤([0#.,E-])","¤¤ $1") ); } }, /** Constant for the formatting style that uses a currency symbol, e.g., "฿". */ SYMBOL { @Override void apply(DecimalFormat decimalFormat) { /* To make certain we are using symbols rather than codes, we replace * each double occurrence of the currency sign character with a single. */ decimalFormat.applyPattern(negify(decimalFormat.toPattern()).replaceAll("¤¤","¤")); } }; /** Effect a style corresponding to an enum value on the given number formatter object. */ abstract void apply(DecimalFormat decimalFormat); } /** Constructor */ protected BtcAutoFormat(Locale locale, Style style, int fractionPlaces) { super((DecimalFormat)NumberFormat.getCurrencyInstance(locale), fractionPlaces, Collections.emptyList()); style.apply(this.numberFormat); } /** * Calculate the appropriate denomination for the given Bitcoin monetary value. This * method takes a BigInteger representing a quantity of satoshis, and returns the * number of places that value's decimal point is to be moved when formatting said value * in order that the resulting number represents the correct quantity of denominational * units. * * <p>As a side-effect, this sets the units indicators of the underlying NumberFormat object. * Only invoke this from a synchronized method, and be sure to put the DecimalFormatSymbols * back to its proper state, otherwise immutability, equals() and hashCode() fail. */ @Override protected int scale(BigInteger satoshis, int fractionPlaces) { /* The algorithm is as follows. TODO: is there a way to optimize step 4? 1. Can we use coin denomination w/ no rounding? If yes, do it. 2. Else, can we use millicoin denomination w/ no rounding? If yes, do it. 3. Else, can we use micro denomination w/ no rounding? If yes, do it. 4. Otherwise we must round: (a) round to nearest coin + decimals (b) round to nearest millicoin + decimals (c) round to nearest microcoin + decimals Subtract each of (a), (b) and (c) from the true value, and choose the denomination that gives smallest absolute difference. It case of tie, use the smaller denomination. */ int places; int coinOffset = Math.max(SMALLEST_UNIT_EXPONENT - fractionPlaces, 0); BigDecimal inCoins = new BigDecimal(satoshis).movePointLeft(coinOffset); if (inCoins.remainder(ONE).compareTo(ZERO) == 0) { places = COIN_SCALE; } else { BigDecimal inMillis = inCoins.movePointRight(MILLICOIN_SCALE); if (inMillis.remainder(ONE).compareTo(ZERO) == 0) { places = MILLICOIN_SCALE; } else { BigDecimal inMicros = inCoins.movePointRight(MICROCOIN_SCALE); if (inMicros.remainder(ONE).compareTo(ZERO) == 0) { places = MICROCOIN_SCALE; } else { // no way to avoid rounding: so what denomination gives smallest error? BigDecimal a = inCoins.subtract(inCoins.setScale(0, HALF_UP)). movePointRight(coinOffset).abs(); BigDecimal b = inMillis.subtract(inMillis.setScale(0, HALF_UP)). movePointRight(coinOffset - MILLICOIN_SCALE).abs(); BigDecimal c = inMicros.subtract(inMicros.setScale(0, HALF_UP)). movePointRight(coinOffset - MICROCOIN_SCALE).abs(); if (a.compareTo(b) < 0) if (a.compareTo(c) < 0) places = COIN_SCALE; else places = MICROCOIN_SCALE; else if (b.compareTo(c) < 0) places = MILLICOIN_SCALE; else places = MICROCOIN_SCALE; } } } prefixUnitsIndicator(numberFormat, places); return places; } /** Returns the {@code int} value indicating coin denomination. This is what causes * the number in a parsed value that lacks a units indicator to be interpreted as a quantity * of bitcoins. */ @Override protected int scale() { return COIN_SCALE; } /** Return the number of decimal places in the fraction part of numbers formatted by this * instance. This is the maximum number of fraction places that will be displayed; * the actual number used is limited to a precision of satoshis. */ public int fractionPlaces() { return minimumFractionDigits; } /** Return true if the other instance is equivalent to this one. * Formatters for different locales will never be equal, even * if they behave identically. */ @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof BtcAutoFormat)) return false; return super.equals(o); } /** * Return a brief description of this formatter. The exact details of the representation * are unspecified and subject to change, but will include some representation of the * pattern and the number of fractional decimal places. */ @Override public String toString() { return "Auto-format " + pattern(); } }
9,853
47.541872
112
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/BriefLogFormatter.java
/* * Copyright 2011 Google Inc. * * 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. */ package org.bitcoinj.utils; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.text.MessageFormat; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; /** * A Java logging formatter that writes more compact output than the default. */ public class BriefLogFormatter extends Formatter { private static final MessageFormat messageFormat = new MessageFormat("{3} {0} {1}.{2}: {4}\n{5}"); // OpenJDK made a questionable, backwards incompatible change to the Logger implementation. It internally uses // weak references now which means simply fetching the logger and changing its configuration won't work. We must // keep a reference to our custom logger around. private static final Logger logger = Logger.getLogger(""); public static void init() { init(Level.INFO); } /** Configures JDK logging to use this class for everything. */ public static void init(Level level) { final Handler[] handlers = logger.getHandlers(); // In regular Java there is always a handler. Avian doesn't install one however. if (handlers.length > 0) handlers[0].setFormatter(new BriefLogFormatter()); logger.setLevel(level); } public static void initVerbose() { init(Level.ALL); logger.log(Level.FINE, "test"); } public static void initWithSilentBitcoinJ() { init(); Logger.getLogger("org.bitcoinj").setLevel(Level.SEVERE); } @Override public String format(LogRecord logRecord) { Object[] arguments = new Object[6]; arguments[0] = logRecord.getThreadID(); String fullClassName = logRecord.getSourceClassName(); int lastDot = fullClassName.lastIndexOf('.'); String className = fullClassName.substring(lastDot + 1); arguments[1] = className; arguments[2] = logRecord.getSourceMethodName(); arguments[3] = DateTimeFormatter.ISO_LOCAL_TIME.format( LocalDateTime.ofInstant(Instant.ofEpochMilli(logRecord.getMillis()), ZoneOffset.UTC)); arguments[4] = logRecord.getMessage(); if (logRecord.getThrown() != null) { Writer result = new StringWriter(); logRecord.getThrown().printStackTrace(new PrintWriter(result)); arguments[5] = result.toString(); } else { arguments[5] = ""; } return messageFormat.format(arguments); } }
3,326
35.966667
116
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/ListenableCompletionStage.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.utils; import com.google.common.util.concurrent.ListenableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.Executor; /** * A {@link CompletionStage} with a {@link ListenableFuture}-compatible interface to smooth migration * from Guava {@code ListenableFuture} to {@link java.util.concurrent.CompletableFuture}/{@code CompletionStage}. * <p> * Note that this is much easier to implement than trying to extend {@link com.google.common.util.concurrent.AbstractFuture} * to implement {@code CompletionStage}. */ public interface ListenableCompletionStage<V> extends CompletionStage<V>, ListenableFuture<V> { /** * @deprecated Use {@link java.util.concurrent.CompletableFuture} and {@link java.util.concurrent.CompletableFuture#thenRunAsync(Runnable, Executor)} */ @Override @Deprecated default void addListener(Runnable listener, Executor executor) { this.thenRunAsync(listener, executor); } }
1,602
39.075
153
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/ListenerRegistration.java
/* * Copyright 2013 Google Inc. * * 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. */ package org.bitcoinj.utils; import java.util.List; import java.util.Objects; import java.util.concurrent.Executor; /** * A simple wrapper around a listener and an executor, with some utility methods. */ public class ListenerRegistration<T> { public final T listener; public final Executor executor; public ListenerRegistration(T listener, Executor executor) { this.listener = Objects.requireNonNull(listener); this.executor = Objects.requireNonNull(executor); } /** Returns true if the listener was removed, else false. */ public static <T> boolean removeFromList(T listener, List<? extends ListenerRegistration<T>> list) { Objects.requireNonNull(listener); ListenerRegistration<T> item = null; for (ListenerRegistration<T> registration : list) { if (registration.listener == listener) { item = registration; break; } } return item != null && list.remove(item); } }
1,606
31.795918
104
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/Threading.java
/* * Copyright 2013 Google Inc. * * 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. */ package org.bitcoinj.utils; import com.google.common.util.concurrent.CycleDetectingLockFactory; import com.google.common.util.concurrent.Uninterruptibles; import org.bitcoinj.base.internal.PlatformUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.locks.ReentrantLock; /** * Various threading related utilities. Provides a wrapper around explicit lock creation that lets you control whether * bitcoinj performs cycle detection or not. Cycle detection is useful to detect bugs but comes with a small cost. * Also provides a worker thread that is designed for event listeners to be dispatched on. */ public class Threading { ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // User thread/event handling utilities // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * An executor with one thread that is intended for running event listeners on. This ensures all event listener code * runs without any locks being held. It's intended for the API user to run things on. Callbacks registered by * bitcoinj internally shouldn't normally run here, although currently there are a few exceptions. */ public static Executor USER_THREAD; /** * A dummy executor that just invokes the runnable immediately. Use this over more complex executors * (e.g. those extending {@link ExecutorService}), which are overkill for our needs. */ public static final Executor SAME_THREAD; /** * Put a dummy task into the queue and wait for it to be run. Because it's single threaded, this means all * tasks submitted before this point are now completed. Usually you won't want to use this method - it's a * convenience primarily used in unit testing. If you want to wait for an event to be called the right thing * to do is usually to create a {@link CompletableFuture} and then call {@link CompletableFuture#complete(Object)} * on it. For example: * <pre>{@code * CompletableFuture f = CompletableFuture.supplyAsync(() -> event, USER_THREAD) * }</pre> * You can then either block on that future, compose it, add listeners to it and so on. */ public static void waitForUserCode() { CompletableFuture.runAsync(() -> {}, USER_THREAD).join(); } /** * An exception handler that will be invoked for any exceptions that occur in the user thread, and * any unhandled exceptions that are caught whilst the framework is processing network traffic or doing other * background tasks. The purpose of this is to allow you to report back unanticipated crashes from your users * to a central collection center for analysis and debugging. You should configure this <b>before</b> any * bitcoinj library code is run, setting it after you started network traffic and other forms of processing * may result in the change not taking effect. */ @Nullable public static volatile Thread.UncaughtExceptionHandler uncaughtExceptionHandler; public static class UserThread extends Thread implements Executor { private static final Logger log = LoggerFactory.getLogger(UserThread.class); // 10,000 pending tasks is entirely arbitrary and may or may not be appropriate for the device we're // running on. public static int WARNING_THRESHOLD = 10000; private final BlockingQueue<Runnable> tasks; public UserThread() { super("bitcoinj user thread"); setDaemon(true); tasks = new LinkedBlockingQueue<>(); start(); } @SuppressWarnings("InfiniteLoopStatement") @Override public void run() { while (true) { Runnable task = Uninterruptibles.takeUninterruptibly(tasks); try { task.run(); } catch (Throwable throwable) { log.warn("Exception in user thread", throwable); Thread.UncaughtExceptionHandler handler = uncaughtExceptionHandler; if (handler != null) handler.uncaughtException(this, throwable); } } } @Override public void execute(Runnable command) { final int size = tasks.size(); if (size == WARNING_THRESHOLD) { log.warn( "User thread has {} pending tasks, memory exhaustion may occur.\n" + "If you see this message, check your memory consumption and see if it's problematic or excessively spikey.\n" + "If it is, check for deadlocked or slow event handlers. If it isn't, try adjusting the constant \n" + "Threading.UserThread.WARNING_THRESHOLD upwards until it's a suitable level for your app, or Integer.MAX_VALUE to disable." , size); } Uninterruptibles.putUninterruptibly(tasks, command); } } static { // Default policy goes here. If you want to change this, use one of the static methods before // instantiating any bitcoinj objects. The policy change will take effect only on new objects // from that point onwards. throwOnLockCycles(); USER_THREAD = new UserThread(); SAME_THREAD = Runnable::run; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Cycle detecting lock factories // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// private static CycleDetectingLockFactory.Policy policy; public static CycleDetectingLockFactory factory; public static ReentrantLock lock(Class clazz) { return lock(clazz.getSimpleName() + " lock"); } public static ReentrantLock lock(String name) { if (PlatformUtils.isAndroidRuntime()) return new ReentrantLock(true); else return factory.newReentrantLock(name); } public static void warnOnLockCycles() { setPolicy(CycleDetectingLockFactory.Policies.WARN); } public static void throwOnLockCycles() { setPolicy(CycleDetectingLockFactory.Policies.THROW); } public static void ignoreLockCycles() { setPolicy(CycleDetectingLockFactory.Policies.DISABLED); } public static void setPolicy(CycleDetectingLockFactory.Policy policy) { Threading.policy = policy; factory = CycleDetectingLockFactory.newInstance(policy); } public static CycleDetectingLockFactory.Policy getPolicy() { return policy; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Generic worker pool. // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** A caching thread pool that creates daemon threads, which won't keep the JVM alive waiting for more work. */ public static ExecutorService THREAD_POOL = Executors.newCachedThreadPool(r -> { Thread t = new Thread(r); t.setName("Threading.THREAD_POOL worker"); t.setDaemon(true); return t; }); }
8,342
42.005155
152
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/ExponentialBackoff.java
/* * Copyright 2013 Google Inc. * * 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. */ package org.bitcoinj.utils; import org.bitcoinj.base.internal.TimeUtils; import java.time.Duration; import java.time.Instant; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** * <p>Tracks successes and failures and calculates a time to retry the operation.</p> * * <p>The retries are exponentially backed off, up to a maximum interval. On success the back off interval is reset.</p> */ public class ExponentialBackoff implements Comparable<ExponentialBackoff> { public static final Duration DEFAULT_INITIAL_INTERVAL = Duration.ofMillis(100); public static final float DEFAULT_MULTIPLIER = 1.1f; public static final Duration DEFAULT_MAXIMUM_INTERVAL = Duration.ofSeconds(30); private Duration backoff; private Instant retryTime; private final Params params; /** * Parameters to configure a particular kind of exponential backoff. */ public static class Params { private final Duration initialInterval; private final float multiplier; private final Duration maximumInterval; /** * @param initialInterval the initial interval to wait * @param multiplier the multiplier to apply on each failure * @param maximumInterval the maximum interval to wait */ public Params(Duration initialInterval, float multiplier, Duration maximumInterval) { checkArgument(multiplier > 1.0f, () -> "multiplier must be greater than 1.0: " + multiplier); checkArgument(maximumInterval.compareTo(initialInterval) >= 0, () -> "maximum must not be less than initial: " + maximumInterval); this.initialInterval = initialInterval; this.multiplier = multiplier; this.maximumInterval = maximumInterval; } /** * Construct params with default values. */ public Params() { initialInterval = DEFAULT_INITIAL_INTERVAL; multiplier = DEFAULT_MULTIPLIER; maximumInterval = DEFAULT_MAXIMUM_INTERVAL; } } public ExponentialBackoff(Params params) { this.params = params; trackSuccess(); } /** Track a success - reset back off interval to the initial value */ public final void trackSuccess() { backoff = params.initialInterval; retryTime = TimeUtils.currentTime(); } /** Track a failure - multiply the back off interval by the multiplier */ public void trackFailure() { retryTime = TimeUtils.currentTime().plus(backoff); backoff = Duration.ofMillis((long) (backoff.toMillis() * params.multiplier)); if (backoff.compareTo(params.maximumInterval) > 0) backoff = params.maximumInterval; } /** Get the next time to retry */ public Instant retryTime() { return retryTime; } /** * Get the next time to retry, in milliseconds since the epoch * @deprecated use {@link #retryTime()} **/ @Deprecated public long getRetryTime() { return retryTime.toEpochMilli(); } @Override public int compareTo(ExponentialBackoff other) { // note that in this implementation compareTo() is not consistent with equals() return retryTime.compareTo(other.retryTime); } @Override public String toString() { return "ExponentialBackoff retry=" + retryTime + " backoff=" + backoff.toMillis() + " ms"; } }
4,082
33.601695
121
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/VersionTally.java
/* * Copyright 2015 Ross Nicoll. * * 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. */ package org.bitcoinj.utils; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.StoredBlock; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.BlockStoreException; import java.util.Stack; /** * Caching counter for the block versions within a moving window. This class * is NOT thread safe (as if two threads are trying to use it concurrently, * there's risk of getting versions out of sequence). * * @see org.bitcoinj.core.NetworkParameters#getMajorityWindow() * @see org.bitcoinj.core.NetworkParameters#getMajorityEnforceBlockUpgrade() * @see org.bitcoinj.core.NetworkParameters#getMajorityRejectBlockOutdated() */ public class VersionTally { /** * Cache of version numbers. */ private final long[] versionWindow; /** * Offset within the version window at which the next version will be * written. */ private int versionWriteHead = 0; /** * Number of versions written into the tally. Until this matches the length * of the version window, we do not have sufficient data to return values. */ private int versionsStored = 0; public VersionTally(final NetworkParameters params) { versionWindow = new long[params.getMajorityWindow()]; } /** * Add a new block version to the tally, and return the count for that version * within the window. * * @param version the block version to add. */ public void add(final long version) { versionWindow[versionWriteHead++] = version; if (versionWriteHead == versionWindow.length) { versionWriteHead = 0; } versionsStored++; } /** * Get the count of blocks at or above the given version, within the window. * * @param version the block version to query. * @return the count for the block version, or null if the window is not yet * full. */ public Integer getCountAtOrAbove(final long version) { if (versionsStored < versionWindow.length) { return null; } int count = 0; for (long l : versionWindow) { if (l >= version) { count++; } } return count; } /** * Initialize the version tally from the block store. Note this does not * search backwards past the start of the block store, so if starting from * a checkpoint this may not fill the window. * * @param blockStore block store to load blocks from. * @param chainHead current chain tip. */ public void initialize(final BlockStore blockStore, final StoredBlock chainHead) throws BlockStoreException { StoredBlock versionBlock = chainHead; final Stack<Long> versions = new Stack<>(); // We don't know how many blocks back we can go, so load what we can first versions.push(versionBlock.getHeader().getVersion()); for (int headOffset = 0; headOffset < versionWindow.length; headOffset++) { versionBlock = versionBlock.getPrev(blockStore); if (null == versionBlock) { break; } versions.push(versionBlock.getHeader().getVersion()); } // Replay the versions into the tally while (!versions.isEmpty()) { add(versions.pop()); } } /** * Get the size of the version window. */ public int size() { return versionWindow.length; } }
4,091
30.96875
84
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/ListenableCompletableFuture.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.utils; import org.bitcoinj.base.internal.FutureUtils; import java.util.concurrent.CompletableFuture; /** * A {@link CompletableFuture} that is also a {@link com.google.common.util.concurrent.ListenableFuture} for migration * from Guava {@code ListenableFuture} to {@link CompletableFuture}. */ public class ListenableCompletableFuture<V> extends CompletableFuture<V> implements ListenableCompletionStage<V> { /** * Returns a new {@link CompletableFuture} that is already completed with * the given value. * <p> * When the migration to {@link CompletableFuture} is finished use of this method * can be replaced with {@link CompletableFuture#completedFuture(Object)}. * * @param value the value * @param <T> the type of the value * @return the completed CompletableFuture */ public static <T> ListenableCompletableFuture<T> completedFuture(T value) { ListenableCompletableFuture<T> future = new ListenableCompletableFuture<>(); future.complete(value); return future; } /** * Returns a new {@link ListenableCompletableFuture} that is already completed exceptionally * with the given throwable. * <p> * When the migration to {@link CompletableFuture} is finished this can be deprecated * and {@link FutureUtils#failedFuture(Throwable)} can be used instead. * * @param throwable the exceptions * @param <T> the type of the expected value * @return the completed CompletableFuture */ public static <T> ListenableCompletableFuture<T> failedFuture(Throwable throwable) { return ListenableCompletableFuture.of(FutureUtils.failedFuture(throwable)); } /** * Converts a generic {@link CompletableFuture} to a {@code ListenableCompletableFuture}. If the passed * in future is already a {@code ListenableCompletableFuture} no conversion is performed. * <p> * When the migration to {@link CompletableFuture} is finished usages of this method * can simply be removed as the conversion will no longer be required. * @param future A CompletableFuture that may need to be converted * @param <T> the type of the futures return value * @return A ListenableCompletableFuture */ public static <T> ListenableCompletableFuture<T> of(CompletableFuture<T> future) { ListenableCompletableFuture<T> listenable; if (future instanceof ListenableCompletableFuture) { listenable = (ListenableCompletableFuture<T>) future; } else { listenable = new ListenableCompletableFuture<>(); future.whenComplete((value, ex) -> { // We can't test for a not-null T `value`, because of the CompletableFuture<Void> case, // so we test for a null Throwable `ex` instead. if (ex == null) { listenable.complete(value); } else { listenable.completeExceptionally(ex); } }); } return listenable; } }
3,709
40.685393
118
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/utils/BlockFileLoader.java
/* * Copyright 2012 Matt Corallo. * * 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. */ package org.bitcoinj.utils; import org.bitcoinj.base.Network; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.core.Block; import org.bitcoinj.core.MessageSerializer; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.ProtocolException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.NoSuchElementException; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** * <p>This class reads block files stored in the Bitcoin Core format. This is simply a way to concatenate * blocks together. Importing block data with this tool can be a lot faster than syncing over the network, if you * have the files available.</p> * * <p>In order to comply with {@link Iterator}, this class swallows a lot of {@link IOException}s, which may result in a few * blocks being missed followed by a huge set of orphan blocks.</p> * * <p>To blindly import all files which can be found in Bitcoin Core (version 0.8 or higher) datadir automatically, * try this code fragment: * {@code * BlockFileLoader loader = new BlockFileLoader(BlockFileLoader.getReferenceClientBlockFileList()); * for (Block block : loader) { * try { chain.add(block); } catch (Exception e) { } * } * }</p> */ public class BlockFileLoader implements Iterable<Block>, Iterator<Block> { /** * Gets the list of files which contain blocks from Bitcoin Core. */ public static List<File> getReferenceClientBlockFileList(File blocksDir) { checkArgument(blocksDir.isDirectory(), () -> "not a directory: " + blocksDir); List<File> list = new LinkedList<>(); for (int i = 0; true; i++) { File file = new File(blocksDir, String.format(Locale.US, "blk%05d.dat", i)); if (!file.exists()) break; list.add(file); } return list; } public static List<File> getReferenceClientBlockFileList() { return getReferenceClientBlockFileList(defaultBlocksDir()); } public static File defaultBlocksDir() { File defaultBlocksDir = AppDataDirectory.getPath("Bitcoin").resolve("blocks").toFile(); if (!defaultBlocksDir.isDirectory()) throw new RuntimeException("Default blocks directory not found"); return defaultBlocksDir; } private final Iterator<File> fileIt; private File file = null; private FileInputStream currentFileStream = null; private Block nextBlock = null; private final long packetMagic; private final MessageSerializer serializer; public BlockFileLoader(Network network, File blocksDir) { this(network, getReferenceClientBlockFileList(blocksDir)); } public BlockFileLoader(Network network, List<File> files) { fileIt = files.iterator(); NetworkParameters params = NetworkParameters.of(network); packetMagic = params.getPacketMagic(); serializer = params.getDefaultSerializer(); } @Deprecated public BlockFileLoader(NetworkParameters params, File blocksDir) { this(params.network(), getReferenceClientBlockFileList(blocksDir)); } @Deprecated public BlockFileLoader(NetworkParameters params, List<File> files) { fileIt = files.iterator(); packetMagic = params.getPacketMagic(); serializer = params.getDefaultSerializer(); } @Override public boolean hasNext() { if (nextBlock == null) loadNextBlock(); return nextBlock != null; } @Override public Block next() throws NoSuchElementException { if (!hasNext()) throw new NoSuchElementException(); Block next = nextBlock; nextBlock = null; return next; } private void loadNextBlock() { while (true) { try { if (!fileIt.hasNext() && (currentFileStream == null || currentFileStream.available() < 1)) break; } catch (IOException e) { currentFileStream = null; if (!fileIt.hasNext()) break; } while (true) { try { if (currentFileStream != null && currentFileStream.available() > 0) break; } catch (IOException e1) { currentFileStream = null; } if (!fileIt.hasNext()) { nextBlock = null; currentFileStream = null; return; } file = fileIt.next(); try { currentFileStream = new FileInputStream(file); } catch (FileNotFoundException e) { currentFileStream = null; } } try { int nextChar = currentFileStream.read(); while (nextChar != -1) { if (nextChar != ((packetMagic >>> 24) & 0xff)) { nextChar = currentFileStream.read(); continue; } nextChar = currentFileStream.read(); if (nextChar != ((packetMagic >>> 16) & 0xff)) continue; nextChar = currentFileStream.read(); if (nextChar != ((packetMagic >>> 8) & 0xff)) continue; nextChar = currentFileStream.read(); if (nextChar == (packetMagic & 0xff)) break; } byte[] bytes = new byte[4]; currentFileStream.read(bytes, 0, 4); long size = ByteUtils.readUint32(bytes, 0); bytes = new byte[(int) size]; currentFileStream.read(bytes, 0, (int) size); try { nextBlock = serializer.makeBlock(ByteBuffer.wrap(bytes)); } catch (ProtocolException e) { nextBlock = null; continue; } catch (Exception e) { throw new RuntimeException("unexpected problem with block in " + file, e); } break; } catch (IOException e) { currentFileStream = null; continue; } } } @Override public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public Iterator<Block> iterator() { return this; } }
7,425
34.874396
124
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/script/package-info.java
/* * Copyright by the original author or authors. * * 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. */ /** * Classes for working with and executing Bitcoin script programs, as embedded in inputs and outputs. */ package org.bitcoinj.script;
752
36.65
101
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/script/ScriptPattern.java
/* * Copyright 2017 John L. Jegutanis * Copyright 2018 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. */ package org.bitcoinj.script; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.base.LegacyAddress; import org.bitcoinj.base.SegwitAddress; import org.bitcoinj.base.Sha256Hash; import java.util.Arrays; import java.util.List; import static org.bitcoinj.script.Script.decodeFromOpN; import static org.bitcoinj.script.ScriptOpCodes.OP_0; import static org.bitcoinj.script.ScriptOpCodes.OP_1; import static org.bitcoinj.script.ScriptOpCodes.OP_16; import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKMULTISIG; import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKMULTISIGVERIFY; import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKSIG; import static org.bitcoinj.script.ScriptOpCodes.OP_DUP; import static org.bitcoinj.script.ScriptOpCodes.OP_EQUAL; import static org.bitcoinj.script.ScriptOpCodes.OP_EQUALVERIFY; import static org.bitcoinj.script.ScriptOpCodes.OP_HASH160; /** * This is a Script pattern matcher with some typical script patterns */ public class ScriptPattern { /** * Returns true if this script is of the form {@code DUP HASH160 <pubkey hash> EQUALVERIFY CHECKSIG}, ie, payment to an * address like {@code 1VayNert3x1KzbpzMGt2qdqrAThiRovi8}. This form was originally intended for the case where you wish * to send somebody money with a written code because their node is offline, but over time has become the standard * way to make payments due to the short and recognizable base58 form addresses come in. */ public static boolean isP2PKH(Script script) { List<ScriptChunk> chunks = script.chunks(); if (chunks.size() != 5) return false; if (!chunks.get(0).equalsOpCode(OP_DUP)) return false; if (!chunks.get(1).equalsOpCode(OP_HASH160)) return false; byte[] chunk2data = chunks.get(2).data; if (chunk2data == null) return false; if (chunk2data.length != LegacyAddress.LENGTH) return false; if (!chunks.get(3).equalsOpCode(OP_EQUALVERIFY)) return false; if (!chunks.get(4).equalsOpCode(OP_CHECKSIG)) return false; return true; } /** * Extract the pubkey hash from a P2PKH scriptPubKey. It's important that the script is in the correct form, so you * will want to guard calls to this method with {@link #isP2PKH(Script)}. */ public static byte[] extractHashFromP2PKH(Script script) { return script.chunks().get(2).data; } /** * <p> * Whether or not this is a scriptPubKey representing a P2SH output. In such outputs, the logic that * controls reclamation is not actually in the output at all. Instead there's just a hash, and it's up to the * spending input to provide a program matching that hash. * </p> * <p> * P2SH is described by <a href="https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki">BIP16</a>. * </p> */ public static boolean isP2SH(Script script) { List<ScriptChunk> chunks = script.chunks(); // We check for the effective serialized form because BIP16 defines a P2SH output using an exact byte // template, not the logical program structure. Thus you can have two programs that look identical when // printed out but one is a P2SH script and the other isn't! :( // We explicitly test that the op code used to load the 20 bytes is 0x14 and not something logically // equivalent like {@code OP_HASH160 OP_PUSHDATA1 0x14 <20 bytes of script hash> OP_EQUAL} if (chunks.size() != 3) return false; if (!chunks.get(0).equalsOpCode(OP_HASH160)) return false; ScriptChunk chunk1 = chunks.get(1); if (chunk1.opcode != 0x14) return false; byte[] chunk1data = chunk1.data; if (chunk1data == null) return false; if (chunk1data.length != LegacyAddress.LENGTH) return false; if (!chunks.get(2).equalsOpCode(OP_EQUAL)) return false; return true; } /** * Extract the script hash from a P2SH scriptPubKey. It's important that the script is in the correct form, so you * will want to guard calls to this method with {@link #isP2SH(Script)}. */ public static byte[] extractHashFromP2SH(Script script) { return script.chunks().get(1).data; } /** * Returns true if this script is of the form {@code <pubkey> OP_CHECKSIG}. This form was originally intended for transactions * where the peers talked to each other directly via TCP/IP, but has fallen out of favor with time due to that mode * of operation being susceptible to man-in-the-middle attacks. It is still used in coinbase outputs and can be * useful more exotic types of transaction, but today most payments are to addresses. */ public static boolean isP2PK(Script script) { List<ScriptChunk> chunks = script.chunks(); if (chunks.size() != 2) return false; ScriptChunk chunk0 = chunks.get(0); if (chunk0.isOpCode()) return false; byte[] chunk0data = chunk0.data; if (chunk0data == null) return false; if (chunk0data.length <= 1) return false; if (!chunks.get(1).equalsOpCode(OP_CHECKSIG)) return false; return true; } /** * Extract the pubkey from a P2SH scriptPubKey. It's important that the script is in the correct form, so you will * want to guard calls to this method with {@link #isP2PK(Script)}. */ public static byte[] extractKeyFromP2PK(Script script) { return script.chunks().get(0).data; } /** * Returns true if this script is of the form {@code OP_0 <hash>}. This can either be a P2WPKH or P2WSH scriptPubKey. These * two script types were introduced with segwit. */ public static boolean isP2WH(Script script) { List<ScriptChunk> chunks = script.chunks(); if (chunks.size() != 2) return false; if (!chunks.get(0).equalsOpCode(OP_0)) return false; byte[] chunk1data = chunks.get(1).data; if (chunk1data == null) return false; if (chunk1data.length != SegwitAddress.WITNESS_PROGRAM_LENGTH_PKH && chunk1data.length != SegwitAddress.WITNESS_PROGRAM_LENGTH_SH) return false; return true; } /** * Returns true if this script is of the form {@code OP_0 <hash>} and hash is 20 bytes long. This can only be a P2WPKH * scriptPubKey. This script type was introduced with segwit. */ public static boolean isP2WPKH(Script script) { if (!isP2WH(script)) return false; List<ScriptChunk> chunks = script.chunks(); if (!chunks.get(0).equalsOpCode(OP_0)) return false; byte[] chunk1data = chunks.get(1).data; return chunk1data != null && chunk1data.length == SegwitAddress.WITNESS_PROGRAM_LENGTH_PKH; } /** * Returns true if this script is of the form {@code OP_0 <hash>} and hash is 32 bytes long. This can only be a P2WSH * scriptPubKey. This script type was introduced with segwit. */ public static boolean isP2WSH(Script script) { if (!isP2WH(script)) return false; List<ScriptChunk> chunks = script.chunks(); if (!chunks.get(0).equalsOpCode(OP_0)) return false; byte[] chunk1data = chunks.get(1).data; return chunk1data != null && chunk1data.length == SegwitAddress.WITNESS_PROGRAM_LENGTH_SH; } /** * Extract the pubkey hash from a P2WPKH or the script hash from a P2WSH scriptPubKey. It's important that the * script is in the correct form, so you will want to guard calls to this method with * {@link #isP2WH(Script)}. */ public static byte[] extractHashFromP2WH(Script script) { return script.chunks().get(1).data; } /** * Returns true if this script is of the form {@code OP_1 <pubkey>}. This is a P2TR scriptPubKey. This * script type was introduced with taproot. */ public static boolean isP2TR(Script script) { List<ScriptChunk> chunks = script.chunks(); if (chunks.size() != 2) return false; if (!chunks.get(0).equalsOpCode(OP_1)) return false; byte[] chunk1data = chunks.get(1).data; if (chunk1data == null) return false; if (chunk1data.length != SegwitAddress.WITNESS_PROGRAM_LENGTH_TR) return false; return true; } /** * Extract the taproot output key from a P2TR scriptPubKey. It's important that the script is in the correct * form, so you will want to guard calls to this method with {@link #isP2TR(Script)}. */ public static byte[] extractOutputKeyFromP2TR(Script script) { return script.chunks().get(1).data; } /** * Returns whether this script matches the format used for m-of-n multisig outputs: * {@code [m] [keys...] [n] CHECKMULTISIG} */ public static boolean isSentToMultisig(Script script) { List<ScriptChunk> chunks = script.chunks(); if (chunks.size() < 4) return false; ScriptChunk chunk = chunks.get(chunks.size() - 1); // Must end in OP_CHECKMULTISIG[VERIFY]. if (!(chunk.equalsOpCode(OP_CHECKMULTISIG) || chunk.equalsOpCode(OP_CHECKMULTISIGVERIFY))) return false; // Second to last chunk must be an OP_N opcode and there should be that many data chunks (keys). int nOpCode = chunks.get(chunks.size() - 2).opcode; if (nOpCode < OP_1 || nOpCode > OP_16) return false; int numKeys = decodeFromOpN(nOpCode); if (numKeys < 1 || chunks.size() != 3 + numKeys) return false; for (int i = 1; i < chunks.size() - 2; i++) { if (chunks.get(i).isOpCode()) return false; } // First chunk must be an OP_N opcode too. int mOpCode = chunks.get(0).opcode; return mOpCode >= OP_1 && mOpCode <= OP_16; } /** * Returns whether this script is using OP_RETURN to store arbitrary data. */ public static boolean isOpReturn(Script script) { List<ScriptChunk> chunks = script.chunks(); return chunks.size() > 0 && chunks.get(0).equalsOpCode(ScriptOpCodes.OP_RETURN); } private static final byte[] SEGWIT_COMMITMENT_HEADER = ByteUtils.parseHex("aa21a9ed"); /** * Returns whether this script matches the pattern for a segwit commitment (in an output of the coinbase * transaction). */ public static boolean isWitnessCommitment(Script script) { List<ScriptChunk> chunks = script.chunks(); if (chunks.size() < 2) return false; if (!chunks.get(0).equalsOpCode(ScriptOpCodes.OP_RETURN)) return false; byte[] chunkData = chunks.get(1).data; if (chunkData == null || chunkData.length != 36) return false; if (!Arrays.equals(Arrays.copyOfRange(chunkData, 0, 4), SEGWIT_COMMITMENT_HEADER)) return false; return true; } /** * Retrieves the hash from a segwit commitment (in an output of the coinbase transaction). */ public static Sha256Hash extractWitnessCommitmentHash(Script script) { return Sha256Hash.wrap(Arrays.copyOfRange(script.chunks().get(1).data, 4, 36)); } }
12,145
40.738832
130
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/script/Script.java
/* * Copyright 2011 Google Inc. * Copyright 2012 Matt Corallo. * Copyright 2014 Andreas Schildbach * Copyright 2017 Nicola Atzei * * 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. */ package org.bitcoinj.script; import org.bitcoinj.base.Network; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.base.Address; import org.bitcoinj.base.Coin; import org.bitcoinj.core.LockTime; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.base.LegacyAddress; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.ProtocolException; import org.bitcoinj.base.SegwitAddress; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.crypto.SignatureDecodeException; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.TransactionWitness; import org.bitcoinj.core.Utils; import org.bitcoinj.base.VarInt; import org.bitcoinj.core.VerificationException; import org.bitcoinj.base.internal.InternalUtils; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.crypto.internal.CryptoUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; import static org.bitcoinj.script.ScriptOpCodes.OP_0; import static org.bitcoinj.script.ScriptOpCodes.OP_0NOTEQUAL; import static org.bitcoinj.script.ScriptOpCodes.OP_1; import static org.bitcoinj.script.ScriptOpCodes.OP_10; import static org.bitcoinj.script.ScriptOpCodes.OP_11; import static org.bitcoinj.script.ScriptOpCodes.OP_12; import static org.bitcoinj.script.ScriptOpCodes.OP_13; import static org.bitcoinj.script.ScriptOpCodes.OP_14; import static org.bitcoinj.script.ScriptOpCodes.OP_15; import static org.bitcoinj.script.ScriptOpCodes.OP_16; import static org.bitcoinj.script.ScriptOpCodes.OP_1ADD; import static org.bitcoinj.script.ScriptOpCodes.OP_1NEGATE; import static org.bitcoinj.script.ScriptOpCodes.OP_1SUB; import static org.bitcoinj.script.ScriptOpCodes.OP_2; import static org.bitcoinj.script.ScriptOpCodes.OP_2DIV; import static org.bitcoinj.script.ScriptOpCodes.OP_2DROP; import static org.bitcoinj.script.ScriptOpCodes.OP_2DUP; import static org.bitcoinj.script.ScriptOpCodes.OP_2MUL; import static org.bitcoinj.script.ScriptOpCodes.OP_2OVER; import static org.bitcoinj.script.ScriptOpCodes.OP_2ROT; import static org.bitcoinj.script.ScriptOpCodes.OP_2SWAP; import static org.bitcoinj.script.ScriptOpCodes.OP_3; import static org.bitcoinj.script.ScriptOpCodes.OP_3DUP; import static org.bitcoinj.script.ScriptOpCodes.OP_4; import static org.bitcoinj.script.ScriptOpCodes.OP_5; import static org.bitcoinj.script.ScriptOpCodes.OP_6; import static org.bitcoinj.script.ScriptOpCodes.OP_7; import static org.bitcoinj.script.ScriptOpCodes.OP_8; import static org.bitcoinj.script.ScriptOpCodes.OP_9; import static org.bitcoinj.script.ScriptOpCodes.OP_ABS; import static org.bitcoinj.script.ScriptOpCodes.OP_ADD; import static org.bitcoinj.script.ScriptOpCodes.OP_AND; import static org.bitcoinj.script.ScriptOpCodes.OP_BOOLAND; import static org.bitcoinj.script.ScriptOpCodes.OP_BOOLOR; import static org.bitcoinj.script.ScriptOpCodes.OP_CAT; import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKLOCKTIMEVERIFY; import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKMULTISIG; import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKMULTISIGVERIFY; import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKSEQUENCEVERIFY; import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKSIG; import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKSIGVERIFY; import static org.bitcoinj.script.ScriptOpCodes.OP_CODESEPARATOR; import static org.bitcoinj.script.ScriptOpCodes.OP_DEPTH; import static org.bitcoinj.script.ScriptOpCodes.OP_DIV; import static org.bitcoinj.script.ScriptOpCodes.OP_DROP; import static org.bitcoinj.script.ScriptOpCodes.OP_DUP; import static org.bitcoinj.script.ScriptOpCodes.OP_ELSE; import static org.bitcoinj.script.ScriptOpCodes.OP_ENDIF; import static org.bitcoinj.script.ScriptOpCodes.OP_EQUAL; import static org.bitcoinj.script.ScriptOpCodes.OP_EQUALVERIFY; import static org.bitcoinj.script.ScriptOpCodes.OP_FROMALTSTACK; import static org.bitcoinj.script.ScriptOpCodes.OP_GREATERTHAN; import static org.bitcoinj.script.ScriptOpCodes.OP_GREATERTHANOREQUAL; import static org.bitcoinj.script.ScriptOpCodes.OP_HASH160; import static org.bitcoinj.script.ScriptOpCodes.OP_HASH256; import static org.bitcoinj.script.ScriptOpCodes.OP_IF; import static org.bitcoinj.script.ScriptOpCodes.OP_IFDUP; import static org.bitcoinj.script.ScriptOpCodes.OP_INVALIDOPCODE; import static org.bitcoinj.script.ScriptOpCodes.OP_INVERT; import static org.bitcoinj.script.ScriptOpCodes.OP_LEFT; import static org.bitcoinj.script.ScriptOpCodes.OP_LESSTHAN; import static org.bitcoinj.script.ScriptOpCodes.OP_LESSTHANOREQUAL; import static org.bitcoinj.script.ScriptOpCodes.OP_LSHIFT; import static org.bitcoinj.script.ScriptOpCodes.OP_MAX; import static org.bitcoinj.script.ScriptOpCodes.OP_MIN; import static org.bitcoinj.script.ScriptOpCodes.OP_MOD; import static org.bitcoinj.script.ScriptOpCodes.OP_MUL; import static org.bitcoinj.script.ScriptOpCodes.OP_NEGATE; import static org.bitcoinj.script.ScriptOpCodes.OP_NIP; import static org.bitcoinj.script.ScriptOpCodes.OP_NOP; import static org.bitcoinj.script.ScriptOpCodes.OP_NOP1; import static org.bitcoinj.script.ScriptOpCodes.OP_NOP10; import static org.bitcoinj.script.ScriptOpCodes.OP_NOP4; import static org.bitcoinj.script.ScriptOpCodes.OP_NOP5; import static org.bitcoinj.script.ScriptOpCodes.OP_NOP6; import static org.bitcoinj.script.ScriptOpCodes.OP_NOP7; import static org.bitcoinj.script.ScriptOpCodes.OP_NOP8; import static org.bitcoinj.script.ScriptOpCodes.OP_NOP9; import static org.bitcoinj.script.ScriptOpCodes.OP_NOT; import static org.bitcoinj.script.ScriptOpCodes.OP_NOTIF; import static org.bitcoinj.script.ScriptOpCodes.OP_NUMEQUAL; import static org.bitcoinj.script.ScriptOpCodes.OP_NUMEQUALVERIFY; import static org.bitcoinj.script.ScriptOpCodes.OP_NUMNOTEQUAL; import static org.bitcoinj.script.ScriptOpCodes.OP_OR; import static org.bitcoinj.script.ScriptOpCodes.OP_OVER; import static org.bitcoinj.script.ScriptOpCodes.OP_PICK; import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA1; import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA2; import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA4; import static org.bitcoinj.script.ScriptOpCodes.OP_RETURN; import static org.bitcoinj.script.ScriptOpCodes.OP_RIGHT; import static org.bitcoinj.script.ScriptOpCodes.OP_RIPEMD160; import static org.bitcoinj.script.ScriptOpCodes.OP_ROLL; import static org.bitcoinj.script.ScriptOpCodes.OP_ROT; import static org.bitcoinj.script.ScriptOpCodes.OP_RSHIFT; import static org.bitcoinj.script.ScriptOpCodes.OP_SHA1; import static org.bitcoinj.script.ScriptOpCodes.OP_SHA256; import static org.bitcoinj.script.ScriptOpCodes.OP_SIZE; import static org.bitcoinj.script.ScriptOpCodes.OP_SUB; import static org.bitcoinj.script.ScriptOpCodes.OP_SUBSTR; import static org.bitcoinj.script.ScriptOpCodes.OP_SWAP; import static org.bitcoinj.script.ScriptOpCodes.OP_TOALTSTACK; import static org.bitcoinj.script.ScriptOpCodes.OP_TUCK; import static org.bitcoinj.script.ScriptOpCodes.OP_VERIFY; import static org.bitcoinj.script.ScriptOpCodes.OP_WITHIN; import static org.bitcoinj.script.ScriptOpCodes.OP_XOR; // TODO: Redesign this entire API to be more type safe and organised. /** * <p>Programs embedded inside transactions that control redemption of payments.</p> * * <p>Bitcoin transactions don't specify what they do directly. Instead <a href="https://en.bitcoin.it/wiki/Script">a * small binary stack language</a> is used to define programs that when evaluated return whether the transaction * "accepts" or rejects the other transactions connected to it.</p> * * <p>In SPV mode, scripts are not run, because that would require all transactions to be available and lightweight * clients don't have that data. In full mode, this class is used to run the interpreted language. It also has * static methods for building scripts.</p> */ public class Script { /** Flags to pass to {@link Script#correctlySpends(Transaction, int, TransactionWitness, Coin, Script, Set)}. * Note currently only P2SH, DERSIG and NULLDUMMY are actually supported. */ public enum VerifyFlag { P2SH, // Enable BIP16-style subscript evaluation. STRICTENC, // Passing a non-strict-DER signature or one with undefined hashtype to a checksig operation causes script failure. DERSIG, // Passing a non-strict-DER signature to a checksig operation causes script failure (softfork safe, BIP66 rule 1) LOW_S, // Passing a non-strict-DER signature or one with S > order/2 to a checksig operation causes script failure NULLDUMMY, // Verify dummy stack item consumed by CHECKMULTISIG is of zero-length. SIGPUSHONLY, // Using a non-push operator in the scriptSig causes script failure (softfork safe, BIP62 rule 2). MINIMALDATA, // Require minimal encodings for all push operations DISCOURAGE_UPGRADABLE_NOPS, // Discourage use of NOPs reserved for upgrades (NOP1-10) CLEANSTACK, // Require that only a single stack element remains after evaluation. CHECKLOCKTIMEVERIFY, // Enable CHECKLOCKTIMEVERIFY operation CHECKSEQUENCEVERIFY // Enable CHECKSEQUENCEVERIFY operation } public static final EnumSet<VerifyFlag> ALL_VERIFY_FLAGS = EnumSet.allOf(VerifyFlag.class); private static final BigInteger LOCKTIME_THRESHOLD_BIG = BigInteger.valueOf(LockTime.THRESHOLD); private static final Logger log = LoggerFactory.getLogger(Script.class); public static final int MAX_SCRIPT_ELEMENT_SIZE = 520; // bytes private static final int MAX_OPS_PER_SCRIPT = 201; private static final int MAX_STACK_SIZE = 1000; private static final int MAX_PUBKEYS_PER_MULTISIG = 20; private static final int MAX_SCRIPT_SIZE = 10000; public static final int SIG_SIZE = 75; /** Max number of sigops allowed in a standard p2sh redeem script */ public static final int MAX_P2SH_SIGOPS = 15; // The program is a set of chunks where each element is either [opcode] or [data, data, data ...] private final List<ScriptChunk> chunks; // Unfortunately, scripts are not ever re-serialized or canonicalized when used in signature hashing. Thus we // must preserve the exact bytes that we read off the wire, along with the parsed form. private final byte[] program; // Creation time of the associated keys, or null if unknown. @Nullable private final Instant creationTime; /** * Wraps given script chunks. * * @param chunks chunks to wrap * @return script that wraps the chunks */ public static Script of(List<ScriptChunk> chunks) { return of(chunks, TimeUtils.currentTime()); } /** * Wraps given script chunks. * * @param chunks chunks to wrap * @param creationTime creation time of the script * @return script that wraps the chunks */ public static Script of(List<ScriptChunk> chunks, Instant creationTime) { chunks = Collections.unmodifiableList(new ArrayList<>(chunks)); // defensive copy Objects.requireNonNull(creationTime); return new Script(null, chunks, creationTime); } /** * Construct a script that copies and wraps a given program. The array is parsed and checked for syntactic * validity. Programs like this are e.g. used in {@link TransactionInput} and {@link TransactionOutput}. * * @param program array of program bytes * @return parsed program * @throws ScriptException if the program could not be parsed */ public static Script parse(byte[] program) throws ScriptException { return parse(program, TimeUtils.currentTime()); } /** * Construct a script that copies and wraps a given program, and a creation time. The array is parsed and checked * for syntactic validity. Programs like this are e.g. used in {@link TransactionInput} and * {@link TransactionOutput}. * * @param program Array of program bytes from a transaction. * @param creationTime creation time of the script * @return parsed program * @throws ScriptException if the program could not be parsed */ public static Script parse(byte[] program, Instant creationTime) throws ScriptException { Objects.requireNonNull(creationTime); program = Arrays.copyOf(program, program.length); // defensive copy List<ScriptChunk> chunks = new ArrayList<>(5); // common size parseIntoChunks(program, chunks); return new Script(program, chunks, creationTime); } /** * 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. */ private static void parseIntoChunks(byte[] program, List<ScriptChunk> chunks) throws ScriptException { ByteArrayInputStream bis = new ByteArrayInputStream(program); while (bis.available() > 0) { int opcode = bis.read(); long dataToRead = -1; if (opcode >= 0 && opcode < OP_PUSHDATA1) { // Read some bytes of data, where how many is the opcode value itself. dataToRead = opcode; } else if (opcode == OP_PUSHDATA1) { if (bis.available() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Unexpected end of script"); dataToRead = bis.read(); } else if (opcode == OP_PUSHDATA2) { // Read a short, then read that many bytes of data. if (bis.available() < 2) throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Unexpected end of script"); dataToRead = ByteUtils.readUint16(bis); } else if (opcode == OP_PUSHDATA4) { // Read a uint32, then read that many bytes of data. // Though this is allowed, because its value cannot be > 520, it should never actually be used if (bis.available() < 4) throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Unexpected end of script"); dataToRead = ByteUtils.readUint32(bis); } ScriptChunk chunk; if (dataToRead == -1) { chunk = new ScriptChunk(opcode, null); } else { if (dataToRead > bis.available()) throw new ScriptException(ScriptError.SCRIPT_ERR_BAD_OPCODE, "Push of data element that is larger than remaining data: " + dataToRead + " vs " + bis.available()); byte[] data = new byte[(int)dataToRead]; checkState(dataToRead == 0 || bis.read(data, 0, (int) dataToRead) == dataToRead); chunk = new ScriptChunk(opcode, data); } // Save some memory by eliminating redundant copies of the same chunk objects. for (ScriptChunk c : STANDARD_TRANSACTION_SCRIPT_CHUNKS) { if (c.equals(chunk)) chunk = c; } chunks.add(chunk); } } private Script(byte[] programBytes, List<ScriptChunk> chunks, Instant creationTime) { this.program = programBytes; this.chunks = chunks; this.creationTime = creationTime; } /** * Gets the serialized program as a newly created byte array. * * @return serialized program */ public byte[] program() { if (program != null) // Don't round-trip as Bitcoin Core doesn't and it would introduce a mismatch. return Arrays.copyOf(program, program.length); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } return bos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } } /** @deprecated use {@link #program()} */ @Deprecated public byte[] getProgram() { return program(); } /** * Gets an immutable list of the scripts parsed form. Each chunk is either an opcode or data element. * * @return script chunks */ public List<ScriptChunk> chunks() { return Collections.unmodifiableList(chunks); } /** @deprecated use {@link #chunks()} */ @Deprecated public List<ScriptChunk> getChunks() { return chunks(); } /** * Gets the creation time of this script, or empty if unknown. * @return creation time of this script, or empty if unknown */ public Optional<Instant> creationTime() { return Optional.ofNullable(creationTime); } /** @deprecated use {@link #creationTime()} */ @Deprecated public long getCreationTimeSeconds() { return creationTime().orElse(Instant.EPOCH).getEpochSecond(); } /** * Returns the program opcodes as a string, for example "[1234] DUP HASH160", or "&lt;empty&gt;". */ @Override public String toString() { if (!chunks.isEmpty()) return InternalUtils.SPACE_JOINER.join(chunks); else return "<empty>"; } private static final ScriptChunk[] STANDARD_TRANSACTION_SCRIPT_CHUNKS = { new ScriptChunk(ScriptOpCodes.OP_DUP, null), new ScriptChunk(ScriptOpCodes.OP_HASH160, null), new ScriptChunk(ScriptOpCodes.OP_EQUALVERIFY, null), new ScriptChunk(ScriptOpCodes.OP_CHECKSIG, null), }; /** * <p>If the program somehow pays to a hash, returns the hash.</p> * * <p>Otherwise this method throws a ScriptException.</p> */ public byte[] getPubKeyHash() throws ScriptException { if (ScriptPattern.isP2PKH(this)) return ScriptPattern.extractHashFromP2PKH(this); else if (ScriptPattern.isP2SH(this)) return ScriptPattern.extractHashFromP2SH(this); else if (ScriptPattern.isP2WH(this)) return ScriptPattern.extractHashFromP2WH(this); else throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Script not in the standard scriptPubKey form"); } /** * Gets the destination address from this script, if it's in the required form. */ public Address getToAddress(Network network) throws ScriptException { return getToAddress(network, false); } /** * Gets the destination address from this script, if it's in the required form. * @deprecated Use {@link #getToAddress(Network)} */ @Deprecated public Address getToAddress(NetworkParameters params) throws ScriptException { return getToAddress(params.network(), false); } /** * Gets the destination address from this script, if it's in the required form. * * @param forcePayToPubKey * If true, allow payToPubKey to be casted to the corresponding address. This is useful if you prefer * showing addresses rather than pubkeys. */ public Address getToAddress(Network network, boolean forcePayToPubKey) throws ScriptException { if (ScriptPattern.isP2PKH(this)) return LegacyAddress.fromPubKeyHash(network, ScriptPattern.extractHashFromP2PKH(this)); else if (ScriptPattern.isP2SH(this)) return LegacyAddress.fromScriptHash(network, ScriptPattern.extractHashFromP2SH(this)); else if (forcePayToPubKey && ScriptPattern.isP2PK(this)) return ECKey.fromPublicOnly(ScriptPattern.extractKeyFromP2PK(this)).toAddress(ScriptType.P2PKH, network); else if (ScriptPattern.isP2WH(this)) return SegwitAddress.fromHash(network, ScriptPattern.extractHashFromP2WH(this)); else if (ScriptPattern.isP2TR(this)) return SegwitAddress.fromProgram(network, 1, ScriptPattern.extractOutputKeyFromP2TR(this)); else throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Cannot cast this script to an address"); } /** * Gets the destination address from this script, if it's in the required form. * * @param forcePayToPubKey * If true, allow payToPubKey to be casted to the corresponding address. This is useful if you prefer * showing addresses rather than pubkeys. * @deprecated Use {@link #getToAddress(Network, boolean)} */ @Deprecated public Address getToAddress(NetworkParameters params, boolean forcePayToPubKey) throws ScriptException { return getToAddress(params.network(), forcePayToPubKey); } ////////////////////// Interface for writing scripts from scratch //////////////////////////////// /** * Writes out the given byte buffer to the output stream with the correct opcode prefix * To write an integer call writeBytes(out, Utils.reverseBytes(Utils.encodeMPI(val, false))); */ public static void writeBytes(OutputStream os, byte[] buf) throws IOException { if (buf.length < OP_PUSHDATA1) { os.write(buf.length); os.write(buf); } else if (buf.length < 256) { os.write(OP_PUSHDATA1); os.write(buf.length); os.write(buf); } else if (buf.length < 65536) { os.write(OP_PUSHDATA2); ByteUtils.writeInt16LE(buf.length, os); os.write(buf); } else { throw new RuntimeException("Unimplemented"); } } /** Creates a program that requires at least N of the given keys to sign, using OP_CHECKMULTISIG. */ public static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys) { checkArgument(threshold > 0); checkArgument(threshold <= pubkeys.size()); checkArgument(pubkeys.size() <= 16); // That's the max we can represent with a single opcode. if (pubkeys.size() > 3) { log.warn("Creating a multi-signature output that is non-standard: {} pubkeys, should be <= 3", pubkeys.size()); } try { ByteArrayOutputStream bits = new ByteArrayOutputStream(); bits.write(encodeToOpN(threshold)); for (ECKey key : pubkeys) { writeBytes(bits, key.getPubKey()); } bits.write(encodeToOpN(pubkeys.size())); bits.write(OP_CHECKMULTISIG); return bits.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } } public static byte[] createInputScript(byte[] signature, byte[] pubkey) { try { // TODO: Do this by creating a Script *first* then having the script reassemble itself into bytes. ByteArrayOutputStream bits = new ByteArrayOutputStream(signature.length + pubkey.length + 2); writeBytes(bits, signature); writeBytes(bits, pubkey); return bits.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } } public static byte[] createInputScript(byte[] signature) { try { // TODO: Do this by creating a Script *first* then having the script reassemble itself into bytes. ByteArrayOutputStream bits = new ByteArrayOutputStream(signature.length + 2); writeBytes(bits, signature); return bits.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } } /** * Creates an incomplete scriptSig that, once filled with signatures, can redeem output containing this scriptPubKey. * Instead of the signatures resulting script has OP_0. * Having incomplete input script allows to pass around partially signed tx. * It is expected that this program later on will be updated with proper signatures. */ public Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript) { if (ScriptPattern.isP2PKH(this)) { checkArgument(key != null, () -> "key required to create P2PKH input script"); return ScriptBuilder.createInputScript(null, key); } else if (ScriptPattern.isP2WPKH(this)) { return ScriptBuilder.createEmpty(); } else if (ScriptPattern.isP2PK(this)) { return ScriptBuilder.createInputScript(null); } else if (ScriptPattern.isP2SH(this)) { checkArgument(redeemScript != null, () -> "redeem script required to create P2SH input script"); return ScriptBuilder.createP2SHMultiSigInputScript(null, redeemScript); } else { throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Do not understand script type: " + this); } } /** * Returns a copy of the given scriptSig with the signature inserted in the given position. */ public Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index) { int sigsPrefixCount = 0; int sigsSuffixCount = 0; if (ScriptPattern.isP2SH(this)) { sigsPrefixCount = 1; // OP_0 <sig>* <redeemScript> sigsSuffixCount = 1; } else if (ScriptPattern.isSentToMultisig(this)) { sigsPrefixCount = 1; // OP_0 <sig>* } else if (ScriptPattern.isP2PKH(this)) { sigsSuffixCount = 1; // <sig> <pubkey> } return ScriptBuilder.updateScriptWithSignature(scriptSig, sigBytes, index, sigsPrefixCount, sigsSuffixCount); } /** * Returns the index where a signature by the key should be inserted. Only applicable to * a P2SH scriptSig. */ public int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey) { // Iterate over existing signatures, skipping the initial OP_0, the final redeem script // and any placeholder OP_0 sigs. List<ScriptChunk> existingChunks = chunks.subList(1, chunks.size() - 1); ScriptChunk redeemScriptChunk = chunks.get(chunks.size() - 1); Objects.requireNonNull(redeemScriptChunk.data); Script redeemScript = Script.parse(redeemScriptChunk.data); int sigCount = 0; int myIndex = redeemScript.findKeyInRedeem(signingKey); for (ScriptChunk chunk : existingChunks) { if (chunk.opcode == OP_0) { // OP_0, skip } else { Objects.requireNonNull(chunk.data); try { if (myIndex < redeemScript.findSigInRedeem(chunk.data, hash)) return sigCount; } catch (SignatureDecodeException e) { // ignore } sigCount++; } } return sigCount; } private int findKeyInRedeem(ECKey key) { checkArgument(chunks.get(0).isOpCode()); // P2SH scriptSig int numKeys = Script.decodeFromOpN(chunks.get(chunks.size() - 2).opcode); for (int i = 0 ; i < numKeys ; i++) { if (Arrays.equals(chunks.get(1 + i).data, key.getPubKey())) { return i; } } throw new IllegalStateException("Could not find matching key " + key.toString() + " in script " + this); } /** * Returns a list of the keys required by this script, assuming a multi-sig script. * * @throws ScriptException if the script type is not understood or is pay to address or is P2SH (run this method on the "Redeem script" instead). */ public List<ECKey> getPubKeys() { if (!ScriptPattern.isSentToMultisig(this)) throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Only usable for multisig scripts."); ArrayList<ECKey> result = new ArrayList<>(); int numKeys = Script.decodeFromOpN(chunks.get(chunks.size() - 2).opcode); for (int i = 0 ; i < numKeys ; i++) result.add(ECKey.fromPublicOnly(chunks.get(1 + i).data)); return result; } private int findSigInRedeem(byte[] signatureBytes, Sha256Hash hash) throws SignatureDecodeException { checkArgument(chunks.get(0).isOpCode()); // P2SH scriptSig int numKeys = Script.decodeFromOpN(chunks.get(chunks.size() - 2).opcode); TransactionSignature signature = TransactionSignature.decodeFromBitcoin(signatureBytes, true, false); for (int i = 0 ; i < numKeys ; i++) { if (ECKey.fromPublicOnly(chunks.get(i + 1).data).verify(hash, signature)) { return i; } } throw new IllegalStateException("Could not find matching key for signature on " + hash.toString() + " sig " + ByteUtils.formatHex(signatureBytes)); } ////////////////////// Interface used during verification of transactions/blocks //////////////////////////////// private static int getSigOpCount(List<ScriptChunk> chunks, boolean accurate) throws ScriptException { int sigOps = 0; int lastOpCode = OP_INVALIDOPCODE; for (ScriptChunk chunk : chunks) { if (chunk.isOpCode()) { switch (chunk.opcode) { case OP_CHECKSIG: case OP_CHECKSIGVERIFY: sigOps++; break; case OP_CHECKMULTISIG: case OP_CHECKMULTISIGVERIFY: if (accurate && lastOpCode >= OP_1 && lastOpCode <= OP_16) sigOps += decodeFromOpN(lastOpCode); else sigOps += 20; break; default: break; } lastOpCode = chunk.opcode; } } return sigOps; } public static int decodeFromOpN(int opcode) { checkArgument((opcode == OP_0 || opcode == OP_1NEGATE) || (opcode >= OP_1 && opcode <= OP_16), () -> "decodeFromOpN called on non OP_N opcode: " + ScriptOpCodes.getOpCodeName(opcode)); if (opcode == OP_0) return 0; else if (opcode == OP_1NEGATE) return -1; else return opcode + 1 - OP_1; } public static int encodeToOpN(int value) { checkArgument(value >= -1 && value <= 16, () -> "encodeToOpN called for " + value + " which we cannot encode in an opcode"); if (value == 0) return OP_0; else if (value == -1) return OP_1NEGATE; else return value - 1 + OP_1; } /** * Gets the count of regular SigOps in the script program (counting multisig ops as 20) */ public static int getSigOpCount(byte[] program) throws ScriptException { List<ScriptChunk> chunks = new ArrayList<>(5); // common size try { parseIntoChunks(program, chunks); } catch (ScriptException e) { // Ignore errors and count up to the parse-able length } return getSigOpCount(chunks, false); } /** * Gets the count of P2SH Sig Ops in the Script scriptSig */ public static long getP2SHSigOpCount(byte[] scriptSig) throws ScriptException { List<ScriptChunk> chunks = new ArrayList<>(5); // common size try { parseIntoChunks(scriptSig, chunks); } catch (ScriptException e) { // Ignore errors and count up to the parse-able length } Collections.reverse(chunks); for (ScriptChunk chunk : chunks) { if (!chunk.isOpCode()) { Script subScript = parse(chunk.data); return getSigOpCount(subScript.chunks, true); } } return 0; } /** * Returns number of signatures required to satisfy this script. */ public int getNumberOfSignaturesRequiredToSpend() { if (ScriptPattern.isSentToMultisig(this)) { // for N of M CHECKMULTISIG script we will need N signatures to spend ScriptChunk nChunk = chunks.get(0); return Script.decodeFromOpN(nChunk.opcode); } else if (ScriptPattern.isP2PKH(this) || ScriptPattern.isP2PK(this)) { // P2PKH and P2PK require single sig return 1; } else if (ScriptPattern.isP2SH(this)) { throw new IllegalStateException("For P2SH number of signatures depends on redeem script"); } else { throw new IllegalStateException("Unsupported script type"); } } /** * Returns number of bytes required to spend this script. It accepts optional ECKey and redeemScript that may * be required for certain types of script to estimate target size. */ public int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript) { if (ScriptPattern.isP2SH(this)) { // scriptSig: <sig> [sig] [sig...] <redeemscript> checkArgument(redeemScript != null, () -> "P2SH script requires redeemScript to be spent"); return redeemScript.getNumberOfSignaturesRequiredToSpend() * SIG_SIZE + redeemScript.program().length; } else if (ScriptPattern.isSentToMultisig(this)) { // scriptSig: OP_0 <sig> [sig] [sig...] return getNumberOfSignaturesRequiredToSpend() * SIG_SIZE + 1; } else if (ScriptPattern.isP2PK(this)) { // scriptSig: <sig> return SIG_SIZE; } else if (ScriptPattern.isP2PKH(this)) { // scriptSig: <sig> <pubkey> int uncompressedPubKeySize = 65; // very conservative return SIG_SIZE + (pubKey != null ? pubKey.getPubKey().length : uncompressedPubKeySize); } else if (ScriptPattern.isP2WPKH(this)) { // scriptSig is empty // witness: <sig> <pubKey> int compressedPubKeySize = 33; int publicKeyLength = pubKey != null ? pubKey.getPubKey().length : compressedPubKeySize; return VarInt.sizeOf(2) // number of witness pushes + VarInt.sizeOf(SIG_SIZE) // size of signature push + SIG_SIZE // signature push + VarInt.sizeOf(publicKeyLength) // size of pubKey push + publicKeyLength; // pubKey push } else { throw new IllegalStateException("Unsupported script type"); } } private static boolean equalsRange(byte[] a, int start, byte[] b) { if (start + b.length > a.length) return false; for (int i = 0; i < b.length; i++) if (a[i + start] != b[i]) return false; return true; } /** * Returns the script bytes of inputScript with all instances of the specified script object removed */ public static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove) { // We usually don't end up removing anything ByteArrayOutputStream bos = new ByteArrayOutputStream(inputScript.length); int cursor = 0; while (cursor < inputScript.length) { boolean skip = equalsRange(inputScript, cursor, chunkToRemove); int opcode = inputScript[cursor++] & 0xFF; int additionalBytes = 0; if (opcode >= 0 && opcode < OP_PUSHDATA1) { additionalBytes = opcode; } else if (opcode == OP_PUSHDATA1) { additionalBytes = (0xFF & inputScript[cursor]) + 1; } else if (opcode == OP_PUSHDATA2) { additionalBytes = ByteUtils.readUint16(inputScript, cursor) + 2; } else if (opcode == OP_PUSHDATA4) { additionalBytes = (int) ByteUtils.readUint32(inputScript, cursor) + 4; } if (!skip) { try { bos.write(opcode); bos.write(Arrays.copyOfRange(inputScript, cursor, cursor + additionalBytes)); } catch (IOException e) { throw new RuntimeException(e); } } cursor += additionalBytes; } return bos.toByteArray(); } /** * Returns the script bytes of inputScript with all instances of the given op code removed */ public static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode) { return removeAllInstancesOf(inputScript, new byte[] {(byte)opCode}); } ////////////////////// Script verification and helpers //////////////////////////////// private static boolean castToBool(byte[] data) { for (int i = 0; i < data.length; i++) { // "Can be negative zero" - Bitcoin Core (see OpenSSL's BN_bn2mpi) if (data[i] != 0) return !(i == data.length - 1 && (data[i] & 0xFF) == 0x80); } return false; } /** * Cast a script chunk to a BigInteger. * * @see #castToBigInteger(byte[], int, boolean) for values with different maximum * sizes. * @throws ScriptException if the chunk is longer than 4 bytes. */ private static BigInteger castToBigInteger(byte[] chunk, final boolean requireMinimal) throws ScriptException { return castToBigInteger(chunk, 4, requireMinimal); } /** * Cast a script chunk to a BigInteger. Normally you would want * {@link #castToBigInteger(byte[], boolean)} instead, this is only for cases where * the normal maximum length does not apply (i.e. CHECKLOCKTIMEVERIFY, CHECKSEQUENCEVERIFY). * * @param maxLength the maximum length in bytes. * @param requireMinimal check if the number is encoded with the minimum possible number of bytes * @throws ScriptException if the chunk is longer than the specified maximum. */ /* package private */ static BigInteger castToBigInteger(final byte[] chunk, final int maxLength, final boolean requireMinimal) throws ScriptException { if (chunk.length > maxLength) throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Script attempted to use an integer larger than " + maxLength + " bytes"); if (requireMinimal && chunk.length > 0) { // Check that the number is encoded with the minimum possible // number of bytes. // // If the most-significant-byte - excluding the sign bit - is zero // then we're not minimal. Note how this test also rejects the // negative-zero encoding, 0x80. if ((chunk[chunk.length - 1] & 0x7f) == 0) { // One exception: if there's more than one byte and the most // significant bit of the second-most-significant-byte is set // it would conflict with the sign bit. An example of this case // is +-255, which encode to 0xff00 and 0xff80 respectively. // (big-endian). if (chunk.length <= 1 || (chunk[chunk.length - 2] & 0x80) == 0) { throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "non-minimally encoded script number"); } } } return ByteUtils.decodeMPI(ByteUtils.reverseBytes(chunk), false); } /** * Exposes the script interpreter. Normally you should not use this directly, instead use * {@link TransactionInput#verify(TransactionOutput)} or * {@link Script#correctlySpends(Transaction, int, TransactionWitness, Coin, Script, Set)}. This method * is useful if you need more precise control or access to the final state of the stack. This interface is very * likely to change in future. */ public static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags) throws ScriptException { int opCount = 0; int lastCodeSepLocation = 0; LinkedList<byte[]> altstack = new LinkedList<>(); LinkedList<Boolean> ifStack = new LinkedList<>(); int nextLocationInScript = 0; for (ScriptChunk chunk : script.chunks) { boolean shouldExecute = !ifStack.contains(false); int opcode = chunk.opcode; nextLocationInScript += chunk.size(); // Check stack element size if (chunk.data != null && chunk.data.length > MAX_SCRIPT_ELEMENT_SIZE) throw new ScriptException(ScriptError.SCRIPT_ERR_PUSH_SIZE, "Attempted to push a data string larger than 520 bytes"); // Note how OP_RESERVED does not count towards the opcode limit. if (opcode > OP_16) { opCount++; if (opCount > MAX_OPS_PER_SCRIPT) throw new ScriptException(ScriptError.SCRIPT_ERR_OP_COUNT, "More script operations than is allowed"); } // Disabled opcodes. if (opcode == OP_CAT || opcode == OP_SUBSTR || opcode == OP_LEFT || opcode == OP_RIGHT || opcode == OP_INVERT || opcode == OP_AND || opcode == OP_OR || opcode == OP_XOR || opcode == OP_2MUL || opcode == OP_2DIV || opcode == OP_MUL || opcode == OP_DIV || opcode == OP_MOD || opcode == OP_LSHIFT || opcode == OP_RSHIFT) throw new ScriptException(ScriptError.SCRIPT_ERR_DISABLED_OPCODE, "Script included disabled Script Op " + ScriptOpCodes.getOpCodeName(opcode)); if (shouldExecute && OP_0 <= opcode && opcode <= OP_PUSHDATA4) { // Check minimal push if (verifyFlags.contains(VerifyFlag.MINIMALDATA) && !chunk.isShortestPossiblePushData()) throw new ScriptException(ScriptError.SCRIPT_ERR_MINIMALDATA, "Script included a not minimal push operation."); if (opcode == OP_0) stack.add(new byte[]{}); else stack.add(chunk.data); } else if (shouldExecute || (OP_IF <= opcode && opcode <= OP_ENDIF)){ switch (opcode) { case OP_IF: if (!shouldExecute) { ifStack.add(false); continue; } if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_UNBALANCED_CONDITIONAL, "Attempted OP_IF on an empty stack"); ifStack.add(castToBool(stack.pollLast())); continue; case OP_NOTIF: if (!shouldExecute) { ifStack.add(false); continue; } if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_UNBALANCED_CONDITIONAL, "Attempted OP_NOTIF on an empty stack"); ifStack.add(!castToBool(stack.pollLast())); continue; case OP_ELSE: if (ifStack.isEmpty()) throw new ScriptException(ScriptError.SCRIPT_ERR_UNBALANCED_CONDITIONAL, "Attempted OP_ELSE without OP_IF/NOTIF"); ifStack.add(!ifStack.pollLast()); continue; case OP_ENDIF: if (ifStack.isEmpty()) throw new ScriptException(ScriptError.SCRIPT_ERR_UNBALANCED_CONDITIONAL, "Attempted OP_ENDIF without OP_IF/NOTIF"); ifStack.pollLast(); continue; // OP_0 is no opcode case OP_1NEGATE: stack.add(ByteUtils.reverseBytes(ByteUtils.encodeMPI(BigInteger.ONE.negate(), false))); break; case OP_1: case OP_2: case OP_3: case OP_4: case OP_5: case OP_6: case OP_7: case OP_8: case OP_9: case OP_10: case OP_11: case OP_12: case OP_13: case OP_14: case OP_15: case OP_16: stack.add(ByteUtils.reverseBytes(ByteUtils.encodeMPI(BigInteger.valueOf(decodeFromOpN(opcode)), false))); break; case OP_NOP: break; case OP_VERIFY: if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_VERIFY on an empty stack"); if (!castToBool(stack.pollLast())) throw new ScriptException(ScriptError.SCRIPT_ERR_VERIFY, "OP_VERIFY failed"); break; case OP_RETURN: throw new ScriptException(ScriptError.SCRIPT_ERR_OP_RETURN, "Script called OP_RETURN"); case OP_TOALTSTACK: if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_TOALTSTACK on an empty stack"); altstack.add(stack.pollLast()); break; case OP_FROMALTSTACK: if (altstack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_ALTSTACK_OPERATION, "Attempted OP_FROMALTSTACK on an empty altstack"); stack.add(altstack.pollLast()); break; case OP_2DROP: if (stack.size() < 2) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_2DROP on a stack with size < 2"); stack.pollLast(); stack.pollLast(); break; case OP_2DUP: if (stack.size() < 2) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_2DUP on a stack with size < 2"); Iterator<byte[]> it2DUP = stack.descendingIterator(); byte[] OP2DUPtmpChunk2 = it2DUP.next(); stack.add(it2DUP.next()); stack.add(OP2DUPtmpChunk2); break; case OP_3DUP: if (stack.size() < 3) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_3DUP on a stack with size < 3"); Iterator<byte[]> it3DUP = stack.descendingIterator(); byte[] OP3DUPtmpChunk3 = it3DUP.next(); byte[] OP3DUPtmpChunk2 = it3DUP.next(); stack.add(it3DUP.next()); stack.add(OP3DUPtmpChunk2); stack.add(OP3DUPtmpChunk3); break; case OP_2OVER: if (stack.size() < 4) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_2OVER on a stack with size < 4"); Iterator<byte[]> it2OVER = stack.descendingIterator(); it2OVER.next(); it2OVER.next(); byte[] OP2OVERtmpChunk2 = it2OVER.next(); stack.add(it2OVER.next()); stack.add(OP2OVERtmpChunk2); break; case OP_2ROT: if (stack.size() < 6) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_2ROT on a stack with size < 6"); byte[] OP2ROTtmpChunk6 = stack.pollLast(); byte[] OP2ROTtmpChunk5 = stack.pollLast(); byte[] OP2ROTtmpChunk4 = stack.pollLast(); byte[] OP2ROTtmpChunk3 = stack.pollLast(); byte[] OP2ROTtmpChunk2 = stack.pollLast(); byte[] OP2ROTtmpChunk1 = stack.pollLast(); stack.add(OP2ROTtmpChunk3); stack.add(OP2ROTtmpChunk4); stack.add(OP2ROTtmpChunk5); stack.add(OP2ROTtmpChunk6); stack.add(OP2ROTtmpChunk1); stack.add(OP2ROTtmpChunk2); break; case OP_2SWAP: if (stack.size() < 4) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_2SWAP on a stack with size < 4"); byte[] OP2SWAPtmpChunk4 = stack.pollLast(); byte[] OP2SWAPtmpChunk3 = stack.pollLast(); byte[] OP2SWAPtmpChunk2 = stack.pollLast(); byte[] OP2SWAPtmpChunk1 = stack.pollLast(); stack.add(OP2SWAPtmpChunk3); stack.add(OP2SWAPtmpChunk4); stack.add(OP2SWAPtmpChunk1); stack.add(OP2SWAPtmpChunk2); break; case OP_IFDUP: if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_IFDUP on an empty stack"); if (castToBool(stack.getLast())) stack.add(stack.getLast()); break; case OP_DEPTH: stack.add(ByteUtils.reverseBytes(ByteUtils.encodeMPI(BigInteger.valueOf(stack.size()), false))); break; case OP_DROP: if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_DROP on an empty stack"); stack.pollLast(); break; case OP_DUP: if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_DUP on an empty stack"); stack.add(stack.getLast()); break; case OP_NIP: if (stack.size() < 2) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_NIP on a stack with size < 2"); byte[] OPNIPtmpChunk = stack.pollLast(); stack.pollLast(); stack.add(OPNIPtmpChunk); break; case OP_OVER: if (stack.size() < 2) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_OVER on a stack with size < 2"); Iterator<byte[]> itOVER = stack.descendingIterator(); itOVER.next(); stack.add(itOVER.next()); break; case OP_PICK: case OP_ROLL: if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_PICK/OP_ROLL on an empty stack"); long val = castToBigInteger(stack.pollLast(), verifyFlags.contains(VerifyFlag.MINIMALDATA)).longValue(); if (val < 0 || val >= stack.size()) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "OP_PICK/OP_ROLL attempted to get data deeper than stack size"); Iterator<byte[]> itPICK = stack.descendingIterator(); for (long i = 0; i < val; i++) itPICK.next(); byte[] OPROLLtmpChunk = itPICK.next(); if (opcode == OP_ROLL) itPICK.remove(); stack.add(OPROLLtmpChunk); break; case OP_ROT: if (stack.size() < 3) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_ROT on a stack with size < 3"); byte[] OPROTtmpChunk3 = stack.pollLast(); byte[] OPROTtmpChunk2 = stack.pollLast(); byte[] OPROTtmpChunk1 = stack.pollLast(); stack.add(OPROTtmpChunk2); stack.add(OPROTtmpChunk3); stack.add(OPROTtmpChunk1); break; case OP_SWAP: case OP_TUCK: if (stack.size() < 2) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_SWAP on a stack with size < 2"); byte[] OPSWAPtmpChunk2 = stack.pollLast(); byte[] OPSWAPtmpChunk1 = stack.pollLast(); stack.add(OPSWAPtmpChunk2); stack.add(OPSWAPtmpChunk1); if (opcode == OP_TUCK) stack.add(OPSWAPtmpChunk2); break; case OP_SIZE: if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_SIZE on an empty stack"); stack.add(ByteUtils.reverseBytes(ByteUtils.encodeMPI(BigInteger.valueOf(stack.getLast().length), false))); break; case OP_EQUAL: if (stack.size() < 2) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_EQUAL on a stack with size < 2"); stack.add(Arrays.equals(stack.pollLast(), stack.pollLast()) ? new byte[] {1} : new byte[] {}); break; case OP_EQUALVERIFY: if (stack.size() < 2) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_EQUALVERIFY on a stack with size < 2"); if (!Arrays.equals(stack.pollLast(), stack.pollLast())) throw new ScriptException(ScriptError.SCRIPT_ERR_EQUALVERIFY, "OP_EQUALVERIFY: non-equal data"); break; case OP_1ADD: case OP_1SUB: case OP_NEGATE: case OP_ABS: case OP_NOT: case OP_0NOTEQUAL: if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted a numeric op on an empty stack"); BigInteger numericOPnum = castToBigInteger(stack.pollLast(), verifyFlags.contains(VerifyFlag.MINIMALDATA)); switch (opcode) { case OP_1ADD: numericOPnum = numericOPnum.add(BigInteger.ONE); break; case OP_1SUB: numericOPnum = numericOPnum.subtract(BigInteger.ONE); break; case OP_NEGATE: numericOPnum = numericOPnum.negate(); break; case OP_ABS: if (numericOPnum.signum() < 0) numericOPnum = numericOPnum.negate(); break; case OP_NOT: if (numericOPnum.equals(BigInteger.ZERO)) numericOPnum = BigInteger.ONE; else numericOPnum = BigInteger.ZERO; break; case OP_0NOTEQUAL: if (numericOPnum.equals(BigInteger.ZERO)) numericOPnum = BigInteger.ZERO; else numericOPnum = BigInteger.ONE; break; default: throw new AssertionError("Unreachable"); } stack.add(ByteUtils.reverseBytes(ByteUtils.encodeMPI(numericOPnum, false))); break; case OP_ADD: case OP_SUB: case OP_BOOLAND: case OP_BOOLOR: case OP_NUMEQUAL: case OP_NUMNOTEQUAL: case OP_LESSTHAN: case OP_GREATERTHAN: case OP_LESSTHANOREQUAL: case OP_GREATERTHANOREQUAL: case OP_MIN: case OP_MAX: if (stack.size() < 2) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted a numeric op on a stack with size < 2"); BigInteger numericOPnum2 = castToBigInteger(stack.pollLast(), verifyFlags.contains(VerifyFlag.MINIMALDATA)); BigInteger numericOPnum1 = castToBigInteger(stack.pollLast(), verifyFlags.contains(VerifyFlag.MINIMALDATA)); BigInteger numericOPresult; switch (opcode) { case OP_ADD: numericOPresult = numericOPnum1.add(numericOPnum2); break; case OP_SUB: numericOPresult = numericOPnum1.subtract(numericOPnum2); break; case OP_BOOLAND: if (!numericOPnum1.equals(BigInteger.ZERO) && !numericOPnum2.equals(BigInteger.ZERO)) numericOPresult = BigInteger.ONE; else numericOPresult = BigInteger.ZERO; break; case OP_BOOLOR: if (!numericOPnum1.equals(BigInteger.ZERO) || !numericOPnum2.equals(BigInteger.ZERO)) numericOPresult = BigInteger.ONE; else numericOPresult = BigInteger.ZERO; break; case OP_NUMEQUAL: if (numericOPnum1.equals(numericOPnum2)) numericOPresult = BigInteger.ONE; else numericOPresult = BigInteger.ZERO; break; case OP_NUMNOTEQUAL: if (!numericOPnum1.equals(numericOPnum2)) numericOPresult = BigInteger.ONE; else numericOPresult = BigInteger.ZERO; break; case OP_LESSTHAN: if (numericOPnum1.compareTo(numericOPnum2) < 0) numericOPresult = BigInteger.ONE; else numericOPresult = BigInteger.ZERO; break; case OP_GREATERTHAN: if (numericOPnum1.compareTo(numericOPnum2) > 0) numericOPresult = BigInteger.ONE; else numericOPresult = BigInteger.ZERO; break; case OP_LESSTHANOREQUAL: if (numericOPnum1.compareTo(numericOPnum2) <= 0) numericOPresult = BigInteger.ONE; else numericOPresult = BigInteger.ZERO; break; case OP_GREATERTHANOREQUAL: if (numericOPnum1.compareTo(numericOPnum2) >= 0) numericOPresult = BigInteger.ONE; else numericOPresult = BigInteger.ZERO; break; case OP_MIN: if (numericOPnum1.compareTo(numericOPnum2) < 0) numericOPresult = numericOPnum1; else numericOPresult = numericOPnum2; break; case OP_MAX: if (numericOPnum1.compareTo(numericOPnum2) > 0) numericOPresult = numericOPnum1; else numericOPresult = numericOPnum2; break; default: throw new RuntimeException("Opcode switched at runtime?"); } stack.add(ByteUtils.reverseBytes(ByteUtils.encodeMPI(numericOPresult, false))); break; case OP_NUMEQUALVERIFY: if (stack.size() < 2) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_NUMEQUALVERIFY on a stack with size < 2"); BigInteger OPNUMEQUALVERIFYnum2 = castToBigInteger(stack.pollLast(), verifyFlags.contains(VerifyFlag.MINIMALDATA)); BigInteger OPNUMEQUALVERIFYnum1 = castToBigInteger(stack.pollLast(), verifyFlags.contains(VerifyFlag.MINIMALDATA)); if (!OPNUMEQUALVERIFYnum1.equals(OPNUMEQUALVERIFYnum2)) throw new ScriptException(ScriptError.SCRIPT_ERR_NUMEQUALVERIFY, "OP_NUMEQUALVERIFY failed"); break; case OP_WITHIN: if (stack.size() < 3) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_WITHIN on a stack with size < 3"); BigInteger OPWITHINnum3 = castToBigInteger(stack.pollLast(), verifyFlags.contains(VerifyFlag.MINIMALDATA)); BigInteger OPWITHINnum2 = castToBigInteger(stack.pollLast(), verifyFlags.contains(VerifyFlag.MINIMALDATA)); BigInteger OPWITHINnum1 = castToBigInteger(stack.pollLast(), verifyFlags.contains(VerifyFlag.MINIMALDATA)); if (OPWITHINnum2.compareTo(OPWITHINnum1) <= 0 && OPWITHINnum1.compareTo(OPWITHINnum3) < 0) stack.add(ByteUtils.reverseBytes(ByteUtils.encodeMPI(BigInteger.ONE, false))); else stack.add(ByteUtils.reverseBytes(ByteUtils.encodeMPI(BigInteger.ZERO, false))); break; case OP_RIPEMD160: if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_RIPEMD160 on an empty stack"); byte[] dataToHash = stack.pollLast(); byte[] ripmeMdHash = CryptoUtils.digestRipeMd160(dataToHash); stack.add(ripmeMdHash); break; case OP_SHA1: if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_SHA1 on an empty stack"); try { stack.add(MessageDigest.getInstance("SHA-1").digest(stack.pollLast())); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); // Cannot happen. } break; case OP_SHA256: if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_SHA256 on an empty stack"); stack.add(Sha256Hash.hash(stack.pollLast())); break; case OP_HASH160: if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_HASH160 on an empty stack"); stack.add(CryptoUtils.sha256hash160(stack.pollLast())); break; case OP_HASH256: if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_SHA256 on an empty stack"); stack.add(Sha256Hash.hashTwice(stack.pollLast())); break; case OP_CODESEPARATOR: lastCodeSepLocation = nextLocationInScript; break; case OP_CHECKSIG: case OP_CHECKSIGVERIFY: if (txContainingThis == null) throw new IllegalStateException("Script attempted signature check but no tx was provided"); executeCheckSig(txContainingThis, (int) index, script, stack, lastCodeSepLocation, opcode, verifyFlags); break; case OP_CHECKMULTISIG: case OP_CHECKMULTISIGVERIFY: if (txContainingThis == null) throw new IllegalStateException("Script attempted signature check but no tx was provided"); opCount = executeMultiSig(txContainingThis, (int) index, script, stack, opCount, lastCodeSepLocation, opcode, verifyFlags); break; case OP_CHECKLOCKTIMEVERIFY: if (!verifyFlags.contains(VerifyFlag.CHECKLOCKTIMEVERIFY)) { // not enabled; treat as a NOP2 if (verifyFlags.contains(VerifyFlag.DISCOURAGE_UPGRADABLE_NOPS)) { throw new ScriptException(ScriptError.SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS, "Script used a reserved opcode " + opcode); } break; } executeCheckLockTimeVerify(txContainingThis, (int) index, stack, verifyFlags); break; case OP_CHECKSEQUENCEVERIFY: if (!verifyFlags.contains(VerifyFlag.CHECKSEQUENCEVERIFY)) { // not enabled; treat as a NOP3 if (verifyFlags.contains(VerifyFlag.DISCOURAGE_UPGRADABLE_NOPS)) { throw new ScriptException(ScriptError.SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS, "Script used a reserved opcode " + opcode); } break; } executeCheckSequenceVerify(txContainingThis, (int) index, stack, verifyFlags); break; case OP_NOP1: case OP_NOP4: case OP_NOP5: case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10: if (verifyFlags.contains(VerifyFlag.DISCOURAGE_UPGRADABLE_NOPS)) { throw new ScriptException(ScriptError.SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS, "Script used a reserved opcode " + opcode); } break; default: throw new ScriptException(ScriptError.SCRIPT_ERR_BAD_OPCODE, "Script used a reserved or disabled opcode: " + opcode); } } if (stack.size() + altstack.size() > MAX_STACK_SIZE || stack.size() + altstack.size() < 0) throw new ScriptException(ScriptError.SCRIPT_ERR_STACK_SIZE, "Stack size exceeded range"); } if (!ifStack.isEmpty()) throw new ScriptException(ScriptError.SCRIPT_ERR_UNBALANCED_CONDITIONAL, "OP_IF/OP_NOTIF without OP_ENDIF"); } // This is more or less a direct translation of the code in Bitcoin Core private static void executeCheckLockTimeVerify(Transaction txContainingThis, int index, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags) throws ScriptException { if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_CHECKLOCKTIMEVERIFY on a stack with size < 1"); // Thus as a special case we tell CScriptNum to accept up // to 5-byte bignums to avoid year 2038 issue. final BigInteger nLockTime = castToBigInteger(stack.getLast(), 5, verifyFlags.contains(VerifyFlag.MINIMALDATA)); if (nLockTime.compareTo(BigInteger.ZERO) < 0) throw new ScriptException(ScriptError.SCRIPT_ERR_NEGATIVE_LOCKTIME, "Negative locktime"); // There are two kinds of nLockTime, need to ensure we're comparing apples-to-apples LockTime txContainingThisLockTime = txContainingThis.lockTime(); if (!( ((txContainingThisLockTime instanceof LockTime.HeightLock) && (nLockTime.compareTo(LOCKTIME_THRESHOLD_BIG)) < 0) || ((txContainingThisLockTime instanceof LockTime.TimeLock) && (nLockTime.compareTo(LOCKTIME_THRESHOLD_BIG)) >= 0)) ) throw new ScriptException(ScriptError.SCRIPT_ERR_UNSATISFIED_LOCKTIME, "Lock time requirement type mismatch"); // Now that we know we're comparing apples-to-apples, the // comparison is a simple numeric one. if (nLockTime.compareTo(BigInteger.valueOf(txContainingThisLockTime.rawValue())) > 0) throw new ScriptException(ScriptError.SCRIPT_ERR_UNSATISFIED_LOCKTIME, "Lock time requirement not satisfied"); // Finally the nLockTime feature can be disabled and thus // CHECKLOCKTIMEVERIFY bypassed if every txin has been // finalized by setting nSequence to maxint. The // transaction would be allowed into the blockchain, making // the opcode ineffective. // // Testing if this vin is not final is sufficient to // prevent this condition. Alternatively we could test all // inputs, but testing just this input minimizes the data // required to prove correct CHECKLOCKTIMEVERIFY execution. if (!txContainingThis.getInput(index).hasSequence()) throw new ScriptException(ScriptError.SCRIPT_ERR_UNSATISFIED_LOCKTIME, "Transaction contains a final transaction input for a CHECKLOCKTIMEVERIFY script."); } private static void executeCheckSequenceVerify(Transaction txContainingThis, int index, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags) throws ScriptException { if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_CHECKSEQUENCEVERIFY on a stack with size < 1"); // Note that elsewhere numeric opcodes are limited to // operands in the range -2**31+1 to 2**31-1, however it is // legal for opcodes to produce results exceeding that // range. This limitation is implemented by CScriptNum's // default 4-byte limit. // // Thus as a special case we tell CScriptNum to accept up // to 5-byte bignums, which are good until 2**39-1, well // beyond the 2**32-1 limit of the nSequence field itself. final long nSequence = castToBigInteger(stack.getLast(), 5, verifyFlags.contains(VerifyFlag.MINIMALDATA)).longValue(); // In the rare event that the argument may be < 0 due to // some arithmetic being done first, you can always use // 0 MAX CHECKSEQUENCEVERIFY. if (nSequence < 0) throw new ScriptException(ScriptError.SCRIPT_ERR_NEGATIVE_LOCKTIME, "Negative sequence"); // To provide for future soft-fork extensibility, if the // operand has the disabled lock-time flag set, // CHECKSEQUENCEVERIFY behaves as a NOP. if ((nSequence & TransactionInput.SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0) return; // Compare the specified sequence number with the input. checkSequence(nSequence, txContainingThis, index); } private static void checkSequence(long nSequence, Transaction txContainingThis, int index) { // Relative lock times are supported by comparing the passed // in operand to the sequence number of the input. long txToSequence = txContainingThis.getInput(index).getSequenceNumber(); // Fail if the transaction's version number is not set high // enough to trigger BIP 68 rules. if (txContainingThis.getVersion() < 2) throw new ScriptException(ScriptError.SCRIPT_ERR_UNSATISFIED_LOCKTIME, "Transaction version is < 2"); // Sequence numbers with their most significant bit set are not // consensus constrained. Testing that the transaction's sequence // number do not have this bit set prevents using this property // to get around a CHECKSEQUENCEVERIFY check. if ((txToSequence & TransactionInput.SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0) throw new ScriptException(ScriptError.SCRIPT_ERR_UNSATISFIED_LOCKTIME, "Sequence disable flag is set"); // Mask off any bits that do not have consensus-enforced meaning // before doing the integer comparisons long nLockTimeMask = TransactionInput.SEQUENCE_LOCKTIME_TYPE_FLAG | TransactionInput.SEQUENCE_LOCKTIME_MASK; long txToSequenceMasked = txToSequence & nLockTimeMask; long nSequenceMasked = nSequence & nLockTimeMask; // There are two kinds of nSequence: lock-by-blockheight // and lock-by-blocktime, distinguished by whether // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG. // // We want to compare apples to apples, so fail the script // unless the type of nSequenceMasked being tested is the same as // the nSequenceMasked in the transaction. if (!((txToSequenceMasked < TransactionInput.SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < TransactionInput.SEQUENCE_LOCKTIME_TYPE_FLAG) || (txToSequenceMasked >= TransactionInput.SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= TransactionInput.SEQUENCE_LOCKTIME_TYPE_FLAG))) { throw new ScriptException(ScriptError.SCRIPT_ERR_UNSATISFIED_LOCKTIME, "Relative locktime requirement type mismatch"); } // Now that we know we're comparing apples-to-apples, the // comparison is a simple numeric one. if (nSequenceMasked > txToSequenceMasked) throw new ScriptException(ScriptError.SCRIPT_ERR_UNSATISFIED_LOCKTIME, "Relative locktime requirement not satisfied"); } private static void executeCheckSig(Transaction txContainingThis, int index, Script script, LinkedList<byte[]> stack, int lastCodeSepLocation, int opcode, Set<VerifyFlag> verifyFlags) throws ScriptException { final boolean requireCanonical = verifyFlags.contains(VerifyFlag.STRICTENC) || verifyFlags.contains(VerifyFlag.DERSIG) || verifyFlags.contains(VerifyFlag.LOW_S); if (stack.size() < 2) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_CHECKSIG(VERIFY) on a stack with size < 2"); byte[] pubKey = stack.pollLast(); byte[] sigBytes = stack.pollLast(); byte[] prog = script.program(); byte[] connectedScript = Arrays.copyOfRange(prog, lastCodeSepLocation, prog.length); ByteArrayOutputStream outStream = new ByteArrayOutputStream(sigBytes.length + 1); try { writeBytes(outStream, sigBytes); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen } connectedScript = removeAllInstancesOf(connectedScript, outStream.toByteArray()); // TODO: Use int for indexes everywhere, we can't have that many inputs/outputs boolean sigValid = false; try { TransactionSignature sig = TransactionSignature.decodeFromBitcoin(sigBytes, requireCanonical, verifyFlags.contains(VerifyFlag.LOW_S)); // TODO: Should check hash type is known Sha256Hash hash = txContainingThis.hashForSignature(index, connectedScript, (byte) sig.sighashFlags); sigValid = ECKey.verify(hash.getBytes(), sig, pubKey); } catch (VerificationException.NoncanonicalSignature e) { throw new ScriptException(ScriptError.SCRIPT_ERR_SIG_DER, "Script contains non-canonical signature"); } catch (SignatureDecodeException e) { // This exception occurs when signing as we run partial/invalid scripts to see if they need more // signing work to be done inside LocalTransactionSigner.signInputs. // FIXME don't rely on exception message if (e.getMessage() != null && !e.getMessage().contains("Reached past end of ASN.1 stream")) // Don't put critical code here; the above check is not reliable on HotSpot due to optimization: // http://jawspeak.com/2010/05/26/hotspot-caused-exceptions-to-lose-their-stack-traces-in-production-and-the-fix/ log.warn("Signature parsing failed!", e); } catch (Exception e) { log.warn("Signature checking failed!", e); } if (opcode == OP_CHECKSIG) stack.add(sigValid ? new byte[] {1} : new byte[] {}); else if (opcode == OP_CHECKSIGVERIFY) if (!sigValid) throw new ScriptException(ScriptError.SCRIPT_ERR_CHECKSIGVERIFY, "Script failed OP_CHECKSIGVERIFY"); } private static int executeMultiSig(Transaction txContainingThis, int index, Script script, LinkedList<byte[]> stack, int opCount, int lastCodeSepLocation, int opcode, Set<VerifyFlag> verifyFlags) throws ScriptException { final boolean requireCanonical = verifyFlags.contains(VerifyFlag.STRICTENC) || verifyFlags.contains(VerifyFlag.DERSIG) || verifyFlags.contains(VerifyFlag.LOW_S); if (stack.size() < 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_CHECKMULTISIG(VERIFY) on a stack with size < 2"); int pubKeyCount = castToBigInteger(stack.pollLast(), verifyFlags.contains(VerifyFlag.MINIMALDATA)).intValue(); if (pubKeyCount < 0 || pubKeyCount > MAX_PUBKEYS_PER_MULTISIG) throw new ScriptException(ScriptError.SCRIPT_ERR_PUBKEY_COUNT, "OP_CHECKMULTISIG(VERIFY) with pubkey count out of range"); opCount += pubKeyCount; if (opCount > MAX_OPS_PER_SCRIPT) throw new ScriptException(ScriptError.SCRIPT_ERR_OP_COUNT, "Total op count > 201 during OP_CHECKMULTISIG(VERIFY)"); if (stack.size() < pubKeyCount + 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_CHECKMULTISIG(VERIFY) on a stack with size < num_of_pubkeys + 2"); LinkedList<byte[]> pubkeys = new LinkedList<>(); for (int i = 0; i < pubKeyCount; i++) { byte[] pubKey = stack.pollLast(); pubkeys.add(pubKey); } int sigCount = castToBigInteger(stack.pollLast(), verifyFlags.contains(VerifyFlag.MINIMALDATA)).intValue(); if (sigCount < 0 || sigCount > pubKeyCount) throw new ScriptException(ScriptError.SCRIPT_ERR_SIG_COUNT, "OP_CHECKMULTISIG(VERIFY) with sig count out of range"); if (stack.size() < sigCount + 1) throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_CHECKMULTISIG(VERIFY) on a stack with size < num_of_pubkeys + num_of_signatures + 3"); LinkedList<byte[]> sigs = new LinkedList<>(); for (int i = 0; i < sigCount; i++) { byte[] sig = stack.pollLast(); sigs.add(sig); } byte[] prog = script.program(); byte[] connectedScript = Arrays.copyOfRange(prog, lastCodeSepLocation, prog.length); for (byte[] sig : sigs) { ByteArrayOutputStream outStream = new ByteArrayOutputStream(sig.length + 1); try { writeBytes(outStream, sig); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen } connectedScript = removeAllInstancesOf(connectedScript, outStream.toByteArray()); } boolean valid = true; while (sigs.size() > 0) { byte[] pubKey = pubkeys.pollFirst(); // We could reasonably move this out of the loop, but because signature verification is significantly // more expensive than hashing, its not a big deal. try { TransactionSignature sig = TransactionSignature.decodeFromBitcoin(sigs.getFirst(), requireCanonical, false); Sha256Hash hash = txContainingThis.hashForSignature(index, connectedScript, (byte) sig.sighashFlags); if (ECKey.verify(hash.getBytes(), sig, pubKey)) sigs.pollFirst(); } catch (Exception e) { // There is (at least) one exception that could be hit here (EOFException, if the sig is too short) // Because I can't verify there aren't more, we use a very generic Exception catch } if (sigs.size() > pubkeys.size()) { valid = false; break; } } // We uselessly remove a stack object to emulate a Bitcoin Core bug. byte[] nullDummy = stack.pollLast(); if (verifyFlags.contains(VerifyFlag.NULLDUMMY) && nullDummy.length > 0) throw new ScriptException(ScriptError.SCRIPT_ERR_SIG_NULLFAIL, "OP_CHECKMULTISIG(VERIFY) with non-null nulldummy: " + Arrays.toString(nullDummy)); if (opcode == OP_CHECKMULTISIG) { stack.add(valid ? new byte[] {1} : new byte[] {}); } else if (opcode == OP_CHECKMULTISIGVERIFY) { if (!valid) throw new ScriptException(ScriptError.SCRIPT_ERR_SIG_NULLFAIL, "Script failed OP_CHECKMULTISIGVERIFY"); } return opCount; } /** * Verifies that this script (interpreted as a scriptSig) correctly spends the given scriptPubKey. * @param txContainingThis The transaction in which this input scriptSig resides. * Accessing txContainingThis from another thread while this method runs results in undefined behavior. * @param scriptSigIndex The index in txContainingThis of the scriptSig (note: NOT the index of the scriptPubKey). * @param scriptPubKey The connected scriptPubKey containing the conditions needed to claim the value. * @param witness Transaction witness belonging to the transaction input containing this script. Needed for segwit. * @param value Value of the output. Needed for segwit scripts. * @param verifyFlags Each flag enables one validation rule. */ public void correctlySpends(Transaction txContainingThis, int scriptSigIndex, @Nullable TransactionWitness witness, @Nullable Coin value, Script scriptPubKey, Set<VerifyFlag> verifyFlags) throws ScriptException { if (ScriptPattern.isP2WPKH(scriptPubKey)) { // For segwit, full validation isn't implemented. So we simply check the signature. P2SH_P2WPKH is handled // by the P2SH code for now. if (witness.getPushCount() < 2) throw new ScriptException(ScriptError.SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY, witness.toString()); TransactionSignature signature; try { signature = TransactionSignature.decodeFromBitcoin(witness.getPush(0), true, true); } catch (SignatureDecodeException x) { throw new ScriptException(ScriptError.SCRIPT_ERR_SIG_DER, "Cannot decode", x); } ECKey pubkey = ECKey.fromPublicOnly(witness.getPush(1)); Script scriptCode = ScriptBuilder.createP2PKHOutputScript(pubkey); Sha256Hash sigHash = txContainingThis.hashForWitnessSignature(scriptSigIndex, scriptCode, value, signature.sigHashMode(), false); boolean validSig = pubkey.verify(sigHash, signature); if (!validSig) throw new ScriptException(ScriptError.SCRIPT_ERR_CHECKSIGVERIFY, "Invalid signature"); } else if (ScriptPattern.isP2PKH(scriptPubKey)) { if (chunks.size() != 2) throw new ScriptException(ScriptError.SCRIPT_ERR_SCRIPT_SIZE, "Invalid size: " + chunks.size()); TransactionSignature signature; try { signature = TransactionSignature.decodeFromBitcoin(chunks.get(0).data, true, true); } catch (SignatureDecodeException x) { throw new ScriptException(ScriptError.SCRIPT_ERR_SIG_DER, "Cannot decode", x); } ECKey pubkey = ECKey.fromPublicOnly(chunks.get(1).data); Sha256Hash sigHash = txContainingThis.hashForSignature(scriptSigIndex, scriptPubKey, signature.sigHashMode(), false); boolean validSig = pubkey.verify(sigHash, signature); if (!validSig) throw new ScriptException(ScriptError.SCRIPT_ERR_CHECKSIGVERIFY, "Invalid signature"); } else if (ScriptPattern.isP2PK(scriptPubKey)) { if (chunks.size() != 1) throw new ScriptException(ScriptError.SCRIPT_ERR_SCRIPT_SIZE, "Invalid size: " + chunks.size()); TransactionSignature signature; try { signature = TransactionSignature.decodeFromBitcoin(chunks.get(0).data, false, false); } catch (SignatureDecodeException x) { throw new ScriptException(ScriptError.SCRIPT_ERR_SIG_DER, "Cannot decode", x); } ECKey pubkey = ECKey.fromPublicOnly(ScriptPattern.extractKeyFromP2PK(scriptPubKey)); Sha256Hash sigHash = txContainingThis.hashForSignature(scriptSigIndex, scriptPubKey, signature.sigHashMode(), false); boolean validSig = pubkey.verify(sigHash, signature); if (!validSig) throw new ScriptException(ScriptError.SCRIPT_ERR_CHECKSIGVERIFY, "Invalid signature"); } else { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, verifyFlags); } } /** * Verifies that this script (interpreted as a scriptSig) correctly spends the given scriptPubKey. * @param txContainingThis The transaction in which this input scriptSig resides. * Accessing txContainingThis from another thread while this method runs results in undefined behavior. * @param scriptSigIndex The index in txContainingThis of the scriptSig (note: NOT the index of the scriptPubKey). * @param scriptPubKey The connected scriptPubKey containing the conditions needed to claim the value. * @param verifyFlags Each flag enables one validation rule. * @deprecated Use {@link #correctlySpends(Transaction, int, TransactionWitness, Coin, Script, Set)} instead. */ @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags) throws ScriptException { // Clone the transaction because executing the script involves editing it, and if we die, we'll leave // the tx half broken (also it's not so thread safe to work on it directly. try { txContainingThis = Transaction.read(ByteBuffer.wrap(txContainingThis.serialize())); } catch (ProtocolException e) { throw new RuntimeException(e); // Should not happen unless we were given a totally broken transaction. } if (program().length > MAX_SCRIPT_SIZE || scriptPubKey.program().length > MAX_SCRIPT_SIZE) throw new ScriptException(ScriptError.SCRIPT_ERR_SCRIPT_SIZE, "Script larger than 10,000 bytes"); LinkedList<byte[]> stack = new LinkedList<>(); LinkedList<byte[]> p2shStack = null; executeScript(txContainingThis, scriptSigIndex, this, stack, verifyFlags); if (verifyFlags.contains(VerifyFlag.P2SH)) p2shStack = new LinkedList<>(stack); executeScript(txContainingThis, scriptSigIndex, scriptPubKey, stack, verifyFlags); if (stack.size() == 0) throw new ScriptException(ScriptError.SCRIPT_ERR_EVAL_FALSE, "Stack empty at end of script execution."); List<byte[]> stackCopy = new LinkedList<>(stack); if (!castToBool(stack.pollLast())) throw new ScriptException(ScriptError.SCRIPT_ERR_EVAL_FALSE, "Script resulted in a non-true stack: " + Utils.toString(stackCopy)); // P2SH is pay to script hash. It means that the scriptPubKey has a special form which is a valid // program but it has "useless" form that if evaluated as a normal program always returns true. // Instead, miners recognize it as special based on its template - it provides a hash of the real scriptPubKey // and that must be provided by the input. The goal of this bizarre arrangement is twofold: // // (1) You can sum up a large, complex script (like a CHECKMULTISIG script) with an address that's the same // size as a regular address. This means it doesn't overload scannable QR codes/NFC tags or become // un-wieldy to copy/paste. // (2) It allows the working set to be smaller: nodes perform best when they can store as many unspent outputs // in RAM as possible, so if the outputs are made smaller and the inputs get bigger, then it's better for // overall scalability and performance. // TODO: Check if we can take out enforceP2SH if there's a checkpoint at the enforcement block. if (verifyFlags.contains(VerifyFlag.P2SH) && ScriptPattern.isP2SH(scriptPubKey)) { for (ScriptChunk chunk : chunks) if (!chunk.isPushData()) throw new ScriptException(ScriptError.SCRIPT_ERR_SIG_PUSHONLY, "Attempted to spend a P2SH scriptPubKey with a script that contained the script op " + chunk); byte[] scriptPubKeyBytes = p2shStack.pollLast(); Script scriptPubKeyP2SH = Script.parse(scriptPubKeyBytes); executeScript(txContainingThis, scriptSigIndex, scriptPubKeyP2SH, p2shStack, verifyFlags); if (p2shStack.size() == 0) throw new ScriptException(ScriptError.SCRIPT_ERR_EVAL_FALSE, "P2SH stack empty at end of script execution."); List<byte[]> p2shStackCopy = new LinkedList<>(p2shStack); if (!castToBool(p2shStack.pollLast())) throw new ScriptException(ScriptError.SCRIPT_ERR_EVAL_FALSE, "P2SH script execution resulted in a non-true stack: " + Utils.toString(p2shStackCopy)); } } // Utility that doesn't copy for internal use private byte[] getQuickProgram() { if (program != null) return program; return program(); } /** * Get the {@link ScriptType}. * @return The script type, or null if the script is of unknown type */ public @Nullable ScriptType getScriptType() { if (ScriptPattern.isP2PKH(this)) return ScriptType.P2PKH; if (ScriptPattern.isP2PK(this)) return ScriptType.P2PK; if (ScriptPattern.isP2SH(this)) return ScriptType.P2SH; if (ScriptPattern.isP2WPKH(this)) return ScriptType.P2WPKH; if (ScriptPattern.isP2WSH(this)) return ScriptType.P2WSH; if (ScriptPattern.isP2TR(this)) return ScriptType.P2TR; return null; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return Arrays.equals(getQuickProgram(), ((Script)o).getQuickProgram()); } @Override public int hashCode() { return Arrays.hashCode(getQuickProgram()); } }
93,907
49.981542
186
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/script/ScriptBuilder.java
/* * Copyright 2013 Google Inc. * Copyright 2018 Nicola Atzei * Copyright 2019 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. */ package org.bitcoinj.script; import org.bitcoinj.base.Address; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.base.LegacyAddress; import org.bitcoinj.base.SegwitAddress; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.Transaction; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.base.ScriptType; import org.bitcoinj.crypto.internal.CryptoUtils; import javax.annotation.Nullable; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Stack; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; import static org.bitcoinj.script.ScriptOpCodes.OP_0; import static org.bitcoinj.script.ScriptOpCodes.OP_1NEGATE; import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKMULTISIG; import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKSIG; import static org.bitcoinj.script.ScriptOpCodes.OP_DUP; import static org.bitcoinj.script.ScriptOpCodes.OP_EQUAL; import static org.bitcoinj.script.ScriptOpCodes.OP_EQUALVERIFY; import static org.bitcoinj.script.ScriptOpCodes.OP_HASH160; import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA1; import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA2; import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA4; import static org.bitcoinj.script.ScriptOpCodes.OP_RETURN; /** * <p>Tools for the construction of commonly used script types. You don't normally need this as it's hidden behind * convenience methods on {@link Transaction}, but they are useful when working with the * protocol at a lower level.</p> */ public class ScriptBuilder { private final List<ScriptChunk> chunks; private Instant creationTime = TimeUtils.currentTime(); /** Creates a fresh ScriptBuilder with an empty program. */ public ScriptBuilder() { chunks = new LinkedList<>(); } /** Creates a fresh ScriptBuilder with the given program as the starting point. */ public ScriptBuilder(Script template) { chunks = new ArrayList<>(template.chunks()); } /** * Sets the creation time to build the script with. If this is not set, the current time is used by the builder. * * @param creationTime creation time to build the script with * @return this builder */ public ScriptBuilder creationTime(Instant creationTime) { this.creationTime = Objects.requireNonNull(creationTime); return this; } /** Adds the given chunk to the end of the program */ public ScriptBuilder addChunk(ScriptChunk chunk) { return addChunk(chunks.size(), chunk); } /** Adds the given chunk at the given index in the program */ public ScriptBuilder addChunk(int index, ScriptChunk chunk) { chunks.add(index, chunk); return this; } /** Adds the given opcode to the end of the program. */ public ScriptBuilder op(int opcode) { return op(chunks.size(), opcode); } /** Adds the given opcode to the given index in the program */ public ScriptBuilder op(int index, int opcode) { checkArgument(opcode > OP_PUSHDATA4); return addChunk(index, new ScriptChunk(opcode, null)); } /** Adds a copy of the given byte array as a data element (i.e. PUSHDATA) at the end of the program. */ public ScriptBuilder data(byte[] data) { if (data.length == 0) return smallNum(0); else return data(chunks.size(), data); } /** Adds a copy of the given byte array as a data element (i.e. PUSHDATA) at the given index in the program. */ public ScriptBuilder data(int index, byte[] data) { // implements BIP62 byte[] copy = Arrays.copyOf(data, data.length); int opcode; if (data.length == 0) { opcode = OP_0; } else if (data.length == 1) { byte b = data[0]; if (b >= 1 && b <= 16) opcode = Script.encodeToOpN(b); else opcode = 1; } else if (data.length < OP_PUSHDATA1) { opcode = data.length; } else if (data.length < 256) { opcode = OP_PUSHDATA1; } else if (data.length < 65536) { opcode = OP_PUSHDATA2; } else { throw new RuntimeException("Unimplemented"); } return addChunk(index, new ScriptChunk(opcode, copy)); } /** * Adds the given number to the end of the program. Automatically uses * shortest encoding possible. */ public ScriptBuilder number(long num) { return number(chunks.size(), num); } /** * Adds the given number to the given index in the program. Automatically * uses shortest encoding possible. */ public ScriptBuilder number(int index, long num) { if (num == -1) { return op(index, OP_1NEGATE); } else if (num >= 0 && num <= 16) { return smallNum(index, (int) num); } else { return bigNum(index, num); } } /** * Adds the given number as a OP_N opcode to the end of the program. * Only handles values 0-16 inclusive. * * @see #number(long) */ public ScriptBuilder smallNum(int num) { return smallNum(chunks.size(), num); } /** Adds the given number as a push data chunk. * This is intended to use for negative numbers or values greater than 16, and although * it will accept numbers in the range 0-16 inclusive, the encoding would be * considered non-standard. * * @see #number(long) */ protected ScriptBuilder bigNum(long num) { return bigNum(chunks.size(), num); } /** * Adds the given number as a OP_N opcode to the given index in the program. * Only handles values 0-16 inclusive. * * @see #number(long) */ public ScriptBuilder smallNum(int index, int num) { checkArgument(num >= 0, () -> "cannot encode negative numbers with smallNum"); checkArgument(num <= 16, () -> "cannot encode numbers larger than 16 with smallNum"); return addChunk(index, new ScriptChunk(Script.encodeToOpN(num), null)); } /** * Adds the given number as a push data chunk to the given index in the program. * This is intended to use for negative numbers or values greater than 16, and although * it will accept numbers in the range 0-16 inclusive, the encoding would be * considered non-standard. * * @see #number(long) */ protected ScriptBuilder bigNum(int index, long num) { final byte[] data; if (num == 0) { data = new byte[0]; } else { Stack<Byte> result = new Stack<>(); final boolean neg = num < 0; long absvalue = Math.abs(num); while (absvalue != 0) { result.push((byte) (absvalue & 0xff)); absvalue >>= 8; } if ((result.peek() & 0x80) != 0) { // The most significant byte is >= 0x80, so push an extra byte that // contains just the sign of the value. result.push((byte) (neg ? 0x80 : 0)); } else if (neg) { // The most significant byte is < 0x80 and the value is negative, // set the sign bit so it is subtracted and interpreted as a // negative when converting back to an integral. result.push((byte) (result.pop() | 0x80)); } data = new byte[result.size()]; for (int byteIdx = 0; byteIdx < data.length; byteIdx++) { data[byteIdx] = result.get(byteIdx); } } // At most the encoded value could take up to 8 bytes, so we don't need // to use OP_PUSHDATA opcodes return addChunk(index, new ScriptChunk(data.length, data)); } /** * Adds true to the end of the program. * @return this */ public ScriptBuilder opTrue() { return number(1); // it push OP_1/OP_TRUE } /** * Adds true to the given index in the program. * @param index at which insert true * @return this */ public ScriptBuilder opTrue(int index) { return number(index, 1); // push OP_1/OP_TRUE } /** * Adds false to the end of the program. * @return this */ public ScriptBuilder opFalse() { return number(0); // push OP_0/OP_FALSE } /** * Adds false to the given index in the program. * @param index at which insert true * @return this */ public ScriptBuilder opFalse(int index) { return number(index, 0); // push OP_0/OP_FALSE } /** Creates a new immutable Script based on the state of the builder. */ public Script build() { return Script.of(chunks, creationTime); } /** Creates an empty script. */ public static Script createEmpty() { return new ScriptBuilder().build(); } /** * Creates a scriptPubKey that encodes payment to the given address. * * @param to address to send payment to * @param creationTime creation time of the scriptPubKey * @return scriptPubKey */ public static Script createOutputScript(Address to, Instant creationTime) { return new ScriptBuilder().outputScript(to).creationTime(creationTime).build(); } /** * Creates a scriptPubKey that encodes payment to the given address. The creation time will be the current time. * * @param to address to send payment to * @return scriptPubKey */ public static Script createOutputScript(Address to) { return new ScriptBuilder().outputScript(to).build(); } private ScriptBuilder outputScript(Address to) { checkState(chunks.isEmpty()); if (to instanceof LegacyAddress) { ScriptType scriptType = to.getOutputScriptType(); if (scriptType == ScriptType.P2PKH) p2pkhOutputScript(((LegacyAddress) to).getHash()); else if (scriptType == ScriptType.P2SH) p2shOutputScript(((LegacyAddress) to).getHash()); else throw new IllegalStateException("Cannot handle " + scriptType); } else if (to instanceof SegwitAddress) { p2whOutputScript((SegwitAddress) to); } else { throw new IllegalStateException("Cannot handle " + to); } return this; } private ScriptBuilder p2whOutputScript(SegwitAddress address) { checkState(chunks.isEmpty()); // OP_0 <pubKeyHash|scriptHash> return smallNum(address.getWitnessVersion()) .data(address.getWitnessProgram()); } /** * Creates a scriptSig that can redeem a P2PKH output. * If given signature is null, incomplete scriptSig will be created with OP_0 instead of signature */ public static Script createInputScript(@Nullable TransactionSignature signature, ECKey pubKey) { byte[] pubkeyBytes = pubKey.getPubKey(); byte[] sigBytes = signature != null ? signature.encodeToBitcoin() : new byte[]{}; return new ScriptBuilder().data(sigBytes).data(pubkeyBytes).build(); } /** * Creates a scriptSig that can redeem a P2PK output. * If given signature is null, incomplete scriptSig will be created with OP_0 instead of signature */ public static Script createInputScript(@Nullable TransactionSignature signature) { byte[] sigBytes = signature != null ? signature.encodeToBitcoin() : new byte[]{}; return new ScriptBuilder().data(sigBytes).build(); } /** Creates a program that requires at least N of the given keys to sign, using OP_CHECKMULTISIG. */ public static Script createMultiSigOutputScript(int threshold, List<ECKey> pubkeys) { checkArgument(threshold > 0); checkArgument(threshold <= pubkeys.size()); checkArgument(pubkeys.size() <= 16); // That's the max we can represent with a single opcode. ScriptBuilder builder = new ScriptBuilder(); builder.smallNum(threshold); for (ECKey key : pubkeys) { builder.data(key.getPubKey()); } builder.smallNum(pubkeys.size()); builder.op(OP_CHECKMULTISIG); return builder.build(); } /** Create a program that satisfies an OP_CHECKMULTISIG program. */ public static Script createMultiSigInputScript(List<TransactionSignature> signatures) { List<byte[]> sigs = new ArrayList<>(signatures.size()); for (TransactionSignature signature : signatures) { sigs.add(signature.encodeToBitcoin()); } return createMultiSigInputScriptBytes(sigs, null); } /** Create a program that satisfies an OP_CHECKMULTISIG program. */ public static Script createMultiSigInputScript(TransactionSignature... signatures) { return createMultiSigInputScript(Arrays.asList(signatures)); } /** Create a program that satisfies an OP_CHECKMULTISIG program, using pre-encoded signatures. */ public static Script createMultiSigInputScriptBytes(List<byte[]> signatures) { return createMultiSigInputScriptBytes(signatures, null); } /** * Create a program that satisfies a P2SH OP_CHECKMULTISIG program. * If given signature list is null, incomplete scriptSig will be created with OP_0 instead of signatures */ public static Script createP2SHMultiSigInputScript(@Nullable List<TransactionSignature> signatures, Script multisigProgram) { List<byte[]> sigs = new ArrayList<>(); if (signatures == null) { // create correct number of empty signatures int numSigs = multisigProgram.getNumberOfSignaturesRequiredToSpend(); for (int i = 0; i < numSigs; i++) sigs.add(new byte[]{}); } else { for (TransactionSignature signature : signatures) { sigs.add(signature.encodeToBitcoin()); } } return createMultiSigInputScriptBytes(sigs, multisigProgram.program()); } /** * Create a program that satisfies an OP_CHECKMULTISIG program, using pre-encoded signatures. * Optionally, appends the script program bytes if spending a P2SH output. */ public static Script createMultiSigInputScriptBytes(List<byte[]> signatures, @Nullable byte[] multisigProgramBytes) { checkArgument(signatures.size() <= 16); ScriptBuilder builder = new ScriptBuilder(); builder.smallNum(0); // Work around a bug in CHECKMULTISIG that is now a required part of the protocol. for (byte[] signature : signatures) builder.data(signature); if (multisigProgramBytes!= null) builder.data(multisigProgramBytes); return builder.build(); } /** * Returns a copy of the given scriptSig with the signature inserted in the given position. * * This function assumes that any missing sigs have OP_0 placeholders. If given scriptSig already has all the signatures * in place, IllegalArgumentException will be thrown. * * @param targetIndex where to insert the signature * @param sigsPrefixCount how many items to copy verbatim (e.g. initial OP_0 for multisig) * @param sigsSuffixCount how many items to copy verbatim at end (e.g. redeemScript for P2SH) */ public static Script updateScriptWithSignature(Script scriptSig, byte[] signature, int targetIndex, int sigsPrefixCount, int sigsSuffixCount) { ScriptBuilder builder = new ScriptBuilder(); List<ScriptChunk> inputChunks = scriptSig.chunks(); int totalChunks = inputChunks.size(); // Check if we have a place to insert, otherwise just return given scriptSig unchanged. // We assume here that OP_0 placeholders always go after the sigs, so // to find if we have sigs missing, we can just check the chunk in latest sig position boolean hasMissingSigs = inputChunks.get(totalChunks - sigsSuffixCount - 1).equalsOpCode(OP_0); checkArgument(hasMissingSigs, () -> "scriptSig is already filled with signatures"); // copy the prefix for (ScriptChunk chunk: inputChunks.subList(0, sigsPrefixCount)) builder.addChunk(chunk); // copy the sigs int pos = 0; boolean inserted = false; for (ScriptChunk chunk: inputChunks.subList(sigsPrefixCount, totalChunks - sigsSuffixCount)) { if (pos == targetIndex) { inserted = true; builder.data(signature); pos++; } if (!chunk.equalsOpCode(OP_0)) { builder.addChunk(chunk); pos++; } } // add OP_0's if needed, since we skipped them in the previous loop while (pos < totalChunks - sigsPrefixCount - sigsSuffixCount) { if (pos == targetIndex) { inserted = true; builder.data(signature); } else { builder.addChunk(new ScriptChunk(OP_0, null)); } pos++; } // copy the suffix for (ScriptChunk chunk: inputChunks.subList(totalChunks - sigsSuffixCount, totalChunks)) builder.addChunk(chunk); checkState(inserted); return builder.build(); } /** Creates a scriptPubKey that encodes payment to the given raw public key. */ public static Script createP2PKOutputScript(byte[] pubKey) { return new ScriptBuilder().data(pubKey).op(OP_CHECKSIG).build(); } /** Creates a scriptPubKey that encodes payment to the given raw public key. */ public static Script createP2PKOutputScript(ECKey pubKey) { return createP2PKOutputScript(pubKey.getPubKey()); } /** * Creates a scriptPubKey that sends to the given public key hash. */ public static Script createP2PKHOutputScript(byte[] hash) { return new ScriptBuilder().p2pkhOutputScript(hash).build(); } private ScriptBuilder p2pkhOutputScript(byte[] hash) { checkArgument(hash.length == LegacyAddress.LENGTH); checkState(chunks.isEmpty()); return op(OP_DUP) .op(OP_HASH160) .data(hash) .op(OP_EQUALVERIFY) .op(OP_CHECKSIG); } /** * Creates a scriptPubKey that sends to the given public key. */ public static Script createP2PKHOutputScript(ECKey key) { checkArgument(key.isCompressed()); return createP2PKHOutputScript(key.getPubKeyHash()); } /** * Creates a segwit scriptPubKey that sends to the given public key hash. */ public static Script createP2WPKHOutputScript(byte[] hash) { checkArgument(hash.length == SegwitAddress.WITNESS_PROGRAM_LENGTH_PKH); return new ScriptBuilder().smallNum(0).data(hash).build(); } /** * Creates a segwit scriptPubKey that sends to the given public key. */ public static Script createP2WPKHOutputScript(ECKey key) { checkArgument(key.isCompressed()); return createP2WPKHOutputScript(key.getPubKeyHash()); } /** * Creates a scriptPubKey that sends to the given script hash. Read * <a href="https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki">BIP 16</a> to learn more about this * kind of script. * * @param hash The hash of the redeem script * @return an output script that sends to the redeem script */ public static Script createP2SHOutputScript(byte[] hash) { return new ScriptBuilder().p2shOutputScript(hash).build(); } private ScriptBuilder p2shOutputScript(byte[] hash) { checkArgument(hash.length == 20); checkState(chunks.isEmpty()); return op(OP_HASH160) .data(hash) .op(OP_EQUAL); } /** * Creates a scriptPubKey for a given redeem script. * * @param redeemScript The redeem script * @return an output script that sends to the redeem script */ public static Script createP2SHOutputScript(Script redeemScript) { byte[] hash = CryptoUtils.sha256hash160(redeemScript.program()); return ScriptBuilder.createP2SHOutputScript(hash); } /** * Creates a segwit scriptPubKey that sends to the given script hash. */ public static Script createP2WSHOutputScript(byte[] hash) { checkArgument(hash.length == SegwitAddress.WITNESS_PROGRAM_LENGTH_SH); return new ScriptBuilder().smallNum(0).data(hash).build(); } /** * Creates a segwit scriptPubKey for the given redeem script. */ public static Script createP2WSHOutputScript(Script redeemScript) { byte[] hash = Sha256Hash.hash(redeemScript.program()); return ScriptBuilder.createP2WSHOutputScript(hash); } /** * Creates a P2SH output script for n-of-m multisig with given public keys and threshold. Given public keys will * be placed in redeem script in the lexicographical sorting order. * * @param threshold The threshold number of keys that must sign (n) * @param pubkeys A list of m public keys * @return The P2SH multisig output script */ public static Script createP2SHOutputScript(int threshold, List<ECKey> pubkeys) { Script redeemScript = createRedeemScript(threshold, pubkeys); return createP2SHOutputScript(redeemScript); } /** * Creates an n-of-m multisig redeem script with given public keys and threshold. Given public keys will be placed in * redeem script in the lexicographical sorting order. * * @param threshold The threshold number of keys that must sign (n) * @param pubkeys A list of m public keys * @return The P2SH multisig redeem script */ public static Script createRedeemScript(int threshold, List<ECKey> pubkeys) { pubkeys = new ArrayList<>(pubkeys); Collections.sort(pubkeys, ECKey.PUBKEY_COMPARATOR); return ScriptBuilder.createMultiSigOutputScript(threshold, pubkeys); } /** * Creates a script of the form OP_RETURN [data]. This feature allows you to attach a small piece of data (like * a hash of something stored elsewhere) to a zero valued output which can never be spent and thus does not pollute * the ledger. */ public static Script createOpReturnScript(byte[] data) { checkArgument(data.length <= 80); return new ScriptBuilder().op(OP_RETURN).data(data).build(); } }
23,710
37.243548
124
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/script/ScriptException.java
/* * Copyright 2011 Google Inc. * * 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. */ package org.bitcoinj.script; import org.bitcoinj.core.VerificationException; @SuppressWarnings("serial") public class ScriptException extends VerificationException { private final ScriptError err; public ScriptException(ScriptError err, String msg) { super(msg); this.err = err; } public ScriptException(ScriptError err, String msg, Exception e) { super(msg, e); this.err = err; } public ScriptError getError() { return err; } }
1,098
26.475
75
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/script/ScriptOpCodes.java
/* * Copyright 2013 Google Inc. * * 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. */ package org.bitcoinj.script; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableBiMap; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Various constants that define the assembly-like scripting language that forms part of the Bitcoin protocol. * See {@link Script} for details. Also provides a method to convert them to a string. */ public class ScriptOpCodes { // push value public static final int OP_0 = 0x00; // push empty vector public static final int OP_FALSE = OP_0; public static final int OP_PUSHDATA1 = 0x4c; public static final int OP_PUSHDATA2 = 0x4d; public static final int OP_PUSHDATA4 = 0x4e; public static final int OP_1NEGATE = 0x4f; public static final int OP_RESERVED = 0x50; public static final int OP_1 = 0x51; public static final int OP_TRUE = OP_1; public static final int OP_2 = 0x52; public static final int OP_3 = 0x53; public static final int OP_4 = 0x54; public static final int OP_5 = 0x55; public static final int OP_6 = 0x56; public static final int OP_7 = 0x57; public static final int OP_8 = 0x58; public static final int OP_9 = 0x59; public static final int OP_10 = 0x5a; public static final int OP_11 = 0x5b; public static final int OP_12 = 0x5c; public static final int OP_13 = 0x5d; public static final int OP_14 = 0x5e; public static final int OP_15 = 0x5f; public static final int OP_16 = 0x60; // control public static final int OP_NOP = 0x61; public static final int OP_VER = 0x62; public static final int OP_IF = 0x63; public static final int OP_NOTIF = 0x64; public static final int OP_VERIF = 0x65; public static final int OP_VERNOTIF = 0x66; public static final int OP_ELSE = 0x67; public static final int OP_ENDIF = 0x68; public static final int OP_VERIFY = 0x69; public static final int OP_RETURN = 0x6a; // stack ops public static final int OP_TOALTSTACK = 0x6b; public static final int OP_FROMALTSTACK = 0x6c; public static final int OP_2DROP = 0x6d; public static final int OP_2DUP = 0x6e; public static final int OP_3DUP = 0x6f; public static final int OP_2OVER = 0x70; public static final int OP_2ROT = 0x71; public static final int OP_2SWAP = 0x72; public static final int OP_IFDUP = 0x73; public static final int OP_DEPTH = 0x74; public static final int OP_DROP = 0x75; public static final int OP_DUP = 0x76; public static final int OP_NIP = 0x77; public static final int OP_OVER = 0x78; public static final int OP_PICK = 0x79; public static final int OP_ROLL = 0x7a; public static final int OP_ROT = 0x7b; public static final int OP_SWAP = 0x7c; public static final int OP_TUCK = 0x7d; // splice ops public static final int OP_CAT = 0x7e; public static final int OP_SUBSTR = 0x7f; public static final int OP_LEFT = 0x80; public static final int OP_RIGHT = 0x81; public static final int OP_SIZE = 0x82; // bit logic public static final int OP_INVERT = 0x83; public static final int OP_AND = 0x84; public static final int OP_OR = 0x85; public static final int OP_XOR = 0x86; public static final int OP_EQUAL = 0x87; public static final int OP_EQUALVERIFY = 0x88; public static final int OP_RESERVED1 = 0x89; public static final int OP_RESERVED2 = 0x8a; // numeric public static final int OP_1ADD = 0x8b; public static final int OP_1SUB = 0x8c; public static final int OP_2MUL = 0x8d; public static final int OP_2DIV = 0x8e; public static final int OP_NEGATE = 0x8f; public static final int OP_ABS = 0x90; public static final int OP_NOT = 0x91; public static final int OP_0NOTEQUAL = 0x92; public static final int OP_ADD = 0x93; public static final int OP_SUB = 0x94; public static final int OP_MUL = 0x95; public static final int OP_DIV = 0x96; public static final int OP_MOD = 0x97; public static final int OP_LSHIFT = 0x98; public static final int OP_RSHIFT = 0x99; public static final int OP_BOOLAND = 0x9a; public static final int OP_BOOLOR = 0x9b; public static final int OP_NUMEQUAL = 0x9c; public static final int OP_NUMEQUALVERIFY = 0x9d; public static final int OP_NUMNOTEQUAL = 0x9e; public static final int OP_LESSTHAN = 0x9f; public static final int OP_GREATERTHAN = 0xa0; public static final int OP_LESSTHANOREQUAL = 0xa1; public static final int OP_GREATERTHANOREQUAL = 0xa2; public static final int OP_MIN = 0xa3; public static final int OP_MAX = 0xa4; public static final int OP_WITHIN = 0xa5; // crypto public static final int OP_RIPEMD160 = 0xa6; public static final int OP_SHA1 = 0xa7; public static final int OP_SHA256 = 0xa8; public static final int OP_HASH160 = 0xa9; public static final int OP_HASH256 = 0xaa; public static final int OP_CODESEPARATOR = 0xab; public static final int OP_CHECKSIG = 0xac; public static final int OP_CHECKSIGVERIFY = 0xad; public static final int OP_CHECKMULTISIG = 0xae; public static final int OP_CHECKMULTISIGVERIFY = 0xaf; // block state /** Check lock time of the block. Introduced in BIP 65, replacing OP_NOP2 */ public static final int OP_CHECKLOCKTIMEVERIFY = 0xb1; public static final int OP_CHECKSEQUENCEVERIFY = 0xb2; // expansion public static final int OP_NOP1 = 0xb0; /** Deprecated by BIP 65 */ @Deprecated public static final int OP_NOP2 = OP_CHECKLOCKTIMEVERIFY; /** Deprecated by BIP 112 */ @Deprecated public static final int OP_NOP3 = OP_CHECKSEQUENCEVERIFY; public static final int OP_NOP4 = 0xb3; public static final int OP_NOP5 = 0xb4; public static final int OP_NOP6 = 0xb5; public static final int OP_NOP7 = 0xb6; public static final int OP_NOP8 = 0xb7; public static final int OP_NOP9 = 0xb8; public static final int OP_NOP10 = 0xb9; public static final int OP_INVALIDOPCODE = 0xff; private static final BiMap<Integer, String> opCodeMap = ImmutableBiMap.<Integer, String>builder() .put(OP_0, "0") .put(OP_PUSHDATA1, "PUSHDATA1") .put(OP_PUSHDATA2, "PUSHDATA2") .put(OP_PUSHDATA4, "PUSHDATA4") .put(OP_1NEGATE, "1NEGATE") .put(OP_RESERVED, "RESERVED") .put(OP_1, "1") .put(OP_2, "2") .put(OP_3, "3") .put(OP_4, "4") .put(OP_5, "5") .put(OP_6, "6") .put(OP_7, "7") .put(OP_8, "8") .put(OP_9, "9") .put(OP_10, "10") .put(OP_11, "11") .put(OP_12, "12") .put(OP_13, "13") .put(OP_14, "14") .put(OP_15, "15") .put(OP_16, "16") .put(OP_NOP, "NOP") .put(OP_VER, "VER") .put(OP_IF, "IF") .put(OP_NOTIF, "NOTIF") .put(OP_VERIF, "VERIF") .put(OP_VERNOTIF, "VERNOTIF") .put(OP_ELSE, "ELSE") .put(OP_ENDIF, "ENDIF") .put(OP_VERIFY, "VERIFY") .put(OP_RETURN, "RETURN") .put(OP_TOALTSTACK, "TOALTSTACK") .put(OP_FROMALTSTACK, "FROMALTSTACK") .put(OP_2DROP, "2DROP") .put(OP_2DUP, "2DUP") .put(OP_3DUP, "3DUP") .put(OP_2OVER, "2OVER") .put(OP_2ROT, "2ROT") .put(OP_2SWAP, "2SWAP") .put(OP_IFDUP, "IFDUP") .put(OP_DEPTH, "DEPTH") .put(OP_DROP, "DROP") .put(OP_DUP, "DUP") .put(OP_NIP, "NIP") .put(OP_OVER, "OVER") .put(OP_PICK, "PICK") .put(OP_ROLL, "ROLL") .put(OP_ROT, "ROT") .put(OP_SWAP, "SWAP") .put(OP_TUCK, "TUCK") .put(OP_CAT, "CAT") .put(OP_SUBSTR, "SUBSTR") .put(OP_LEFT, "LEFT") .put(OP_RIGHT, "RIGHT") .put(OP_SIZE, "SIZE") .put(OP_INVERT, "INVERT") .put(OP_AND, "AND") .put(OP_OR, "OR") .put(OP_XOR, "XOR") .put(OP_EQUAL, "EQUAL") .put(OP_EQUALVERIFY, "EQUALVERIFY") .put(OP_RESERVED1, "RESERVED1") .put(OP_RESERVED2, "RESERVED2") .put(OP_1ADD, "1ADD") .put(OP_1SUB, "1SUB") .put(OP_2MUL, "2MUL") .put(OP_2DIV, "2DIV") .put(OP_NEGATE, "NEGATE") .put(OP_ABS, "ABS") .put(OP_NOT, "NOT") .put(OP_0NOTEQUAL, "0NOTEQUAL") .put(OP_ADD, "ADD") .put(OP_SUB, "SUB") .put(OP_MUL, "MUL") .put(OP_DIV, "DIV") .put(OP_MOD, "MOD") .put(OP_LSHIFT, "LSHIFT") .put(OP_RSHIFT, "RSHIFT") .put(OP_BOOLAND, "BOOLAND") .put(OP_BOOLOR, "BOOLOR") .put(OP_NUMEQUAL, "NUMEQUAL") .put(OP_NUMEQUALVERIFY, "NUMEQUALVERIFY") .put(OP_NUMNOTEQUAL, "NUMNOTEQUAL") .put(OP_LESSTHAN, "LESSTHAN") .put(OP_GREATERTHAN, "GREATERTHAN") .put(OP_LESSTHANOREQUAL, "LESSTHANOREQUAL") .put(OP_GREATERTHANOREQUAL, "GREATERTHANOREQUAL") .put(OP_MIN, "MIN") .put(OP_MAX, "MAX") .put(OP_WITHIN, "WITHIN") .put(OP_RIPEMD160, "RIPEMD160") .put(OP_SHA1, "SHA1") .put(OP_SHA256, "SHA256") .put(OP_HASH160, "HASH160") .put(OP_HASH256, "HASH256") .put(OP_CODESEPARATOR, "CODESEPARATOR") .put(OP_CHECKSIG, "CHECKSIG") .put(OP_CHECKSIGVERIFY, "CHECKSIGVERIFY") .put(OP_CHECKMULTISIG, "CHECKMULTISIG") .put(OP_CHECKMULTISIGVERIFY, "CHECKMULTISIGVERIFY") .put(OP_NOP1, "NOP1") .put(OP_CHECKLOCKTIMEVERIFY, "CHECKLOCKTIMEVERIFY") .put(OP_CHECKSEQUENCEVERIFY, "CHECKSEQUENCEVERIFY") .put(OP_NOP4, "NOP4") .put(OP_NOP5, "NOP5") .put(OP_NOP6, "NOP6") .put(OP_NOP7, "NOP7") .put(OP_NOP8, "NOP8") .put(OP_NOP9, "NOP9") .put(OP_NOP10, "NOP10").build(); private static final Map<String, Integer> opCodeNameMap = createOpCodeNameMap(); private static Map<String, Integer> createOpCodeNameMap() { Map<String, Integer> map = new HashMap<>(opCodeMap.inverse()); map.put("OP_FALSE", OP_FALSE); map.put("OP_TRUE", OP_TRUE); map.put("NOP2", OP_NOP2); map.put("NOP3", OP_NOP3); return Collections.unmodifiableMap(map); } /** * Converts the given OpCode into a string (eg "0", "PUSHDATA", or "NON_OP(10)") */ public static String getOpCodeName(int opcode) { if (opCodeMap.containsKey(opcode)) return opCodeMap.get(opcode); return "NON_OP(" + opcode + ")"; } /** * Converts the given pushdata OpCode into a string (eg "PUSHDATA2", or "PUSHDATA(23)") */ public static String getPushDataName(int opcode) { if (opCodeMap.containsKey(opcode)) return opCodeMap.get(opcode); return "PUSHDATA(" + opcode + ")"; } /** * Converts the given OpCodeName into an int */ public static int getOpCode(String opCodeName) { if (opCodeNameMap.containsKey(opCodeName)) return opCodeNameMap.get(opCodeName); return OP_INVALIDOPCODE; } }
11,776
35.348765
110
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/script/ScriptError.java
/* * Copyright 2017 Nicola Atzei * * 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. */ package org.bitcoinj.script; import java.util.HashMap; import java.util.Map; public enum ScriptError { SCRIPT_ERR_OK("OK"), SCRIPT_ERR_UNKNOWN_ERROR("UNKNOWN_ERROR"), SCRIPT_ERR_EVAL_FALSE("EVAL_FALSE"), SCRIPT_ERR_OP_RETURN("OP_RETURN"), /* Max sizes */ SCRIPT_ERR_SCRIPT_SIZE("SCRIPT_SIZE"), SCRIPT_ERR_PUSH_SIZE("PUSH_SIZE"), SCRIPT_ERR_OP_COUNT("OP_COUNT"), SCRIPT_ERR_STACK_SIZE("STACK_SIZE"), SCRIPT_ERR_SIG_COUNT("SIG_COUNT"), SCRIPT_ERR_PUBKEY_COUNT("PUBKEY_COUNT"), /* Failed verify operations */ SCRIPT_ERR_VERIFY("VERIFY"), SCRIPT_ERR_EQUALVERIFY("EQUALVERIFY"), SCRIPT_ERR_CHECKMULTISIGVERIFY("CHECKMULTISIGVERIFY"), SCRIPT_ERR_CHECKSIGVERIFY("CHECKSIGVERIFY"), SCRIPT_ERR_NUMEQUALVERIFY("NUMEQUALVERIFY"), /* Logical/Format/Canonical errors */ SCRIPT_ERR_BAD_OPCODE("BAD_OPCODE"), SCRIPT_ERR_DISABLED_OPCODE("DISABLED_OPCODE"), SCRIPT_ERR_INVALID_STACK_OPERATION("INVALID_STACK_OPERATION"), SCRIPT_ERR_INVALID_ALTSTACK_OPERATION("INVALID_ALTSTACK_OPERATION"), SCRIPT_ERR_UNBALANCED_CONDITIONAL("UNBALANCED_CONDITIONAL"), /* CHECKLOCKTIMEVERIFY and CHECKSEQUENCEVERIFY */ SCRIPT_ERR_NEGATIVE_LOCKTIME("NEGATIVE_LOCKTIME"), SCRIPT_ERR_UNSATISFIED_LOCKTIME("UNSATISFIED_LOCKTIME"), /* Malleability */ SCRIPT_ERR_SIG_HASHTYPE("SIG_HASHTYPE"), SCRIPT_ERR_SIG_DER("SIG_DER"), SCRIPT_ERR_MINIMALDATA("MINIMALDATA"), SCRIPT_ERR_SIG_PUSHONLY("SIG_PUSHONLY"), SCRIPT_ERR_SIG_HIGH_S("SIG_HIGH_S"), SCRIPT_ERR_SIG_NULLDUMMY("SIG_NULLDUMMY"), SCRIPT_ERR_PUBKEYTYPE("PUBKEYTYPE"), SCRIPT_ERR_CLEANSTACK("CLEANSTACK"), SCRIPT_ERR_MINIMALIF("MINIMALIF"), SCRIPT_ERR_SIG_NULLFAIL("NULLFAIL"), /* softfork safeness */ SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS("DISCOURAGE_UPGRADABLE_NOPS"), SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM("DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"), /* segregated witness */ SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH("WITNESS_PROGRAM_WRONG_LENGTH"), SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY("WITNESS_PROGRAM_WITNESS_EMPTY"), SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH("WITNESS_PROGRAM_MISMATCH"), SCRIPT_ERR_WITNESS_MALLEATED("WITNESS_MALLEATED"), SCRIPT_ERR_WITNESS_MALLEATED_P2SH("WITNESS_MALLEATED_P2SH"), SCRIPT_ERR_WITNESS_UNEXPECTED("WITNESS_UNEXPECTED"), SCRIPT_ERR_WITNESS_PUBKEYTYPE("WITNESS_PUBKEYTYPE"), SCRIPT_ERR_ERROR_COUNT("ERROR_COUNT"); private final String mnemonic; private static final Map<String, ScriptError> mnemonicToScriptErrorMap; ScriptError(String name) { this.mnemonic = name; } static { mnemonicToScriptErrorMap = new HashMap<>(); for (ScriptError err : ScriptError.values()) { mnemonicToScriptErrorMap.put(err.getMnemonic(), err); } } public String getMnemonic() { return mnemonic; } public static ScriptError fromMnemonic(String name) { ScriptError err = mnemonicToScriptErrorMap.get(name); if (err == null) throw new IllegalArgumentException(name + " is not a valid name"); return err; } }
3,773
34.271028
94
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/script/ScriptChunk.java
/* * Copyright 2013 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. */ package org.bitcoinj.script; import org.bitcoinj.base.internal.ByteUtils; import javax.annotation.Nullable; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.Objects; import static org.bitcoinj.base.internal.Preconditions.checkState; import static org.bitcoinj.script.ScriptOpCodes.OP_0; import static org.bitcoinj.script.ScriptOpCodes.OP_1; import static org.bitcoinj.script.ScriptOpCodes.OP_16; import static org.bitcoinj.script.ScriptOpCodes.OP_1NEGATE; import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA1; import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA2; import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA4; import static org.bitcoinj.script.ScriptOpCodes.getOpCodeName; import static org.bitcoinj.script.ScriptOpCodes.getPushDataName; /** * A script element that is either a data push (signature, pubkey, etc) or a non-push (logic, numeric, etc) operation. */ public class ScriptChunk { /** Operation to be executed. Opcodes are defined in {@link ScriptOpCodes}. */ public final int opcode; /** * For push operations, this is the vector to be pushed on the stack. For {@link ScriptOpCodes#OP_0}, the vector is * empty. Null for non-push operations. */ @Nullable public final byte[] data; public ScriptChunk(int opcode, @Nullable byte[] data) { this.opcode = opcode; this.data = data; } public boolean equalsOpCode(int opcode) { return opcode == this.opcode; } /** * If this chunk is a single byte of non-pushdata content (could be OP_RESERVED or some invalid Opcode) */ public boolean isOpCode() { return opcode > OP_PUSHDATA4; } /** * Returns true if this chunk is pushdata content, including the single-byte pushdatas. */ public boolean isPushData() { return opcode <= OP_16; } /** If this chunk is an OP_N opcode returns the equivalent integer value. */ public int decodeOpN() { return Script.decodeFromOpN(opcode); } /** * Called on a pushdata chunk, returns true if it uses the smallest possible way (according to BIP62) to push the data. */ public boolean isShortestPossiblePushData() { checkState(isPushData()); if (data == null) return true; // OP_N if (data.length == 0) return opcode == OP_0; if (data.length == 1) { byte b = data[0]; if (b >= 0x01 && b <= 0x10) return opcode == OP_1 + b - 1; if ((b & 0xFF) == 0x81) return opcode == OP_1NEGATE; } if (data.length < OP_PUSHDATA1) return opcode == data.length; if (data.length < 256) return opcode == OP_PUSHDATA1; if (data.length < 65536) return opcode == OP_PUSHDATA2; // can never be used, but implemented for completeness return opcode == OP_PUSHDATA4; } public void write(OutputStream stream) throws IOException { if (isOpCode()) { checkState(data == null); stream.write(opcode); } else if (data != null) { if (opcode < OP_PUSHDATA1) { checkState(data.length == opcode); stream.write(opcode); } else if (opcode == OP_PUSHDATA1) { checkState(data.length <= 0xFF); stream.write(OP_PUSHDATA1); stream.write(data.length); } else if (opcode == OP_PUSHDATA2) { checkState(data.length <= 0xFFFF); stream.write(OP_PUSHDATA2); ByteUtils.writeInt16LE(data.length, stream); } else if (opcode == OP_PUSHDATA4) { checkState(data.length <= Script.MAX_SCRIPT_ELEMENT_SIZE); stream.write(OP_PUSHDATA4); ByteUtils.writeInt32LE(data.length, stream); } else { throw new RuntimeException("Unimplemented"); } stream.write(data); } else { stream.write(opcode); // smallNum } } public byte[] toByteArray() { ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { write(stream); } catch (IOException e) { // Should not happen as ByteArrayOutputStream does not throw IOException on write throw new RuntimeException(e); } return stream.toByteArray(); } /* * The size, in bytes, that this chunk would occupy if serialized into a Script. */ public int size() { final int opcodeLength = 1; int pushDataSizeLength = 0; if (opcode == OP_PUSHDATA1) pushDataSizeLength = 1; else if (opcode == OP_PUSHDATA2) pushDataSizeLength = 2; else if (opcode == OP_PUSHDATA4) pushDataSizeLength = 4; final int dataLength = data == null ? 0 : data.length; return opcodeLength + pushDataSizeLength + dataLength; } @Override public String toString() { if (data == null) return getOpCodeName(opcode); return String.format("%s[%s]", getPushDataName(opcode), ByteUtils.formatHex(data)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ScriptChunk other = (ScriptChunk) o; return opcode == other.opcode && Arrays.equals(data, other.data); } @Override public int hashCode() { return Objects.hash(opcode, Arrays.hashCode(data)); } }
6,322
33.36413
123
java
bitcoinj
bitcoinj-master/examples/src/main/java/org/bitcoinj/examples/FetchTransactions.java
/* * Copyright 2012 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. */ package org.bitcoinj.examples; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Network; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.*; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.MemoryBlockStore; import org.bitcoinj.utils.BriefLogFormatter; import java.net.InetAddress; import java.util.List; import java.util.concurrent.Future; /** * Downloads the given transaction and its dependencies from a peers memory pool then prints them out. */ public class FetchTransactions { public static void main(String[] args) throws Exception { BriefLogFormatter.init(); System.out.println("Connecting to node"); final Network network = BitcoinNetwork.TESTNET; final NetworkParameters params = NetworkParameters.of(network); BlockStore blockStore = new MemoryBlockStore(params.getGenesisBlock()); BlockChain chain = new BlockChain(params, blockStore); PeerGroup peerGroup = new PeerGroup(network, chain); peerGroup.start(); peerGroup.addAddress(PeerAddress.localhost(params)); peerGroup.waitForPeers(1).get(); Peer peer = peerGroup.getConnectedPeers().get(0); Sha256Hash txHash = Sha256Hash.wrap(args[0]); Future<Transaction> future = peer.getPeerMempoolTransaction(txHash); System.out.println("Waiting for node to send us the requested transaction: " + txHash); Transaction tx = future.get(); System.out.println(tx); System.out.println("Waiting for node to send us the dependencies ..."); List<Transaction> deps = peer.downloadDependencies(tx).get(); for (Transaction dep : deps) { System.out.println("Got dependency " + dep.getTxId()); } System.out.println("Done."); peerGroup.stop(); } }
2,469
36.424242
102
java
bitcoinj
bitcoinj-master/examples/src/main/java/org/bitcoinj/examples/ForwardingService.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.examples; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.Address; import org.bitcoinj.base.Coin; import org.bitcoinj.base.AddressParser; import org.bitcoinj.core.Context; import org.bitcoinj.base.DefaultAddressParser; import org.bitcoinj.core.Transaction; import org.bitcoinj.kits.WalletAppKit; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.wallet.CoinSelection; import org.bitcoinj.wallet.CoinSelector; import org.bitcoinj.wallet.SendRequest; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.listeners.WalletCoinsReceivedEventListener; import java.io.Closeable; import java.io.File; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.toList; /** * ForwardingService demonstrates basic usage of bitcoinj. It creates an SPV Wallet, listens on the network * and when it receives coins, simply sends them onwards to the address given on the command line. */ public class ForwardingService implements Closeable { static final String USAGE = "Usage: address-to-forward-to [mainnet|testnet|signet|regtest]"; static final int REQUIRED_CONFIRMATIONS = 1; static final int MAX_CONNECTIONS = 4; private final AddressParser addressParser = new DefaultAddressParser(); private final BitcoinNetwork network; private final Address forwardingAddress; private volatile WalletAppKit kit; /** * Run the forwarding service as a command line tool * @param args See {@link #USAGE} */ public static void main(String[] args) { // This line makes the log output more compact and easily read, especially when using the JDK log adapter. BriefLogFormatter.init(); Context.propagate(new Context()); if (args.length < 1 || args.length > 2) { System.err.println(USAGE); System.exit(1); } // Create and run the service, which will listen for transactions and forward coins until stopped try (ForwardingService forwardingService = new ForwardingService(args)) { forwardingService.run(); // Wait for Control-C try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException ignored) {} } } /** * Initialize by parsing the network and forwarding address command-line arguments. * * @param args the arguments from {@link #main(String[])} */ public ForwardingService(String[] args) { if (args.length >= 2) { // If network was specified, validate address against network network = BitcoinNetwork.fromString(args[1]).orElseThrow(); forwardingAddress = addressParser.parseAddress(args[0], network); } else { // Else network not-specified, extract network from address forwardingAddress = addressParser.parseAddressAnyNetwork(args[0]); network = (BitcoinNetwork) forwardingAddress.network(); } } /** * Start the wallet and register the coin-forwarding listener. */ public void run() { System.out.println("Network: " + network.id()); System.out.println("Forwarding address: " + forwardingAddress); // Create and start the WalletKit kit = WalletAppKit.launch(network, new File("."), getPrefix(network), MAX_CONNECTIONS); // Add a listener that forwards received coins kit.wallet().addCoinsReceivedEventListener(this::coinForwardingListener); // After we start listening, we can tell the user the receiving address System.out.printf("Waiting to receive coins on: %s\n", kit.wallet().currentReceiveAddress()); System.out.println("Press Ctrl-C to quit."); } /** * Close the service. * <p> * Note that {@link WalletAppKit#setAutoStop(boolean)} is set by default and installs a shutdown handler * via {@link Runtime#addShutdownHook(Thread)} so we do not need to worry about explicitly shutting down * the {@code WalletAppKit} if the process is terminated. */ @Override public void close() { if (kit != null) { if (kit.isRunning()) { kit.wallet().removeCoinsReceivedEventListener(this::coinForwardingListener); } kit.close(); } } /** * A listener to receive coins and forward them to the configured address. * Implements the {@link WalletCoinsReceivedEventListener} functional interface. * @param wallet The active wallet * @param incomingTx the received transaction * @param prevBalance wallet balance before this transaction (unused) * @param newBalance wallet balance after this transaction (unused) */ private void coinForwardingListener(Wallet wallet, Transaction incomingTx, Coin prevBalance, Coin newBalance) { // Incoming transaction received, now "compose" (i.e. chain) a call to wait for required confirmations // The transaction "incomingTx" can either be pending, or included into a block (we didn't see the broadcast). Coin value = incomingTx.getValueSentToMe(wallet); System.out.printf("Received tx for %s : %s\n", value.toFriendlyString(), incomingTx); System.out.println("Transaction will be forwarded after it confirms."); System.out.println("Waiting for confirmation..."); wallet.waitForConfirmations(incomingTx, REQUIRED_CONFIRMATIONS) .thenCompose(confidence -> { // Required confirmations received, now compose a call to broadcast the forwarding transaction System.out.printf("Incoming tx has received %d confirmations.\n", confidence.getDepthInBlocks()); // Now send the coins onwards by sending exactly the outputs that have been sent to us SendRequest sendRequest = SendRequest.emptyWallet(forwardingAddress); sendRequest.coinSelector = forwardingCoinSelector(incomingTx.getTxId()); System.out.printf("Creating outgoing transaction for %s...\n", forwardingAddress); return wallet.sendTransaction(sendRequest); }) .thenCompose(broadcast -> { System.out.printf("Transaction %s is signed and is being delivered to %s...\n", broadcast.transaction().getTxId(), network); return broadcast.awaitRelayed(); // Wait until peers report they have seen the transaction }) .thenAccept(broadcast -> System.out.printf("Sent %s onwards and acknowledged by peers, via transaction %s\n", broadcast.transaction().getOutputSum().toFriendlyString(), broadcast.transaction().getTxId()) ); } static String getPrefix(BitcoinNetwork network) { return String.format("forwarding-service-%s", network.toString()); } /** * Create a CoinSelector that only returns outputs from a given parent transaction. * <p> * This is using the idea of partial function application to create a 2-argument function for coin selection * with a third, fixed argument of the transaction id. * @param parentTxId The parent transaction hash * @return a coin selector */ static CoinSelector forwardingCoinSelector(Sha256Hash parentTxId) { return (target, candidates) -> candidates.stream() .filter(output -> output.getParentTransactionHash().equals(parentTxId)) .collect(collectingAndThen(toList(), CoinSelection::new)); } }
8,274
43.972826
140
java
bitcoinj
bitcoinj-master/examples/src/main/java/org/bitcoinj/examples/RefreshWallet.java
/* * 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. */ package org.bitcoinj.examples; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Coin; import org.bitcoinj.base.Network; import org.bitcoinj.core.*; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.MemoryBlockStore; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.listeners.WalletCoinsReceivedEventListener; import java.io.File; /** * RefreshWallet loads a wallet, then processes the block chain to update the transaction pools within it. * To get a test wallet you can use wallet-tool from the tools subproject. */ public class RefreshWallet { public static void main(String[] args) throws Exception { File file = new File(args[0]); Wallet wallet = Wallet.loadFromFile(file); System.out.println(wallet.toString()); // Set up the components and link them together. final Network network = BitcoinNetwork.TESTNET; final NetworkParameters params = NetworkParameters.of(network); BlockStore blockStore = new MemoryBlockStore(params.getGenesisBlock()); BlockChain chain = new BlockChain(params, wallet, blockStore); final PeerGroup peerGroup = new PeerGroup(network, chain); peerGroup.startAsync(); wallet.addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() { @Override public synchronized void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) { System.out.println("\nReceived tx " + tx.getTxId()); System.out.println(tx.toString()); } }); // Now download and process the block chain. peerGroup.downloadBlockChain(); peerGroup.stopAsync(); wallet.saveToFile(file); System.out.println("\nDone!\n"); System.out.println(wallet.toString()); } }
2,489
36.727273
115
java
bitcoinj
bitcoinj-master/examples/src/main/java/org/bitcoinj/examples/DumpWallet.java
/* * Copyright 2011 Google Inc. * * 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. */ package org.bitcoinj.examples; import java.io.File; import org.bitcoinj.wallet.Wallet; /** * DumpWallet loads a serialized wallet and prints information about what it contains. */ public class DumpWallet { public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: java DumpWallet <filename>"); return; } Wallet wallet = Wallet.loadFromFile(new File(args[0])); System.out.println(wallet.toString()); } }
1,119
29.27027
86
java
bitcoinj
bitcoinj-master/examples/src/main/java/org/bitcoinj/examples/BackupToMnemonicSeed.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.examples; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.internal.InternalUtils; import org.bitcoinj.wallet.DeterministicSeed; import org.bitcoinj.wallet.Wallet; /** * The following example shows you how to create a deterministic seed from a hierarchical deterministic wallet represented as a mnemonic code. * This seed can be used to fully restore your wallet. The RestoreFromSeed.java example shows how to load the wallet from this seed. * * In Bitcoin Improvement Proposal (BIP) 39 and BIP 32 describe the details about hierarchical deterministic wallets and mnemonic sentences * https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki * https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki */ public class BackupToMnemonicSeed { public static void main(String[] args) { Wallet wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH); DeterministicSeed seed = wallet.getKeyChainSeed(); System.out.println("seed: " + seed.toString()); System.out.println("creation time: " + seed.creationTime().get().getEpochSecond()); System.out.println("mnemonicCode: " + InternalUtils.SPACE_JOINER.join(seed.getMnemonicCode())); } }
1,913
40.608696
142
java
bitcoinj
bitcoinj-master/examples/src/main/java/org/bitcoinj/examples/PrintPeers.java
/* * Copyright 2011 John Sample. * * 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. */ package org.bitcoinj.examples; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Network; import org.bitcoinj.core.listeners.PeerConnectedEventListener; import org.bitcoinj.core.listeners.PeerDisconnectedEventListener; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Peer; import org.bitcoinj.core.PeerAddress; import org.bitcoinj.core.VersionMessage; import org.bitcoinj.net.discovery.DnsDiscovery; import org.bitcoinj.net.discovery.PeerDiscoveryException; import org.bitcoinj.net.NioClientManager; import org.bitcoinj.utils.BriefLogFormatter; import com.google.common.util.concurrent.Futures; import java.net.InetAddress; import java.net.InetSocketAddress; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; /** * Prints a list of IP addresses obtained from DNS. */ public class PrintPeers { private static List<InetSocketAddress> dnsPeers; private static void printElapsed(long start) { long now = System.currentTimeMillis(); System.out.println(String.format("Took %.2f seconds", (now - start) / 1000.0)); } private static void printPeers(List<InetSocketAddress> addresses) { for (InetSocketAddress address : addresses) { String hostAddress = address.getAddress().getHostAddress(); System.out.println(String.format("%s:%d", hostAddress, address.getPort())); } } private static void printDNS(Network network) throws PeerDiscoveryException { long start = System.currentTimeMillis(); DnsDiscovery dns = new DnsDiscovery(NetworkParameters.of(network)); dnsPeers = dns.getPeers(0, Duration.ofSeconds(10)); printPeers(dnsPeers); printElapsed(start); } public static void main(String[] args) throws Exception { BriefLogFormatter.init(); final Network network = BitcoinNetwork.MAINNET; final NetworkParameters params = NetworkParameters.of(network); System.out.println("=== DNS ==="); printDNS(network); System.out.println("=== Version/chain heights ==="); ArrayList<InetAddress> addrs = new ArrayList<>(); for (InetSocketAddress peer : dnsPeers) addrs.add(peer.getAddress()); System.out.println("Scanning " + addrs.size() + " peers:"); final Object lock = new Object(); final long[] bestHeight = new long[1]; List<CompletableFuture<Void>> futures = new ArrayList<>(); NioClientManager clientManager = new NioClientManager(); for (final InetAddress addr : addrs) { InetSocketAddress address = new InetSocketAddress(addr, params.getPort()); final Peer peer = new Peer(params, new VersionMessage(params, 0), PeerAddress.simple(address), null); final CompletableFuture<Void> future = new CompletableFuture<>(); // Once the connection has completed version handshaking ... peer.addConnectedEventListener((p, peerCount) -> { // Check the chain height it claims to have. VersionMessage ver = peer.getPeerVersionMessage(); long nodeHeight = ver.bestHeight; synchronized (lock) { long diff = bestHeight[0] - nodeHeight; if (diff > 0) { System.out.println("Node is behind by " + diff + " blocks: " + addr); } else if (diff == 0) { System.out.println("Node " + addr + " has " + nodeHeight + " blocks"); bestHeight[0] = nodeHeight; } else if (diff < 0) { System.out.println("Node is ahead by " + Math.abs(diff) + " blocks: " + addr); bestHeight[0] = nodeHeight; } } // Now finish the future and close the connection future.complete(null); peer.close(); }); peer.addDisconnectedEventListener((p, peerCount) -> { if (!future.isDone()) System.out.println("Failed to talk to " + addr); future.complete(null); }); clientManager.openConnection(address, peer); futures.add(future); } // Wait for every tried connection to finish. CompletableFuture.allOf(futures.toArray( new CompletableFuture[0])).join(); } }
5,114
41.272727
102
java
bitcoinj
bitcoinj-master/examples/src/main/java/org/bitcoinj/examples/SendRequest.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.examples; import org.bitcoinj.base.Address; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Coin; import org.bitcoinj.core.*; import org.bitcoinj.kits.WalletAppKit; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.Wallet.BalanceType; import java.io.File; import java.util.concurrent.CompletableFuture; /** * The following example shows you how to create a SendRequest to send coins from a wallet to a given address. */ public class SendRequest { public static void main(String[] args) throws Exception { // We use the WalletAppKit that handles all the boilerplate for us. Have a look at the Kit.java example for more details. WalletAppKit kit = WalletAppKit.launch(BitcoinNetwork.TESTNET, new File("."), "sendrequest-example"); // How much coins do we want to send? // The Coin class represents a monetary Bitcoin value. // We use the parseCoin function to simply get a Coin instance from a simple String. Coin value = Coin.parseCoin("0.09"); // To which address you want to send the coins? // The Address class represents a Bitcoin address. Address to = kit.wallet().parseAddress("bcrt1qspfueag7fvty7m8htuzare3xs898zvh30fttu2"); System.out.println("Send money to: " + to.toString()); // There are different ways to create and publish a SendRequest. This is probably the easiest one. // Have a look at the code of the SendRequest class to see what's happening and what other options you have: https://bitcoinj.github.io/javadoc/0.11/com/google/bitcoin/core/Wallet.SendRequest.html // // Please note that this might raise a InsufficientMoneyException if your wallet has not enough coins to spend. // When using the testnet you can use a faucet to get testnet coins. // In this example we catch the InsufficientMoneyException and register a BalanceFuture callback that runs once the wallet has enough balance. try { Wallet.SendResult result = kit.wallet().sendCoins(kit.peerGroup(), to, value); System.out.println("coins sent. transaction hash: " + result.transaction().getTxId()); // you can use a block explorer like https://www.biteasy.com/ to inspect the transaction with the printed transaction hash. } catch (InsufficientMoneyException e) { System.out.println("Not enough coins in your wallet. Missing " + e.missing.getValue() + " satoshis are missing (including fees)"); System.out.println("Send money to: " + kit.wallet().currentReceiveAddress().toString()); // Bitcoinj allows you to define a BalanceFuture to execute a callback once your wallet has a certain balance. // Here we wait until we have enough balance and display a notice. CompletableFuture<Coin> balanceFuture = kit.wallet().getBalanceFuture(value, BalanceType.AVAILABLE); balanceFuture.whenComplete((balance, throwable) -> { if (balance != null) { System.out.println("coins arrived and the wallet now has enough balance"); } else { System.out.println("something went wrong"); } }); } // shutting down //kit.stopAsync(); //kit.awaitTerminated(); } }
3,994
48.320988
204
java
bitcoinj
bitcoinj-master/examples/src/main/java/org/bitcoinj/examples/GenerateLowSTests.java
/* * Copyright 2015 Ross Nicoll. * Copyright 2019 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. */ package org.bitcoinj.examples; import java.io.IOException; import java.math.BigInteger; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.EnumSet; import java.util.Objects; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Network; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.base.Coin; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.crypto.SignatureDecodeException; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.VerificationException; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptBuilder; import org.bitcoinj.script.ScriptChunk; import org.bitcoinj.script.ScriptException; import static org.bitcoinj.script.ScriptOpCodes.getOpCodeName; import org.bitcoinj.signers.LocalTransactionSigner; import org.bitcoinj.signers.TransactionSigner.ProposedTransaction; import org.bitcoinj.wallet.KeyBag; import org.bitcoinj.wallet.RedeemData; /** * Test case generator for transactions with low-S and high-S signatures, to * test the LOW_S script validation flag. * * @author Ross Nicoll */ public class GenerateLowSTests { public static final BigInteger HIGH_S_DIFFERENCE = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16); public static void main(final String[] argv) throws NoSuchAlgorithmException, IOException, VerificationException, SignatureDecodeException { final Network network = BitcoinNetwork.MAINNET; final LocalTransactionSigner signer = new LocalTransactionSigner(); final SecureRandom secureRandom = SecureRandom.getInstanceStrong(); final ECKey key = new ECKey(secureRandom); final KeyBag bag = new KeyBag() { @Override public ECKey findKeyFromPubKeyHash(byte[] pubkeyHash, ScriptType scriptType) { return key; } @Override public ECKey findKeyFromPubKey(byte[] pubKey) { return key; } @Override public RedeemData findRedeemDataFromScriptHash(byte[] scriptHash) { return null; } }; // Generate a fictional output transaction we take values from, and // an input transaction for the test case final Transaction outputTransaction = new Transaction(); final Transaction inputTransaction = new Transaction(); final TransactionOutput output = new TransactionOutput(inputTransaction, Coin.ZERO, key.toAddress(ScriptType.P2PKH, network)); inputTransaction.addOutput(output); outputTransaction.addInput(output); outputTransaction.addOutput(Coin.ZERO, new ECKey(secureRandom).toAddress(ScriptType.P2PKH, network)); addOutputs(outputTransaction, bag); // Sign the transaction final ProposedTransaction proposedTransaction = new ProposedTransaction(outputTransaction); signer.signInputs(proposedTransaction, bag); final TransactionInput input = proposedTransaction.partialTx.getInput(0); input.verify(output); input.getScriptSig().correctlySpends(outputTransaction, 0, null, null, output.getScriptPubKey(), EnumSet.of(Script.VerifyFlag.DERSIG, Script.VerifyFlag.P2SH)); final Script scriptSig = input.getScriptSig(); final TransactionSignature signature = TransactionSignature.decodeFromBitcoin(scriptSig.chunks().get(0).data, true, false); // First output a conventional low-S transaction with the LOW_S flag, for the tx_valid.json set System.out.println("[\"A transaction with a low-S signature.\"],"); System.out.println("[[[\"" + inputTransaction.getTxId() + "\", " + output.getIndex() + ", \"" + scriptToString(output.getScriptPubKey()) + "\"]],\n" + "\"" + ByteUtils.formatHex(proposedTransaction.partialTx.serialize()) + "\", \"" + Script.VerifyFlag.P2SH.name() + "," + Script.VerifyFlag.LOW_S.name() + "\"],"); final BigInteger highS = HIGH_S_DIFFERENCE.subtract(signature.s); final TransactionSignature highSig = new TransactionSignature(signature.r, highS); input.setScriptSig(new ScriptBuilder().data(highSig.encodeToBitcoin()).data(scriptSig.chunks().get(1).data).build()); input.getScriptSig().correctlySpends(outputTransaction, 0, null, null, output.getScriptPubKey(), EnumSet.of(Script.VerifyFlag.P2SH)); // A high-S transaction without the LOW_S flag, for the tx_valid.json set System.out.println("[\"A transaction with a high-S signature.\"],"); System.out.println("[[[\"" + inputTransaction.getTxId() + "\", " + output.getIndex() + ", \"" + scriptToString(output.getScriptPubKey()) + "\"]],\n" + "\"" + ByteUtils.formatHex(proposedTransaction.partialTx.serialize()) + "\", \"" + Script.VerifyFlag.P2SH.name() + "\"],"); // Lastly a conventional high-S transaction with the LOW_S flag, for the tx_invalid.json set System.out.println("[\"A transaction with a high-S signature.\"],"); System.out.println("[[[\"" + inputTransaction.getTxId() + "\", " + output.getIndex() + ", \"" + scriptToString(output.getScriptPubKey()) + "\"]],\n" + "\"" + ByteUtils.formatHex(proposedTransaction.partialTx.serialize()) + "\", \"" + Script.VerifyFlag.P2SH.name() + "," + Script.VerifyFlag.LOW_S.name() + "\"],"); } private static void addOutputs(final Transaction outputTransaction, final KeyBag bag) throws ScriptException { int numInputs = outputTransaction.getInputs().size(); for (int i = 0; i < numInputs; i++) { TransactionInput txIn = outputTransaction.getInput(i); Script scriptPubKey = txIn.getConnectedOutput().getScriptPubKey(); RedeemData redeemData = txIn.getConnectedRedeemData(bag); Objects.requireNonNull(redeemData, () -> "Transaction exists in wallet that we cannot redeem: " + txIn.getOutpoint().hash()); txIn.setScriptSig(scriptPubKey.createEmptyInputScript(redeemData.keys.get(0), redeemData.redeemScript)); } } /** * Convert a script to a string format that suits the style expected in * tx_valid.json and tx_invalid.json. */ private static String scriptToString(Script scriptPubKey) { final StringBuilder buf = new StringBuilder(); for (ScriptChunk chunk: scriptPubKey.chunks()) { if (buf.length() > 0) { buf.append(" "); } if (chunk.isOpCode()) { buf.append(getOpCodeName(chunk.opcode)); } else if (chunk.data != null) { // Data chunk buf.append("0x") .append(Integer.toString(chunk.opcode, 16)).append(" 0x") .append(ByteUtils.formatHex(chunk.data)); } else { buf.append(chunk.toString()); } } return buf.toString(); } }
7,979
43.831461
142
java
bitcoinj
bitcoinj-master/examples/src/main/java/org/bitcoinj/examples/DoubleSpend.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.examples; import org.bitcoinj.base.Address; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.core.*; import org.bitcoinj.kits.WalletAppKit; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.Wallet; import java.io.File; import static org.bitcoinj.base.Coin.*; /** * This is a little test app that waits for a coin on a local regtest node, then generates two transactions that double * spend the same output and sends them. It's useful for testing double spend codepaths but is otherwise not something * you would normally want to do. */ public class DoubleSpend { public static void main(String[] args) throws Exception { BriefLogFormatter.init(); WalletAppKit kit = WalletAppKit.launch(BitcoinNetwork.REGTEST, new File("."), "doublespend", (k) -> k.setAutoSave(false) ); System.out.println(kit.wallet()); kit.wallet().getBalanceFuture(COIN, Wallet.BalanceType.AVAILABLE).get(); Address destinationAddress = kit.wallet().parseAddress("bcrt1qsmf9envp5dphlu6my2tpwfmce0793jvpvlg5ez"); Transaction tx1 = kit.wallet().createSend(destinationAddress, CENT); Transaction tx2 = kit.wallet().createSend(destinationAddress, CENT.add(SATOSHI.multiply(10))); final Peer peer = kit.peerGroup().getConnectedPeers().get(0); peer.addPreMessageReceivedEventListener(Threading.SAME_THREAD, (peer1, m) -> { System.err.println("Got a message!" + m.getClass().getSimpleName() + ": " + m); return m; } ); peer.sendMessage(tx1); peer.sendMessage(tx2); Thread.sleep(5000); kit.stopAsync(); kit.awaitTerminated(); } }
2,430
36.984375
120
java
bitcoinj
bitcoinj-master/examples/src/main/java/org/bitcoinj/examples/Kit.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.examples; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.core.*; import org.bitcoinj.kits.WalletAppKit; import java.io.File; /** * The following example shows how to use the by bitcoinj provided WalletAppKit. * The WalletAppKit class wraps the boilerplate (Peers, BlockChain, BlockStorage, Wallet) needed to set up a new SPV bitcoinj app. * * In this example we also define a WalletEventListener class with implementors that are called when the wallet changes (for example sending/receiving money) */ public class Kit { public static void main(String[] args) { // First we configure the network we want to use. // The available options are: // - BitcoinNetwork.MAINNET // - BitcoinNetwork.TESTTEST // - BitcoinNetwork.SIGNET // - BitcoinNetwork.REGTEST // While developing your application you probably want to use the Regtest mode and run your local bitcoin network. Run bitcoind with the -regtest flag // To test you app with a real network you can use the testnet. The testnet is an alternative bitcoin network that follows the same rules as main network. // Coins are worth nothing and you can get coins from a faucet. // // For more information have a look at: https://bitcoinj.github.io/testing and https://bitcoin.org/en/developer-examples#testing-applications BitcoinNetwork network = BitcoinNetwork.TESTNET; // Initialize and start a WalletAppKit. The kit handles all the boilerplate for us and is the easiest way to get everything up and running. // Look at the WalletAppKit documentation and its source to understand what's happening behind the scenes: https://github.com/bitcoinj/bitcoinj/blob/master/core/src/main/java/org/bitcoinj/kits/WalletAppKit.java // WalletAppKit extends the Guava AbstractIdleService. Have a look at the introduction to Guava services: https://github.com/google/guava/wiki/ServiceExplained WalletAppKit kit = WalletAppKit.launch(network, new File("."), "walletappkit-example", (k) -> { // In case you want to connect with your local bitcoind tell the kit to connect to localhost. // This is done automatically in reg test mode. // k.connectToLocalHost(); }); kit.wallet().addCoinsReceivedEventListener((wallet, tx, prevBalance, newBalance) -> { System.out.println("-----> coins resceived: " + tx.getTxId()); System.out.println("received: " + tx.getValue(wallet)); }); kit.wallet().addCoinsSentEventListener((wallet, tx, prevBalance, newBalance) -> System.out.println("coins sent")); kit.wallet().addKeyChainEventListener(keys -> System.out.println("new key added")); kit.wallet().addScriptsChangeEventListener((wallet, scripts, isAddingScripts) -> System.out.println("new script added")); kit.wallet().addTransactionConfidenceEventListener((wallet, tx) -> { System.out.println("-----> confidence changed: " + tx.getTxId()); TransactionConfidence confidence = tx.getConfidence(); System.out.println("new block depth: " + confidence.getDepthInBlocks()); }); // Ready to run. The kit syncs the blockchain and our wallet event listener gets notified when something happens. // To test everything we create and print a fresh receiving address. Send some coins to that address and see if everything works. System.out.println("send money to: " + kit.wallet().freshReceiveAddress().toString()); // Make sure to properly shut down all the running services when you manually want to stop the kit. The WalletAppKit registers a runtime ShutdownHook so we actually do not need to worry about that when our application is stopping. //System.out.println("shutting down again"); //kit.stopAsync(); //kit.awaitTerminated(); } }
4,571
52.788235
238
java
bitcoinj
bitcoinj-master/examples/src/main/java/org/bitcoinj/examples/FetchBlock.java
/* * 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. */ package org.bitcoinj.examples; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Network; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.*; import org.bitcoinj.net.discovery.DnsDiscovery; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.MemoryBlockStore; import org.bitcoinj.utils.BriefLogFormatter; import picocli.CommandLine; import java.net.InetAddress; import java.util.concurrent.Callable; import java.util.concurrent.Future; /** * <p>Downloads the block given a block hash from the remote or localhost node and prints it out.</p> * <p>When downloading from localhost, run bitcoind locally: bitcoind -testnet -daemon. * After bitcoind is up and running, use command: org.bitcoinj.examples.FetchBlock --localhost &lt;blockHash&gt; </p> * <p>Otherwise, use command: org.bitcoinj.examples.FetchBlock &lt;blockHash&gt;, this command will download blocks from a peer generated by DNS seeds.</p> */ @CommandLine.Command(usageHelpAutoWidth = true, sortOptions = false) public class FetchBlock implements Callable<Integer> { @CommandLine.Parameters(index = "0", description = "The hash of the block to download.") private String blockHashParam; @CommandLine.Option(names = "--localhost", description = "Connect to the localhost node. Default: ${DEFAULT-VALUE}") private boolean localhost = true; @CommandLine.Option(names = "--help", usageHelp = true, description = "Displays program options.") private boolean help; public static void main(String[] args) throws Exception { BriefLogFormatter.init(); int exitCode = new CommandLine(new FetchBlock()).execute(args); System.exit(exitCode); } @Override public Integer call() throws Exception { // Connect to testnet and find a peer System.out.println("Connecting to node"); final Network network = BitcoinNetwork.TESTNET; final NetworkParameters params = NetworkParameters.of(network); BlockStore blockStore = new MemoryBlockStore(params.getGenesisBlock()); BlockChain chain = new BlockChain(params, blockStore); PeerGroup peerGroup = new PeerGroup(network, chain); if (localhost) { peerGroup.addPeerDiscovery(new DnsDiscovery(params)); } else { PeerAddress addr = PeerAddress.localhost(params); peerGroup.addAddress(addr); } peerGroup.start(); peerGroup.waitForPeers(1).get(); Peer peer = peerGroup.getConnectedPeers().get(0); // Retrieve a block through a peer Sha256Hash blockHash = Sha256Hash.wrap(blockHashParam); Future<Block> future = peer.getBlock(blockHash); System.out.println("Waiting for node to send us the requested block: " + blockHash); Block block = future.get(); System.out.println(block); peerGroup.stopAsync(); return 0; } }
3,551
40.788235
155
java
bitcoinj
bitcoinj-master/examples/src/main/java/org/bitcoinj/examples/PeerMonitor.java
/* * Copyright 2012 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. */ package org.bitcoinj.examples; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Network; import org.bitcoinj.core.AddressMessage; import org.bitcoinj.base.Coin; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Peer; import org.bitcoinj.core.PeerAddress; import org.bitcoinj.core.PeerGroup; import org.bitcoinj.net.discovery.DnsDiscovery; import org.bitcoinj.utils.BriefLogFormatter; import javax.swing.*; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumnModel; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Shows connected peers in a table view, so you can watch as they come and go. */ public class PeerMonitor { private PeerGroup peerGroup; private final Executor reverseDnsThreadPool = Executors.newCachedThreadPool(); private PeerTableModel peerTableModel; private PeerTableRenderer peerTableRenderer; private final ConcurrentHashMap<Peer, String> reverseDnsLookups = new ConcurrentHashMap<>(); private final ConcurrentHashMap<Peer, AddressMessage> addressMessages = new ConcurrentHashMap<>(); public static void main(String[] args) throws Exception { BriefLogFormatter.init(); new PeerMonitor(); } public PeerMonitor() { setupNetwork(); setupGUI(); peerGroup.startAsync(); } private void setupNetwork() { Network network = BitcoinNetwork.MAINNET; peerGroup = new PeerGroup(network, null /* no chain */); peerGroup.setUserAgent("PeerMonitor", "1.0"); peerGroup.setMaxConnections(4); peerGroup.addPeerDiscovery(new DnsDiscovery(NetworkParameters.of(network))); peerGroup.addConnectedEventListener((peer, peerCount) -> { refreshUI(); lookupReverseDNS(peer); getAddr(peer); }); peerGroup.addDisconnectedEventListener((peer, peerCount) -> { refreshUI(); reverseDnsLookups.remove(peer); addressMessages.remove(peer); }); } private void lookupReverseDNS(final Peer peer) { getHostName(peer.getAddress()).thenAccept(reverseDns -> { reverseDnsLookups.put(peer, reverseDns); refreshUI(); }); } private void getAddr(final Peer peer) { peer.getAddr() .orTimeout(15, TimeUnit.SECONDS) .whenComplete((addressMessage, e) -> { if (addressMessage != null) { addressMessages.put(peer, addressMessage); refreshUI(); } else { e.printStackTrace(); } }); } private CompletableFuture<String> getHostName(final PeerAddress peerAddress) { if (peerAddress.getAddr() != null) { // This can take a looooong time. return CompletableFuture.supplyAsync(peerAddress.getAddr()::getCanonicalHostName, reverseDnsThreadPool); } else if (peerAddress.getHostname() != null ){ return CompletableFuture.completedFuture(peerAddress.getHostname()); } else { return CompletableFuture.completedFuture("-unavailable-"); } } private void refreshUI() { // Tell the Swing UI thread to redraw the peers table. SwingUtilities.invokeLater(() -> peerTableModel.updateFromPeerGroup()); } private void setupGUI() { JFrame window = new JFrame("Network monitor"); window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); window.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent windowEvent) { System.out.println("Shutting down ..."); peerGroup.stop(); System.out.println("Shutdown complete."); System.exit(0); } }); JPanel panel = new JPanel(); JLabel instructions = new JLabel("Number of peers to connect to: "); final SpinnerNumberModel spinnerModel = new SpinnerNumberModel(4, 0, 100, 1); spinnerModel.addChangeListener(changeEvent -> peerGroup.setMaxConnections(spinnerModel.getNumber().intValue())); JSpinner numPeersSpinner = new JSpinner(spinnerModel); panel.add(instructions); panel.add(numPeersSpinner); window.getContentPane().add(panel, BorderLayout.NORTH); peerTableModel = new PeerTableModel(); JTable peerTable = new JTable(peerTableModel); peerTable.setAutoCreateRowSorter(true); peerTableRenderer = new PeerTableRenderer(peerTableModel); peerTable.setDefaultRenderer(String.class, peerTableRenderer); peerTable.setDefaultRenderer(Integer.class, peerTableRenderer); peerTable.setDefaultRenderer(Long.class, peerTableRenderer); TableColumnModel columnModel = peerTable.getColumnModel(); columnModel.getColumn(PeerTableModel.IP_ADDRESS).setPreferredWidth(300); columnModel.getColumn(PeerTableModel.USER_AGENT).setPreferredWidth(150); columnModel.getColumn(PeerTableModel.FEE_FILTER).setPreferredWidth(150); columnModel.getColumn(PeerTableModel.ADDRESSES).setPreferredWidth(400); JScrollPane scrollPane = new JScrollPane(peerTable); window.getContentPane().add(scrollPane, BorderLayout.CENTER); window.pack(); window.setSize(1280, 768); window.setVisible(true); // Refresh the UI every half second to get the latest ping times. The event handler runs in the UI thread. new Timer(1000, actionEvent -> peerTableModel.updateFromPeerGroup()).start(); } private class PeerTableModel extends AbstractTableModel { public static final int IP_ADDRESS = 0; public static final int PROTOCOL_VERSION = 1; public static final int USER_AGENT = 2; public static final int CHAIN_HEIGHT = 3; public static final int FEE_FILTER = 4; public static final int PING_TIME = 5; public static final int LAST_PING_TIME = 6; public static final int ADDRESSES = 7; public List<Peer> connectedPeers = new ArrayList<>(); public List<Peer> pendingPeers = new ArrayList<>(); public void updateFromPeerGroup() { connectedPeers = peerGroup.getConnectedPeers(); pendingPeers = peerGroup.getPendingPeers(); fireTableDataChanged(); } @Override public int getRowCount() { return connectedPeers.size() + pendingPeers.size(); } @Override public String getColumnName(int i) { switch (i) { case IP_ADDRESS: return "Address"; case PROTOCOL_VERSION: return "Protocol version"; case USER_AGENT: return "User Agent"; case CHAIN_HEIGHT: return "Chain height"; case FEE_FILTER: return "Fee filter (per kB)"; case PING_TIME: return "Average ping"; case LAST_PING_TIME: return "Last ping"; case ADDRESSES: return "Peer addresses"; default: throw new RuntimeException(); } } @Override public int getColumnCount() { return 8; } @Override public Class<?> getColumnClass(int column) { switch (column) { case PROTOCOL_VERSION: return Integer.class; case CHAIN_HEIGHT: case PING_TIME: case LAST_PING_TIME: return Long.class; default: return String.class; } } @Override public Object getValueAt(int row, int col) { if (row >= connectedPeers.size()) { // Peer that isn't connected yet. Peer peer = pendingPeers.get(row - connectedPeers.size()); switch (col) { case IP_ADDRESS: return getAddressForPeer(peer); case PROTOCOL_VERSION: return 0; case CHAIN_HEIGHT: case PING_TIME: case LAST_PING_TIME: return 0L; default: return "(pending)"; } } Peer peer = connectedPeers.get(row); switch (col) { case IP_ADDRESS: return getAddressForPeer(peer); case PROTOCOL_VERSION: return Integer.toString(peer.getPeerVersionMessage().clientVersion); case USER_AGENT: return peer.getPeerVersionMessage().subVer; case CHAIN_HEIGHT: return peer.getBestHeight(); case FEE_FILTER: Coin feeFilter = peer.getFeeFilter(); return feeFilter != null ? feeFilter.toFriendlyString() : ""; case PING_TIME: return peer.pingInterval().map(Duration::toMillis).orElse(0L); case LAST_PING_TIME: return peer.lastPingInterval().map(Duration::toMillis).orElse(0L); case ADDRESSES: return getAddressesForPeer(peer); default: throw new RuntimeException(); } } private String getAddressForPeer(Peer peer) { String s = reverseDnsLookups.get(peer); return (s != null) ? s : peer.getAddress().getAddr().getHostAddress(); } private String getAddressesForPeer(Peer peer) { AddressMessage addressMessage = addressMessages.get(peer); return addressMessage != null ? addressMessage.toString() : ""; } } private class PeerTableRenderer extends JLabel implements TableCellRenderer { private final PeerTableModel model; private final Font normal, bold; public PeerTableRenderer(PeerTableModel model) { super(); this.model = model; this.normal = new Font("Sans Serif", Font.PLAIN, 12); this.bold = new Font("Sans Serif", Font.BOLD, 12); } @Override public Component getTableCellRendererComponent(JTable table, Object contents, boolean selected, boolean hasFocus, int row, int column) { row = table.convertRowIndexToModel(row); column = table.convertColumnIndexToModel(column); String str = contents.toString(); if (model.connectedPeers == null || model.pendingPeers == null) { setText(str); return this; } if (row >= model.connectedPeers.size()) { setFont(normal); setForeground(Color.LIGHT_GRAY); } else { if (model.connectedPeers.get(row) == peerGroup.getDownloadPeer()) setFont(bold); else setFont(normal); setForeground(Color.BLACK); // Mark chain heights that aren't normal but not for pending peers, as we don't know their heights yet. if (column == PeerTableModel.CHAIN_HEIGHT) { long height = (Long) contents; if (height != peerGroup.getMostCommonChainHeight()) { str = height + " \u2022 "; } } } boolean isPingColumn = column == PeerTableModel.PING_TIME || column == PeerTableModel.LAST_PING_TIME; if (isPingColumn && contents.equals(Long.MAX_VALUE)) { // We don't know the answer yet str = ""; } setText(str); return this; } } }
12,991
37.898204
120
java
bitcoinj
bitcoinj-master/examples/src/main/java/org/bitcoinj/examples/RestoreFromSeed.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.examples; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Network; import org.bitcoinj.base.ScriptType; import org.bitcoinj.core.listeners.DownloadProgressTracker; import org.bitcoinj.core.*; import org.bitcoinj.net.discovery.DnsDiscovery; import org.bitcoinj.store.SPVBlockStore; import org.bitcoinj.wallet.DeterministicSeed; import org.bitcoinj.wallet.KeyChainGroupStructure; import org.bitcoinj.wallet.Wallet; import java.io.File; import java.time.Instant; /** * The following example shows you how to restore a HD wallet from a previously generated deterministic seed. * In this example we manually setup the blockchain, peer group, etc. You can also use the WalletAppKit which provides a restoreWalletFromSeed function to load a wallet from a deterministic seed. */ public class RestoreFromSeed { public static void main(String[] args) throws Exception { Network network = BitcoinNetwork.TESTNET; NetworkParameters params = NetworkParameters.of(network); // Bitcoinj supports hierarchical deterministic wallets (or "HD Wallets"): https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki // HD wallets allow you to restore your wallet simply from a root seed. This seed can be represented using a short mnemonic sentence as described in BIP 39: https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki // Here we restore our wallet from a seed with no passphrase. Also have a look at the BackupToMnemonicSeed.java example that shows how to backup a wallet by creating a mnemonic sentence. String seedCode = "yard impulse luxury drive today throw farm pepper survey wreck glass federal"; String passphrase = ""; Instant creationtime = Instant.ofEpochSecond(1409478661L); DeterministicSeed seed = DeterministicSeed.ofMnemonic(seedCode, passphrase, creationtime); // The wallet class provides a easy fromSeed() function that loads a new wallet from a given seed. Wallet wallet = Wallet.fromSeed(network, seed, ScriptType.P2PKH); // Because we are importing an existing wallet which might already have transactions we must re-download the blockchain to make the wallet picks up these transactions // You can find some information about this in the guides: https://bitcoinj.github.io/working-with-the-wallet#setup // To do this we clear the transactions of the wallet and delete a possible existing blockchain file before we download the blockchain again further down. System.out.println(wallet.toString()); wallet.clearTransactions(0); File chainFile = new File("restore-from-seed.spvchain"); if (chainFile.exists()) { chainFile.delete(); } // Setting up the BlochChain, the BlocksStore and connecting to the network. SPVBlockStore chainStore = new SPVBlockStore(params, chainFile); BlockChain chain = new BlockChain(params, chainStore); PeerGroup peerGroup = new PeerGroup(network, chain); peerGroup.addPeerDiscovery(new DnsDiscovery(params)); // Now we need to hook the wallet up to the blockchain and the peers. This registers event listeners that notify our wallet about new transactions. chain.addWallet(wallet); peerGroup.addWallet(wallet); DownloadProgressTracker bListener = new DownloadProgressTracker() { @Override public void doneDownload() { System.out.println("blockchain downloaded"); } }; // Now we re-download the blockchain. This replays the chain into the wallet. Once this is completed our wallet should know of all its transactions and print the correct balance. peerGroup.start(); peerGroup.startBlockChainDownload(bListener); bListener.await(); // Print a debug message with the details about the wallet. The correct balance should now be displayed. System.out.println(wallet.toString()); // shutting down again peerGroup.stop(); } }
4,708
48.052083
227
java
bitcoinj
bitcoinj-master/examples/src/main/java/org/bitcoinj/examples/PrivateKeys.java
/* * 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. */ package org.bitcoinj.examples; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Network; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Address; import org.bitcoinj.base.Base58; import org.bitcoinj.core.BlockChain; import org.bitcoinj.crypto.DumpedPrivateKey; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.PeerAddress; import org.bitcoinj.core.PeerGroup; import org.bitcoinj.store.MemoryBlockStore; import org.bitcoinj.wallet.Wallet; import java.math.BigInteger; import java.net.InetAddress; /** * This example shows how to solve the challenge Hal posted here:<p> * * <a href="http://www.bitcoin.org/smf/index.php?topic=3638.0">http://www.bitcoin.org/smf/index.php?topic=3638 * .0</a><p> * * in which a private key with some coins associated with it is published. The goal is to import the private key, * claim the coins and then send them to a different address. */ public class PrivateKeys { public static void main(String[] args) throws Exception { // TODO: Assumes main network not testnet. Make it selectable. Network network = BitcoinNetwork.MAINNET; NetworkParameters params = NetworkParameters.of(network); try { // Decode the private key from Satoshis Base58 variant. If 51 characters long then it's from Bitcoins // dumpprivkey command and includes a version byte and checksum, or if 52 characters long then it has // compressed pub key. Otherwise assume it's a raw key. ECKey key; if (args[0].length() == 51 || args[0].length() == 52) { DumpedPrivateKey dumpedPrivateKey = DumpedPrivateKey.fromBase58(network, args[0]); key = dumpedPrivateKey.getKey(); } else { BigInteger privKey = Base58.decodeToBigInteger(args[0]); key = ECKey.fromPrivate(privKey); } System.out.println("Address from private key is: " + key.toAddress(ScriptType.P2WPKH, network).toString()); // Import the private key to a fresh wallet. Wallet wallet = Wallet.createDeterministic(network, ScriptType.P2PKH); wallet.importKey(key); // And the address ... Address destination = wallet.parseAddress(args[1]); // Find the transactions that involve those coins. final MemoryBlockStore blockStore = new MemoryBlockStore(params.getGenesisBlock()); BlockChain chain = new BlockChain(params, wallet, blockStore); final PeerGroup peerGroup = new PeerGroup(network, chain); peerGroup.addAddress(PeerAddress.localhost(params)); peerGroup.startAsync(); peerGroup.downloadBlockChain(); // And take them! System.out.println("Claiming " + wallet.getBalance().toFriendlyString()); wallet.sendCoins(peerGroup, destination, wallet.getBalance()); // Wait a few seconds to let the packets flush out to the network (ugly). Thread.sleep(5000); peerGroup.stopAsync(); System.exit(0); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("First arg should be private key in Base58 format. Second argument should be address " + "to send to."); } } }
4,032
41.452632
119
java
bitcoinj
bitcoinj-master/wallettool/src/test/java/org/bitcoinj/wallettool/WalletToolTest.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.wallettool; import org.checkerframework.framework.qual.IgnoreInWholeProgramInference; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import picocli.CommandLine; import java.io.File; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Basic functional/integration tests of {@code wallet-tool} */ public class WalletToolTest { @TempDir File tempDir; @Test void canConstruct() { WalletTool walletTool = new WalletTool(); assertNotNull(walletTool); } @Test void noArgsFails() { int exitCode = execute(); assertEquals(2, exitCode); } @Test void emptyStringArgFails() { int exitCode = execute(""); assertEquals(1, exitCode); } @Test void helpSucceeds() { int exitCode = execute("--help"); assertEquals(0, exitCode); } @Test void createNoFileSpecified() { int exitCode = execute("create"); // TODO: currently a stacktrace, give user-friendly error assertEquals(1, exitCode); } @Test void createMinimal(@TempDir File tempDir) { String walletFile = tempDir.getPath() + "/wallet"; int exitCode = execute("create", "--wallet", walletFile); assertEquals(0, exitCode); } @Test void createWithDate(@TempDir File tempDir) { String walletFile = tempDir.getPath() + "/wallet"; String date = "2023-05-01"; int exitCode = execute("create", "--wallet", walletFile, "--date", date); assertEquals(0, exitCode); } @Disabled("Requires a RegTest Bitcoin Core instance that is manually advanced by 1 block") @Test void waitForBlock(@TempDir File tempDir) { String walletFile = tempDir.getPath() + "/wallet"; String date = "2023-05-01"; int createExitCode = execute("create", "--net", "regtest", "--wallet", walletFile, "--date", date); assertEquals(0, createExitCode); // TODO: Add a JSON-RPC client that can tell the server to generate 1 block int syncExitCode = execute("sync", "--wallet", walletFile, "--net", "regtest", "--waitfor", "BLOCK"); assertEquals(0, syncExitCode); } /** * Run the wallet-tool via {@link CommandLine#execute(String...)} * @param args command-line arguments * @return exit code */ int execute(String... args) { return new CommandLine(new WalletTool()).execute(args); } }
3,223
27.785714
109
java
bitcoinj
bitcoinj-master/wallettool/src/main/java/org/bitcoinj/wallettool/WalletTool.java
/* * Copyright 2012 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. */ package org.bitcoinj.wallettool; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Network; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.crypto.AesKey; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.crypto.*; import org.bitcoinj.protocols.payments.PaymentProtocol; import org.bitcoinj.protocols.payments.PaymentProtocolException; import org.bitcoinj.protocols.payments.PaymentSession; import org.bitcoinj.base.ScriptType; import org.bitcoinj.script.ScriptException; import org.bitcoinj.store.*; import org.bitcoinj.uri.BitcoinURI; import org.bitcoinj.uri.BitcoinURIParseException; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.wallet.CoinSelection; import org.bitcoinj.wallet.CoinSelector; import org.bitcoinj.wallet.DeterministicKeyChain; import org.bitcoinj.wallet.DeterministicSeed; import com.google.common.io.Resources; import com.google.protobuf.ByteString; import org.bitcoinj.core.AbstractBlockChain; import org.bitcoinj.base.Address; import org.bitcoinj.base.exceptions.AddressFormatException; import org.bitcoinj.base.Base58; import org.bitcoinj.core.BlockChain; import org.bitcoinj.core.CheckpointManager; import org.bitcoinj.base.Coin; import org.bitcoinj.core.Context; import org.bitcoinj.crypto.DumpedPrivateKey; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.core.FullPrunedBlockChain; import org.bitcoinj.core.InsufficientMoneyException; import org.bitcoinj.base.LegacyAddress; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Peer; import org.bitcoinj.core.PeerAddress; import org.bitcoinj.core.PeerGroup; import org.bitcoinj.core.StoredBlock; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionBroadcast; import org.bitcoinj.core.VerificationException; import org.bitcoinj.core.listeners.DownloadProgressTracker; import org.bitcoinj.wallet.KeyChainGroupStructure; import org.bitcoinj.wallet.Protos; import org.bitcoinj.wallet.SendRequest; import org.bitcoinj.wallet.UnreadableWalletException; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.WalletProtobufSerializer; import org.bitcoinj.wallet.Wallet.BalanceType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import picocli.CommandLine; import javax.annotation.Nullable; import java.io.*; import java.math.BigInteger; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.text.ParseException; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.bitcoinj.base.Coin.parseCoin; /** * A command line tool for manipulating wallets and working with Bitcoin. */ @CommandLine.Command(name = "wallet-tool", usageHelpAutoWidth = true, sortOptions = false, description = "Print and manipulate wallets.") public class WalletTool implements Callable<Integer> { @CommandLine.Parameters(index = "0", description = "Action to perform. Valid values:%n" + " dump Loads and prints the given wallet in textual form to stdout. Private keys and seed are only printed if --dump-privkeys is specified. If the wallet is encrypted, also specify the --password option to dump the private keys and seed.%n" + " If --dump-lookahead is present, also show pregenerated but not yet issued keys.%n" + " raw-dump Prints the wallet as a raw protobuf with no parsing or sanity checking applied.%n" + " create Makes a new wallet in the file specified by --wallet. Will complain and require --force if the wallet already exists.%n" + " If --seed is present, it should specify either a mnemonic code or hex/base58 raw seed bytes.%n" + " If --watchkey is present, it creates a watching wallet using the specified base58 xpub.%n" + " If --seed or --watchkey is combined with either --date or --unixtime, use that as a birthdate for the wallet. See the set-creation-time action for the meaning of these flags.%n" + " If --output-script-type is present, use that for deriving addresses.%n" + " add-key Adds a new key to the wallet.%n" + " If --date is specified, that's the creation date.%n" + " If --unixtime is specified, that's the creation time and it overrides --date.%n" + " If --privkey is specified, use as a WIF-, hex- or base58-encoded private key.%n" + " Don't specify --pubkey in that case, it will be derived automatically.%n" + " If --pubkey is specified, use as a hex/base58 encoded non-compressed public key.%n" + " add-addr Requires --addr to be specified, and adds it as a watching address.%n" + " delete-key Removes the key specified by --pubkey or --addr from the wallet.%n" + " current-receive-addr Prints the current receive address, deriving one if needed. Addresses derived with this action are%n" + " independent of addresses derived with the add-key action.%n" + " sync Sync the wallet with the latest block chain (download new transactions).%n" + " If the chain file does not exist or if --force is present, this will RESET the wallet.%n" + " reset Deletes all transactions from the wallet, for if you want to replay the chain.%n" + " send Creates and broadcasts a transaction from the given wallet.%n" + " Requires either --output or --payment-request to be specified.%n" + " If --output is specified, a transaction is created from the provided output from this wallet and broadcasted, e.g.:%n" + " --output=1GthXFQMktFLWdh5EPNGqbq3H6WdG8zsWj:1.245%n" + " You can repeat --output=address:value multiple times.%n" + " There is a magic value ALL which empties the wallet to that address, e.g.:%n" + " --output=1GthXFQMktFLWdh5EPNGqbq3H6WdG8zsWj:ALL%n" + " The output destination can also be a native segwit address.%n" + " If the output destination starts with 04 and is 65 or 33 bytes long it will be treated as a public key instead of an address and the send will use%n" + " <key> CHECKSIG as the script.%n" + " If --payment-request is specified, a transaction will be created using the provided payment request. A payment request can be a local file, a bitcoin uri, or url to download the payment request, e.g.:%n" + " --payment-request=/path/to/my.bitcoinpaymentrequest%n" + " --payment-request=bitcoin:?r=http://merchant.com/pay.php?123%n" + " --payment-request=http://merchant.com/pay.php?123%n" + " Other options include:%n" + " --fee-per-vkb or --fee-sat-per-vbyte sets the network fee, see below%n" + " --select-addr or --select-output to select specific outputs%n" + " --locktime=1234 sets the lock time to block 1234%n" + " --locktime=2013/01/01 sets the lock time to 1st Jan 2013%n" + " --allow-unconfirmed will let you create spends of pending non-change outputs.%n" + " --no-pki disables pki verification for payment requests.%n" + " encrypt Requires --password and uses it to encrypt the wallet in place.%n" + " decrypt Requires --password and uses it to decrypt the wallet in place.%n" + " upgrade Upgrade basic or deterministic wallets to deterministic wallets of the given script type.%n" + " If --output-script-type is present, use that as the upgrade target.%n" + " rotate Takes --date and sets that as the key rotation time. Any coins controlled by keys or HD chains created before this date will be re-spent to a key (from an HD tree) that was created after it.%n" + " If --date is missing, the current time is assumed. If the time covers all keys, a new HD tree%n" + " will be created from a new random seed.%n" + " set-creation-time Modify the creation time of the active chains of this wallet. This is useful for repairing wallets that accidently have been created \"in the future\". Currently, watching wallets are not supported.%n" + " If --date is specified, that's the creation date.%n" + " If --unixtime is specified, that's the creation time and it overrides --date.%n" + " If you omit both options, the creation time is being cleared (set to 0).%n") private String actionStr; @CommandLine.Option(names = "--net", description = "Which network to connect to. Valid values: ${COMPLETION-CANDIDATES}. Default: ${DEFAULT-VALUE}") private BitcoinNetwork net = BitcoinNetwork.MAINNET; @CommandLine.Option(names = "--debuglog", description = "Enables logging from the core library.") private boolean debugLog = false; @CommandLine.Option(names = "--force", description = "Overrides any safety checks on the requested action.") private boolean force = false; @CommandLine.Option(names = "--wallet", description = "Specifies what wallet file to load and save.") private File walletFile = null; @CommandLine.Option(names = "--seed", description = "Specifies either a mnemonic code or hex/base58 raw seed bytes.") private String seedStr = null; @CommandLine.Option(names = "--watchkey", description = "Describes a watching wallet using the specified base58 xpub.") private String watchKeyStr = null; @CommandLine.Option(names = "--output-script-type", description = "Provide an output script type to any action that requires one. Valid values: P2PKH, P2WPKH. Default: ${DEFAULT-VALUE}") private ScriptType outputScriptType = ScriptType.P2PKH; @CommandLine.Option(names = "--date", description = "Provide a date in form YYYY-MM-DD to any action that requires one.") private LocalDate date = null; @CommandLine.Option(names = "--unixtime", description = "Provide a date in seconds since epoch.") private Long unixtime = null; @CommandLine.Option(names = "--waitfor", description = "You can wait for the condition specified by the --waitfor flag to become true. Transactions and new blocks will be processed during this time. When the waited for condition is met, the tx/block hash will be printed. Waiting occurs after the --action is performed, if any is specified. Valid values:%n" + "EVER Never quit.%n" + "WALLET_TX Any transaction that sends coins to or from the wallet.%n" + "BLOCK A new block that builds on the best chain.%n" + "BALANCE Waits until the wallets balance meets the --condition.") private WaitForEnum waitFor = null; @CommandLine.Option(names = "--mode", description = "Whether to do full verification of the chain or just light mode. Valid values: ${COMPLETION-CANDIDATES}. Default: ${DEFAULT-VALUE}") private ValidationMode mode = ValidationMode.SPV; @CommandLine.Option(names = "--chain", description = "Specifies the name of the file that stores the block chain.") private File chainFile = null; @CommandLine.Option(names = "--pubkey", description = "Specifies a hex/base58 encoded non-compressed public key.") private String pubKeyStr; @CommandLine.Option(names = "--privkey", description = "Specifies a WIF-, hex- or base58-encoded private key.") private String privKeyStr; @CommandLine.Option(names = "--addr", description ="Specifies a Bitcoin address, either segwit or legacy.") private String addrStr; @CommandLine.Option(names = "--peers", description = "Comma separated IP addresses/domain names for connections instead of peer discovery.") private String peersStr; @CommandLine.Option(names = "--xpubkeys", description = "Specifies external public keys.") private String xpubKeysStr; @CommandLine.Option(names = "--select-addr", description = "When sending, only pick coins from this address.") private String selectAddrStr; @CommandLine.Option(names = "--select-output", description = "When sending, only pick coins from this output.") private String selectOutputStr; @CommandLine.Option(names = "--output", description = "Creates an output with the specified amount, separated by a colon. The special amount ALL is used to use the entire balance.") private List<String> outputsStr; @CommandLine.Option(names = "--fee-per-vkb", description = "Sets the network fee in Bitcoin per kilobyte when sending, e.g. --fee-per-vkb=0.0005") private String feePerVkbStr; @CommandLine.Option(names = "--fee-sat-per-vbyte", description = "Sets the network fee in satoshi per byte when sending, e.g. --fee-sat-per-vbyte=50") private String feeSatPerVbyteStr; @CommandLine.Option(names = "--condition", description = "Allows you to specify a numeric condition for other commands. The format is one of the following operators = < > <= >= immediately followed by a number.%nExamples: --condition=\">5.10\" or --condition=\"<=1\"") private String conditionStr = null; @CommandLine.Option(names = "--locktime", description = "Specifies a lock-time either by date or by block number.") private String lockTimeStr; @CommandLine.Option(names = "--allow-unconfirmed", description = "Lets you create spends of pending non-change outputs.") private boolean allowUnconfirmed = false; @CommandLine.Option(names = "--offline", description = "If specified when sending, don't try and connect, just write the tx to the wallet.") private boolean offline = false; @CommandLine.Option(names = "--ignore-mandatory-extensions", description = "If a wallet has unknown required extensions that would otherwise cause load failures, this overrides that.") private boolean ignoreMandatoryExtensions = false; @CommandLine.Option(names = "--password", description = "For an encrypted wallet, the password is provided here.") private String password = null; @CommandLine.Option(names = "--payment-request", description = "Specifies a payment request either by name of a local file, a bitcoin uri, or url to download the payment request.") private String paymentRequestLocationStr; @CommandLine.Option(names = "--no-pki", description = "Disables pki verification for payment requests.") private boolean noPki = false; @CommandLine.Option(names = "--dump-privkeys", description = "Private keys and seed are printed.") private boolean dumpPrivKeys = false; @CommandLine.Option(names = "--dump-lookahead", description = "Show pregenerated but not yet issued keys.") private boolean dumpLookAhead = false; @CommandLine.Option(names = "--help", usageHelp = true, description = "Displays program options.") private boolean help; private static final Logger log = LoggerFactory.getLogger(WalletTool.class); private static NetworkParameters params; private static BlockStore store; private static AbstractBlockChain chain; private static PeerGroup peerGroup; private static Wallet wallet; private static org.bitcoin.protocols.payments.Protos.PaymentRequest paymentRequest; public static class Condition { public enum Type { // Less than, greater than, less than or equal, greater than or equal. EQUAL, LT, GT, LTE, GTE } Type type; String value; public Condition(String from) { if (from.length() < 2) throw new RuntimeException("Condition string too short: " + from); if (from.startsWith("<=")) type = Type.LTE; else if (from.startsWith(">=")) type = Type.GTE; else if (from.startsWith("<")) type = Type.LT; else if (from.startsWith("=")) type = Type.EQUAL; else if (from.startsWith(">")) type = Type.GT; else throw new RuntimeException("Unknown operator in condition: " + from); String s; switch (type) { case LT: case GT: case EQUAL: s = from.substring(1); break; case LTE: case GTE: s = from.substring(2); break; default: throw new RuntimeException("Unreachable"); } value = s; } public boolean matchBitcoins(Coin comparison) { try { Coin units = parseCoin(value); switch (type) { case LT: return comparison.compareTo(units) < 0; case GT: return comparison.compareTo(units) > 0; case EQUAL: return comparison.compareTo(units) == 0; case LTE: return comparison.compareTo(units) <= 0; case GTE: return comparison.compareTo(units) >= 0; default: throw new RuntimeException("Unreachable"); } } catch (NumberFormatException e) { System.err.println("Could not parse value from condition string: " + value); System.exit(1); return false; } } } private static Condition condition; public enum ActionEnum { DUMP, RAW_DUMP, CREATE, ADD_KEY, ADD_ADDR, DELETE_KEY, CURRENT_RECEIVE_ADDR, SYNC, RESET, SEND, ENCRYPT, DECRYPT, UPGRADE, ROTATE, SET_CREATION_TIME, } public enum WaitForEnum { EVER, WALLET_TX, BLOCK, BALANCE } public enum ValidationMode { FULL, SPV } public static void main(String[] args) { int exitCode = new CommandLine(new WalletTool()).execute(args); System.exit(exitCode); } @Override public Integer call() throws IOException, BlockStoreException { if (help) { System.out.println(Resources.toString(WalletTool.class.getResource("wallet-tool-help.txt"), StandardCharsets.UTF_8)); return 0; } ActionEnum action; try { action = ActionEnum.valueOf(actionStr.toUpperCase().replace("-", "_")); } catch (IllegalArgumentException e) { System.err.println("Could not understand action name " + actionStr); return 1; } if (debugLog) { BriefLogFormatter.init(); log.info("Starting up ..."); } else { // Disable logspam unless there is a flag. java.util.logging.Logger logger = LogManager.getLogManager().getLogger(""); logger.setLevel(Level.SEVERE); } params = NetworkParameters.of(net); String fileName = String.format("%s.chain", net); if (chainFile == null) { chainFile = new File(fileName); } Context.propagate(new Context()); if (conditionStr != null) { condition = new Condition(conditionStr); } if (action == ActionEnum.CREATE) { createWallet(net, walletFile); return 0; // We're done. } if (!walletFile.exists()) { System.err.println("Specified wallet file " + walletFile + " does not exist. Try wallet-tool --wallet=" + walletFile + " create"); return 1; } if (action == ActionEnum.RAW_DUMP) { // Just parse the protobuf and print, then bail out. Don't try and do a real deserialization. This is // useful mostly for investigating corrupted wallets. try (FileInputStream stream = new FileInputStream(walletFile)) { Protos.Wallet proto = WalletProtobufSerializer.parseToProto(stream); proto = attemptHexConversion(proto); System.out.println(proto.toString()); return 0; } } boolean forceReset = action == ActionEnum.RESET || (action == ActionEnum.SYNC && force); try { wallet = Wallet.loadFromFile(walletFile, WalletProtobufSerializer.WalletFactory.DEFAULT, forceReset, ignoreMandatoryExtensions); } catch (UnreadableWalletException e) { System.err.println("Failed to load wallet '" + walletFile + "': " + e.getMessage()); e.printStackTrace(); return 1; } if (wallet.network() != net) { System.err.println("Wallet does not match requested network: " + wallet.network() + " vs " + net); return 1; } // What should we do? switch (action) { case DUMP: dumpWallet(); break; case ADD_KEY: addKey(); break; case ADD_ADDR: addAddr(); break; case DELETE_KEY: deleteKey(); break; case CURRENT_RECEIVE_ADDR: currentReceiveAddr(); break; case RESET: reset(); break; case SYNC: syncChain(); break; case SEND: if (paymentRequestLocationStr != null && outputsStr != null) { System.err.println("--payment-request and --output cannot be used together."); return 1; } else if (feePerVkbStr != null && feeSatPerVbyteStr != null) { System.err.println("--fee-per-kb and --fee-sat-per-byte cannot be used together."); return 1; } else if (outputsStr != null) { Coin feePerVkb = null; if (feePerVkbStr != null) feePerVkb = parseCoin(feePerVkbStr); if (feeSatPerVbyteStr != null) feePerVkb = Coin.valueOf(Long.parseLong(feeSatPerVbyteStr) * 1000); if (selectAddrStr != null && selectOutputStr != null) { System.err.println("--select-addr and --select-output cannot be used together."); return 1; } CoinSelector coinSelector = null; if (selectAddrStr != null) { Address selectAddr; try { selectAddr = wallet.parseAddress(selectAddrStr); } catch (AddressFormatException x) { System.err.println("Could not parse given address, or wrong network: " + selectAddrStr); return 1; } final Address validSelectAddr = selectAddr; coinSelector = (target, candidates) -> { List<TransactionOutput> gathered = new LinkedList<TransactionOutput>(); for (TransactionOutput candidate : candidates) { try { Address candidateAddr = candidate.getScriptPubKey().getToAddress(net); if (validSelectAddr.equals(candidateAddr)) gathered.add(candidate); } catch (ScriptException x) { // swallow } } return new CoinSelection(gathered); }; } if (selectOutputStr != null) { String[] parts = selectOutputStr.split(":", 2); Sha256Hash selectTransactionHash = Sha256Hash.wrap(parts[0]); int selectIndex = Integer.parseInt(parts[1]); coinSelector = (target, candidates) -> { List<TransactionOutput> gathered = new LinkedList<TransactionOutput>(); for (TransactionOutput candidate : candidates) { int candicateIndex = candidate.getIndex(); final Sha256Hash candidateTransactionHash = candidate.getParentTransactionHash(); if (selectIndex == candicateIndex && selectTransactionHash.equals(candidateTransactionHash)) gathered.add(candidate); } return new CoinSelection(gathered); }; } send(coinSelector, outputsStr, feePerVkb, lockTimeStr, allowUnconfirmed); } else if (paymentRequestLocationStr != null) { sendPaymentRequest(paymentRequestLocationStr, !noPki); } else { System.err.println("You must specify a --payment-request or at least one --output=addr:value."); return 1; } break; case ENCRYPT: encrypt(); break; case DECRYPT: decrypt(); break; case UPGRADE: upgrade(); break; case ROTATE: rotate(); break; case SET_CREATION_TIME: setCreationTime(); break; } if (!wallet.isConsistent()) { System.err.println("************** WALLET IS INCONSISTENT *****************"); return 10; } saveWallet(walletFile); if (waitFor != null) { setup(); CompletableFuture<String> futureMessage = wait(waitFor, condition); if (!peerGroup.isRunning()) peerGroup.startAsync(); System.out.println(futureMessage.join()); if (!wallet.isConsistent()) { System.err.println("************** WALLET IS INCONSISTENT *****************"); return 10; } saveWallet(walletFile); } shutdown(); return 0; } private static Protos.Wallet attemptHexConversion(Protos.Wallet proto) { // Try to convert any raw hashes and such to textual equivalents for easier debugging. This makes it a bit // less "raw" but we will just abort on any errors. try { Protos.Wallet.Builder builder = proto.toBuilder(); for (Protos.Transaction tx : builder.getTransactionList()) { Protos.Transaction.Builder txBuilder = tx.toBuilder(); txBuilder.setHash(bytesToHex(txBuilder.getHash())); for (int i = 0; i < txBuilder.getBlockHashCount(); i++) txBuilder.setBlockHash(i, bytesToHex(txBuilder.getBlockHash(i))); for (Protos.TransactionInput input : txBuilder.getTransactionInputList()) { Protos.TransactionInput.Builder inputBuilder = input.toBuilder(); inputBuilder.setTransactionOutPointHash(bytesToHex(inputBuilder.getTransactionOutPointHash())); } for (Protos.TransactionOutput output : txBuilder.getTransactionOutputList()) { Protos.TransactionOutput.Builder outputBuilder = output.toBuilder(); if (outputBuilder.hasSpentByTransactionHash()) outputBuilder.setSpentByTransactionHash(bytesToHex(outputBuilder.getSpentByTransactionHash())); } // TODO: keys, ip addresses etc. } return builder.build(); } catch (Throwable throwable) { log.error("Failed to do hex conversion on wallet proto", throwable); return proto; } } private static ByteString bytesToHex(ByteString bytes) { return ByteString.copyFrom(ByteUtils.formatHex(bytes.toByteArray()).getBytes()); } private void upgrade() { DeterministicKeyChain activeKeyChain = wallet.getActiveKeyChain(); ScriptType currentOutputScriptType = activeKeyChain != null ? activeKeyChain.getOutputScriptType() : null; if (!wallet.isDeterministicUpgradeRequired(outputScriptType)) { System.err .println("No upgrade from " + (currentOutputScriptType != null ? currentOutputScriptType : "basic") + " to " + outputScriptType); return; } AesKey aesKey = null; if (wallet.isEncrypted()) { aesKey = passwordToKey(true); if (aesKey == null) return; } wallet.upgradeToDeterministic(outputScriptType, aesKey); System.out.println("Upgraded from " + (currentOutputScriptType != null ? currentOutputScriptType : "basic") + " to " + outputScriptType); } private void rotate() throws BlockStoreException { setup(); peerGroup.start(); // Set a key rotation time and possibly broadcast the resulting maintenance transactions. Instant rotationTime = TimeUtils.currentTime(); if (date != null) { rotationTime = Instant.from(date); } else if (unixtime != null) { rotationTime = Instant.ofEpochSecond(unixtime); } log.info("Setting wallet key rotation time to {}", TimeUtils.dateTimeFormat(rotationTime)); wallet.setKeyRotationTime(rotationTime); AesKey aesKey = null; if (wallet.isEncrypted()) { aesKey = passwordToKey(true); if (aesKey == null) return; } wallet.doMaintenance(aesKey, true).join(); } private void encrypt() { if (password == null) { System.err.println("You must provide a --password"); return; } if (wallet.isEncrypted()) { System.err.println("This wallet is already encrypted."); return; } wallet.encrypt(password); } private void decrypt() { if (password == null) { System.err.println("You must provide a --password"); return; } if (!wallet.isEncrypted()) { System.err.println("This wallet is not encrypted."); return; } try { wallet.decrypt(password); } catch (KeyCrypterException e) { System.err.println("Password incorrect."); } } private void addAddr() { if (addrStr == null) { System.err.println("You must specify an --addr to watch."); return; } try { Address address = LegacyAddress.fromBase58(addrStr, net); // If no creation time is specified, assume genesis (zero). getCreationTime().ifPresentOrElse( creationTime -> wallet.addWatchedAddress(address, creationTime), () -> wallet.addWatchedAddress(address)); } catch (AddressFormatException e) { System.err.println("Could not parse given address, or wrong network: " + addrStr); } } private void send(CoinSelector coinSelector, List<String> outputs, Coin feePerVkb, String lockTimeStr, boolean allowUnconfirmed) throws VerificationException { Coin balance = coinSelector != null ? wallet.getBalance(coinSelector) : wallet.getBalance(allowUnconfirmed ? BalanceType.ESTIMATED : BalanceType.AVAILABLE); // Convert the input strings to outputs. Transaction tx = new Transaction(); for (String spec : outputs) { try { OutputSpec outputSpec = new OutputSpec(spec); Coin value = outputSpec.value != null ? outputSpec.value : balance; if (outputSpec.isAddress()) tx.addOutput(value, outputSpec.addr); else tx.addOutput(value, outputSpec.key); } catch (AddressFormatException.WrongNetwork e) { System.err.println("Malformed output specification, address is for a different network: " + spec); return; } catch (AddressFormatException e) { System.err.println("Malformed output specification, could not parse as address: " + spec); return; } catch (NumberFormatException e) { System.err.println("Malformed output specification, could not parse as value: " + spec); return; } catch (IllegalArgumentException e) { System.err.println(e.getMessage()); return; } } boolean emptyWallet = tx.getOutputs().size() == 1 && tx.getOutput(0).getValue().equals(balance); if (emptyWallet) { log.info("Emptying out wallet, recipient may get less than what you expect"); } AesKey aesKey; if (password != null) { aesKey = passwordToKey(true); if (aesKey == null) return; // Error message already printed. } else { aesKey = null; } SendRequest req = buildSendRequest(tx, emptyWallet, allowUnconfirmed, coinSelector, feePerVkb, aesKey); try { wallet.completeTx(req); } catch (InsufficientMoneyException e) { System.err.println("Insufficient funds: have " + balance.toFriendlyString()); } try { if (lockTimeStr != null) { tx.setLockTime(parseLockTimeStr(lockTimeStr)); // For lock times to take effect, at least one output must have a non-final sequence number. tx.getInput(0).setSequenceNumber(0); // And because we modified the transaction after it was completed, we must re-sign the inputs. wallet.signTransaction(req); } } catch (ParseException e) { System.err.println("Could not understand --locktime of " + lockTimeStr); return; } catch (ScriptException e) { throw new RuntimeException(e); } System.out.println("id: " + tx.getTxId()); System.out.println("tx: " + ByteUtils.formatHex(tx.serialize())); if (offline) { wallet.commitTx(tx); return; } try { setup(); peerGroup.start(); } catch (BlockStoreException e) { throw new RuntimeException(e); } try { // Wait for peers to connect, the tx to be sent to one of them and for it to be propagated across the // network. Once propagation is complete and we heard the transaction back from all our peers, it will // be committed to the wallet. peerGroup.broadcastTransaction(tx).awaitRelayed().get(); // Hack for regtest/single peer mode, as we're about to shut down and won't get an ACK from the remote end. List<Peer> peerList = peerGroup.getConnectedPeers(); if (peerList.size() == 1) peerList.get(0).sendPing().get(); } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } } // "Atomically" create a SendRequest. In the future SendRequest may be immutable and this method will be updated private SendRequest buildSendRequest(Transaction tx, boolean emptyWallet, boolean allowUnconfirmed, @Nullable CoinSelector coinSelector, @Nullable Coin feePerVkb, @Nullable AesKey aesKey) { SendRequest req = SendRequest.forTx(tx); req.emptyWallet = emptyWallet; if (coinSelector != null) { req.coinSelector = coinSelector; req.recipientsPayFees = true; } if (allowUnconfirmed) { // Note that this will overwrite the CoinSelector set above req.allowUnconfirmed(); } if (feePerVkb != null) req.setFeePerVkb(feePerVkb); req.aesKey = aesKey; return req; } static class OutputSpec { public final Coin value; public final Address addr; public final ECKey key; public OutputSpec(String spec) throws IllegalArgumentException { String[] parts = spec.split(":"); if (parts.length != 2) { throw new IllegalArgumentException("Malformed output specification, must have two parts separated by :"); } String destination = parts[0]; if ("ALL".equalsIgnoreCase(parts[1])) value = null; else value = parseCoin(parts[1]); if (destination.startsWith("0")) { // Treat as a raw public key. byte[] pubKey = new BigInteger(destination, 16).toByteArray(); key = ECKey.fromPublicOnly(pubKey); addr = null; } else { // Treat as an address. addr = wallet.parseAddress(destination); key = null; } } public boolean isAddress() { return addr != null; } } /** * Parses the string either as a whole number of blocks, or if it contains slashes as a YYYY/MM/DD format date * and returns the lock time in wire format. */ private static long parseLockTimeStr(String lockTimeStr) throws ParseException { if (lockTimeStr.contains("/")) { Instant time = Instant.from(DateTimeFormatter.ofPattern("yyyy/MM/dd").parse(lockTimeStr)); return time.getEpochSecond(); } return Long.parseLong(lockTimeStr); } private void sendPaymentRequest(String location, boolean verifyPki) { if (location.startsWith("http") || location.startsWith("bitcoin")) { try { CompletableFuture<PaymentSession> future; if (location.startsWith("http")) { future = PaymentSession.createFromUrl(location, verifyPki); } else { BitcoinURI paymentRequestURI = BitcoinURI.of(location); future = PaymentSession.createFromBitcoinUri(paymentRequestURI, verifyPki); } PaymentSession session = future.get(); if (session != null) { send(session); } else { System.err.println("Server returned null session"); System.exit(1); } } catch (PaymentProtocolException e) { System.err.println("Error creating payment session " + e.getMessage()); System.exit(1); } catch (BitcoinURIParseException e) { System.err.println("Invalid bitcoin uri: " + e.getMessage()); System.exit(1); } catch (InterruptedException e) { // Ignore. } catch (ExecutionException e) { throw new RuntimeException(e); } } else { // Try to open the payment request as a file. FileInputStream stream = null; try { File paymentRequestFile = new File(location); stream = new FileInputStream(paymentRequestFile); } catch (Exception e) { System.err.println("Failed to open file: " + e.getMessage()); System.exit(1); } try { paymentRequest = org.bitcoin.protocols.payments.Protos.PaymentRequest.newBuilder().mergeFrom(stream).build(); } catch(IOException e) { System.err.println("Failed to parse payment request from file " + e.getMessage()); System.exit(1); } PaymentSession session = null; try { session = new PaymentSession(paymentRequest, verifyPki); } catch (PaymentProtocolException e) { System.err.println("Error creating payment session " + e.getMessage()); System.exit(1); } send(session); } } private void send(PaymentSession session) { System.out.println("Payment Request"); System.out.println("Coin: " + session.getValue().toFriendlyString()); System.out.println("Date: " + session.time()); System.out.println("Memo: " + session.getMemo()); if (session.pkiVerificationData != null) { System.out.println("Pki-Verified Name: " + session.pkiVerificationData.displayName); System.out.println("PKI data verified by: " + session.pkiVerificationData.rootAuthorityName); } final SendRequest req = session.getSendRequest(); if (password != null) { req.aesKey = passwordToKey(true); if (req.aesKey == null) return; // Error message already printed. } // Complete the transaction try { wallet.completeTx(req); // may throw InsufficientMoneyException. } catch (InsufficientMoneyException e) { System.err.println("Insufficient funds: have " + wallet.getBalance().toFriendlyString()); System.exit(1); } if (offline) { wallet.commitTx(req.tx); return; } // Setup network communication (but not PeerGroup) try { setup(); } catch (BlockStoreException e) { System.err.println("BlockStoreException: " + e.getMessage()); System.exit(1); } // Send the payment try { // No refund address specified, no user-specified memo field. PaymentProtocol.Ack ack = session.sendPayment(Collections.singletonList(req.tx), null, null).get(); wallet.commitTx(req.tx); System.out.println("Memo from server: " + ack.getMemo()); } catch (ExecutionException e) { try { throw e.getCause(); } catch (PaymentProtocolException.InvalidPaymentRequestURL e1) { System.out.println("Missing/Invalid Payment Request URL, broadcasting transaction with PeerGroup"); broadcastPayment(req); } catch (PaymentProtocolException e1) { System.err.println("Failed to send payment " + e.getMessage()); System.exit(1); } catch (IOException e1) { System.err.println("Invalid payment " + e.getMessage()); System.exit(1); } catch (Throwable t) { System.err.println("Unexpected error " + e.getMessage()); System.exit(1); } } catch (VerificationException e) { System.err.println("Failed to send payment " + e.getMessage()); System.exit(1); } catch (InterruptedException e) { System.err.println("Interrupted: " + e.getMessage()); System.exit(1); } } private void broadcastPayment(SendRequest req) { peerGroup.start(); TransactionBroadcast broadcast = peerGroup.broadcastTransaction(req.tx); try { // Wait for broadcast to be sent broadcast.awaitRelayed().get(); } catch (InterruptedException | ExecutionException e) { System.err.println("Failed to broadcast payment " + e.getMessage()); System.exit(1); } } /** * Wait for a condition to be satisfied * @param waitFor condition type to wait for * @param condition balance condition to wait for * @return A (future) human-readable message (txId, block hash, or balance) to display when wait is complete */ private CompletableFuture<String> wait(WaitForEnum waitFor, Condition condition) { CompletableFuture<String> future = new CompletableFuture<>(); switch (waitFor) { case EVER: break; // Future will never complete case WALLET_TX: // Future will complete with a transaction ID string Consumer<Transaction> txListener = tx -> future.complete(tx.getTxId().toString()); // Both listeners run in a peer thread wallet.addCoinsReceivedEventListener((wallet, tx, prevBalance, newBalance) -> txListener.accept(tx)); wallet.addCoinsSentEventListener((wallet, tx, prevBalance, newBalance) -> txListener.accept(tx)); break; case BLOCK: // Future will complete with a Block hash string peerGroup.addBlocksDownloadedEventListener((peer, block, filteredBlock, blocksLeft) -> future.complete(block.getHashAsString()) ); break; case BALANCE: // Future will complete with a balance amount string // Check if the balance already meets the given condition. Coin existingBalance = wallet.getBalance(Wallet.BalanceType.ESTIMATED); if (condition.matchBitcoins(existingBalance)) { future.complete(existingBalance.toFriendlyString()); } else { Runnable onChange = () -> { synchronized (this) { saveWallet(walletFile); Coin balance = wallet.getBalance(Wallet.BalanceType.ESTIMATED); if (condition.matchBitcoins(balance)) { future.complete(balance.toFriendlyString()); } } }; wallet.addCoinsReceivedEventListener((w, t, p, n) -> onChange.run()); wallet.addCoinsSentEventListener((w, t, p, n) -> onChange.run()); wallet.addChangeEventListener(w -> onChange.run()); wallet.addReorganizeEventListener(w -> onChange.run()); } break; } return future; } private void reset() { // Delete the transactions and save. In future, reset the chain head pointer. wallet.clearTransactions(0); saveWallet(walletFile); } // Sets up all objects needed for network communication but does not bring up the peers. private void setup() throws BlockStoreException { if (store != null) return; // Already done. // Will create a fresh chain if one doesn't exist or there is an issue with this one. boolean reset = !chainFile.exists(); if (reset) { // No chain, so reset the wallet as we will be downloading from scratch. System.out.println("Chain file is missing so resetting the wallet."); reset(); } if (mode == ValidationMode.SPV) { store = new SPVBlockStore(params, chainFile); if (reset) { try { CheckpointManager.checkpoint(params, CheckpointManager.openStream(params), store, wallet.earliestKeyCreationTime()); StoredBlock head = store.getChainHead(); System.out.println("Skipped to checkpoint " + head.getHeight() + " at " + TimeUtils.dateTimeFormat(head.getHeader().time())); } catch (IOException x) { System.out.println("Could not load checkpoints: " + x.getMessage()); } } chain = new BlockChain(params, wallet, store); } else if (mode == ValidationMode.FULL) { store = new MemoryFullPrunedBlockStore(params, 5000); chain = new FullPrunedBlockChain(params, wallet, (FullPrunedBlockStore) store); } // This will ensure the wallet is saved when it changes. wallet.autosaveToFile(walletFile, Duration.ofSeconds(5), null); if (peerGroup == null) { peerGroup = new PeerGroup(net, chain); } peerGroup.setUserAgent("WalletTool", "1.0"); if (net == BitcoinNetwork.REGTEST) { peerGroup.addAddress(PeerAddress.localhost(params)); peerGroup.setMinBroadcastConnections(1); peerGroup.setMaxConnections(1); } peerGroup.addWallet(wallet); if (peersStr != null) { String[] peerAddrs = peersStr.split(","); for (String peer : peerAddrs) { try { peerGroup.addAddress(PeerAddress.simple(InetAddress.getByName(peer), params.getPort())); } catch (UnknownHostException e) { System.err.println("Could not understand peer domain name/IP address: " + peer + ": " + e.getMessage()); System.exit(1); } } } else { peerGroup.setRequiredServices(0); } } private void syncChain() { try { setup(); int startTransactions = wallet.getTransactions(true).size(); DownloadProgressTracker listener = new DownloadProgressTracker(); peerGroup.start(); peerGroup.startBlockChainDownload(listener); try { listener.await(); } catch (InterruptedException e) { System.err.println("Chain download interrupted, quitting ..."); System.exit(1); } int endTransactions = wallet.getTransactions(true).size(); if (endTransactions > startTransactions) { System.out.println("Synced " + (endTransactions - startTransactions) + " transactions."); } } catch (BlockStoreException e) { System.err.println("Error reading block chain file " + chainFile + ": " + e.getMessage()); e.printStackTrace(); } } private void shutdown() { try { if (peerGroup == null) return; // setup() never called so nothing to do. if (peerGroup.isRunning()) peerGroup.stop(); saveWallet(walletFile); store.close(); wallet = null; } catch (BlockStoreException e) { throw new RuntimeException(e); } } private void createWallet(Network network, File walletFile) throws IOException { KeyChainGroupStructure keyChainGroupStructure = KeyChainGroupStructure.BIP32; if (walletFile.exists() && !force) { System.err.println("Wallet creation requested but " + walletFile + " already exists, use --force"); return; } Instant creationTime = getCreationTime().orElse(MnemonicCode.BIP39_STANDARDISATION_TIME); if (seedStr != null) { DeterministicSeed seed; // Parse as mnemonic code. final List<String> split = splitMnemonic(seedStr); String passphrase = ""; // TODO allow user to specify a passphrase seed = DeterministicSeed.ofMnemonic(split, passphrase, creationTime); try { seed.check(); } catch (MnemonicException.MnemonicLengthException e) { System.err.println("The seed did not have 12 words in, perhaps you need quotes around it?"); return; } catch (MnemonicException.MnemonicWordException e) { System.err.println("The seed contained an unrecognised word: " + e.badWord); return; } catch (MnemonicException.MnemonicChecksumException e) { System.err.println("The seed did not pass checksumming, perhaps one of the words is wrong?"); return; } catch (MnemonicException e) { // not reached - all subclasses handled above throw new RuntimeException(e); } wallet = Wallet.fromSeed(network, seed, outputScriptType, keyChainGroupStructure); } else if (watchKeyStr != null) { wallet = Wallet.fromWatchingKeyB58(network, watchKeyStr, creationTime); } else { wallet = Wallet.createDeterministic(network, outputScriptType, keyChainGroupStructure); } if (password != null) wallet.encrypt(password); wallet.saveToFile(walletFile); } private List<String> splitMnemonic(String seedStr) { return Stream.of(seedStr.split("[ :;,]")) // anyOf(" :;,") .filter(s -> !s.isEmpty()) .collect(Collectors.toUnmodifiableList()); } private void saveWallet(File walletFile) { try { // This will save the new state of the wallet to a temp file then rename, in case anything goes wrong. wallet.saveToFile(walletFile); } catch (IOException e) { System.err.println("Failed to save wallet! Old wallet should be left untouched."); e.printStackTrace(); System.exit(1); } } private void addKey() { ECKey key; Optional<Instant> creationTime = getCreationTime(); if (privKeyStr != null) { try { DumpedPrivateKey dpk = DumpedPrivateKey.fromBase58(net, privKeyStr); // WIF key = dpk.getKey(); } catch (AddressFormatException e) { byte[] decode = parseAsHexOrBase58(privKeyStr); if (decode == null) { System.err.println("Could not understand --privkey as either WIF, hex or base58: " + privKeyStr); return; } key = ECKey.fromPrivate(ByteUtils.bytesToBigInteger(decode)); } if (pubKeyStr != null) { // Give the user a hint. System.out.println("You don't have to specify --pubkey when a private key is supplied."); } creationTime.ifPresentOrElse(key::setCreationTime, key::clearCreationTime); } else if (pubKeyStr != null) { byte[] pubkey = parseAsHexOrBase58(pubKeyStr); key = ECKey.fromPublicOnly(pubkey); creationTime.ifPresentOrElse(key::setCreationTime, key::clearCreationTime); } else { System.err.println("Either --privkey or --pubkey must be specified."); return; } if (wallet.hasKey(key)) { System.err.println("That key already exists in this wallet."); return; } try { if (wallet.isEncrypted()) { AesKey aesKey = passwordToKey(true); if (aesKey == null) return; // Error message already printed. key = key.encrypt(Objects.requireNonNull(wallet.getKeyCrypter()), aesKey); } } catch (KeyCrypterException kce) { System.err.println("There was an encryption related error when adding the key. The error was '" + kce.getMessage() + "'."); return; } if (!key.isCompressed()) System.out.println("WARNING: Importing an uncompressed key"); wallet.importKey(key); System.out.print("Addresses: " + key.toAddress(ScriptType.P2PKH, net)); if (key.isCompressed()) System.out.print("," + key.toAddress(ScriptType.P2WPKH, net)); System.out.println(); } @Nullable private AesKey passwordToKey(boolean printError) { if (password == null) { if (printError) System.err.println("You must provide a password."); return null; } if (!wallet.checkPassword(password)) { if (printError) System.err.println("The password is incorrect."); return null; } return Objects.requireNonNull(wallet.getKeyCrypter()).deriveKey(password); } /** * Attempts to parse the given string as arbitrary-length hex or base58 and then return the results, or null if * neither parse was successful. */ private byte[] parseAsHexOrBase58(String data) { try { return ByteUtils.parseHex(data); } catch (Exception e) { // Didn't decode as hex, try base58. try { return Base58.decodeChecked(data); } catch (AddressFormatException e1) { return null; } } } private Optional<Instant> getCreationTime() { if (unixtime != null) return Optional.of(Instant.ofEpochSecond(unixtime)); else if (date != null) return Optional.of(date.atStartOfDay(ZoneId.systemDefault()).toInstant()); else return Optional.empty(); } private void deleteKey() { if (pubKeyStr == null && addrStr == null) { System.err.println("One of --pubkey or --addr must be specified."); return; } ECKey key; if (pubKeyStr != null) { key = wallet.findKeyFromPubKey(ByteUtils.parseHex(pubKeyStr)); } else { try { Address address = wallet.parseAddress(addrStr); key = wallet.findKeyFromAddress(address); } catch (AddressFormatException e) { System.err.println(addrStr + " does not parse as a Bitcoin address of the right network parameters."); return; } } if (key == null) { System.err.println("Wallet does not seem to contain that key."); return; } boolean removed = wallet.removeKey(key); if (removed) System.out.println("Key " + key + " was removed"); else System.err.println("Key " + key + " could not be removed"); } private void currentReceiveAddr() { Address address = wallet.currentReceiveAddress(); System.out.println(address); } private void dumpWallet() throws BlockStoreException { // Setup to get the chain height so we can estimate lock times, but don't wipe the transactions if it's not // there just for the dump case. if (chainFile.exists()) setup(); if (dumpPrivKeys && wallet.isEncrypted()) { if (password != null) { final AesKey aesKey = passwordToKey(true); if (aesKey == null) return; // Error message already printed. printWallet( aesKey); } else { System.err.println("Can't dump privkeys, wallet is encrypted."); return; } } else { printWallet( null); } } private void printWallet(@Nullable AesKey aesKey) { System.out.println(wallet.toString(dumpLookAhead, dumpPrivKeys, aesKey, true, true, chain)); } private void setCreationTime() { Optional<Instant> creationTime = getCreationTime(); for (DeterministicKeyChain chain : wallet.getActiveKeyChains()) { DeterministicSeed seed = chain.getSeed(); if (seed == null) System.out.println("Active chain does not have a seed: " + chain); else creationTime.ifPresentOrElse(seed::setCreationTime, seed::clearCreationTime); } System.out.println(creationTime .map(time -> "Setting creation time to: " + TimeUtils.dateTimeFormat(time)) .orElse("Clearing creation time.")); } }
61,736
46.710201
363
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/overlay/OverlayableStackPaneController.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.walletfx.overlay; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import org.bitcoinj.walletfx.utils.GuiUtils; import javax.annotation.Nullable; import java.io.IOException; import java.net.URL; import static org.bitcoinj.walletfx.utils.GuiUtils.blurIn; import static org.bitcoinj.walletfx.utils.GuiUtils.blurOut; import static org.bitcoinj.walletfx.utils.GuiUtils.checkGuiThread; import static org.bitcoinj.walletfx.utils.GuiUtils.explodeOut; import static org.bitcoinj.walletfx.utils.GuiUtils.fadeIn; import static org.bitcoinj.walletfx.utils.GuiUtils.fadeOutAndRemove; import static org.bitcoinj.walletfx.utils.GuiUtils.zoomIn; /** * Abstract Controller for a {@link StackPane} that can have other {@link Pane}s displayed on top of it as a modals. */ public abstract class OverlayableStackPaneController { /** * The {@link StackPane} that contains the {@code mainUI} and any active overlays. Typically, this * will be the root node of a {@code Scene} contained in a {@code Stage}. */ protected final StackPane uiStack = new StackPane(); /** * The {@link Pane} containing the bottom-most view, that can be overlaid with other views. */ protected Pane mainUI; private final Node stopClickPane = new Pane(); @Nullable private OverlayUI<? extends OverlayController<?>> currentOverlay; public <T extends OverlayController<T>> OverlayUI<T> overlayUI(Node node, T controller) { checkGuiThread(); OverlayUI<T> pair = new OverlayUI<>(node, controller); controller.initOverlay(this, pair); pair.show(); return pair; } /** Loads the FXML file with the given name, blurs out the main UI and puts this one on top. */ public <T extends OverlayController<T>> OverlayUI<T> overlayUI(String name) { try { checkGuiThread(); // Load the UI from disk. URL location = GuiUtils.getResource(this.getClass(), name); FXMLLoader loader = new FXMLLoader(location); Pane overlayNode = loader.load(); T controller = loader.getController(); OverlayUI<T> pair = new OverlayUI<>(overlayNode, controller); controller.initOverlay(this, pair); pair.show(); return pair; } catch (IOException e) { throw new RuntimeException(e); // Can't happen. } } public class OverlayUI<T extends OverlayController<T>> { private Node ui; public T controller; public OverlayUI(Node ui, T controller) { this.ui = ui; this.controller = controller; } public void show() { checkGuiThread(); if (currentOverlay == null) { uiStack.getChildren().add(stopClickPane); uiStack.getChildren().add(ui); blurOut(mainUI); //darken(mainUI); fadeIn(ui); zoomIn(ui); } else { // Do a quick transition between the current overlay and the next. // Bug here: we don't pay attention to changes in outsideClickDismisses. explodeOut(currentOverlay.ui); fadeOutAndRemove(uiStack, currentOverlay.ui); uiStack.getChildren().add(ui); ui.setOpacity(0.0); fadeIn(ui, 100); zoomIn(ui, 100); } currentOverlay = this; } public void outsideClickDismisses() { stopClickPane.setOnMouseClicked((ev) -> done()); } public void done() { checkGuiThread(); if (ui == null) return; // In the middle of being dismissed and got an extra click. explodeOut(ui); fadeOutAndRemove(uiStack, ui, stopClickPane); blurIn(mainUI); //undark(mainUI); this.ui = null; this.controller = null; currentOverlay = null; } } }
4,729
35.666667
116
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/overlay/OverlayController.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.walletfx.overlay; /** * Interface for controllers displayed via OverlayWindow.OverlayUI */ public interface OverlayController<T> { /** * @param rootController The root controller (containing the StackPane) * @param ui The overlay UI (node, controller pair) */ void initOverlay(OverlayableStackPaneController rootController, OverlayableStackPaneController.OverlayUI<? extends OverlayController<T>> ui); }
1,063
37
145
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/application/AppDelegate.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.walletfx.application; import javafx.application.Application; import javafx.stage.Stage; /** * A delegate that implements JavaFX {@link Application} */ public interface AppDelegate { /** * Implement this method if you have code to run during {@link Application#init()} or * if you need a reference to the actual {@code Application object} * @param application a reference to the actual {@code Application} object * @throws Exception something bad happened */ default void init(Application application) throws Exception { } void start(Stage primaryStage) throws Exception; void stop() throws Exception; }
1,285
34.722222
89
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/application/WalletApplication.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.walletfx.application; import com.google.common.util.concurrent.Service; import javafx.application.Platform; import javafx.scene.input.KeyCombination; import javafx.stage.Stage; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.internal.PlatformUtils; import org.bitcoinj.core.Context; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.kits.WalletAppKit; import org.bitcoinj.utils.AppDataDirectory; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.DeterministicSeed; import org.bitcoinj.wallet.KeyChainGroupStructure; import org.bitcoinj.walletfx.utils.GuiUtils; import wallettemplate.WalletSetPasswordController; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import static org.bitcoinj.walletfx.utils.GuiUtils.informationalAlert; /** * Base class for JavaFX Wallet Applications */ public abstract class WalletApplication implements AppDelegate { private static WalletApplication instance; private WalletAppKit walletAppKit; private final String applicationName; private final BitcoinNetwork network; private final KeyChainGroupStructure keyChainGroupStructure; private final ScriptType preferredOutputScriptType; private final String walletFileName; private MainWindowController controller; public WalletApplication(String applicationName, BitcoinNetwork network, ScriptType preferredOutputScriptType, KeyChainGroupStructure keyChainGroupStructure) { instance = this; this.applicationName = applicationName; this.walletFileName = applicationName.replaceAll("[^a-zA-Z0-9.-]", "_") + "-" + suffixFromNetwork(network); this.network = network; this.preferredOutputScriptType = preferredOutputScriptType; this.keyChainGroupStructure = keyChainGroupStructure; } public WalletApplication(String applicationName, BitcoinNetwork network, ScriptType preferredOutputScriptType) { this(applicationName, network, preferredOutputScriptType, KeyChainGroupStructure.BIP43); } public static WalletApplication instance() { return instance; } public WalletAppKit walletAppKit() { return walletAppKit; } public String applicationName() { return applicationName; } /** * @return Parameters for network this wallet is running on * @deprecated Use {@link #network} (or {@link NetworkParameters#of} if you really need a {@link NetworkParameters}.) */ @Deprecated public NetworkParameters params() { return NetworkParameters.of(network); } public BitcoinNetwork network() { return network; } public ScriptType preferredOutputScriptType() { return preferredOutputScriptType; } public MainWindowController mainWindowController() { return controller; } protected abstract MainWindowController loadController() throws IOException; @Override public void start(Stage primaryStage) throws Exception { try { startImpl(primaryStage); } catch (Throwable e) { GuiUtils.crashAlert(e); throw e; } } private void startImpl(Stage primaryStage) throws IOException { // Show the crash dialog for any exceptions that we don't handle and that hit the main loop. GuiUtils.handleCrashesOnThisThread(); // Make log output concise. BriefLogFormatter.init(); if (PlatformUtils.isMac()) { // We could match the Mac Aqua style here, except that (a) Modena doesn't look that bad, and (b) // the date picker widget is kinda broken in AquaFx and I can't be bothered fixing it. // AquaFx.style(); } controller = loadController(); primaryStage.setScene(controller.scene()); startWalletAppKit(primaryStage); controller.scene().getAccelerators().put(KeyCombination.valueOf("Shortcut+F"), () -> walletAppKit().peerGroup().getDownloadPeer().close()); } protected void startWalletAppKit(Stage primaryStage) throws IOException { Context.propagate(new Context()); // Tell bitcoinj to run event handlers on the JavaFX UI thread. This keeps things simple and means // we cannot forget to switch threads when adding event handlers. Unfortunately, the DownloadListener // we give to the app kit is currently an exception and runs on a library thread. It'll get fixed in // a future version. Threading.USER_THREAD = Platform::runLater; // Create the app kit. It won't do any heavyweight initialization until after we start it. setupWalletKit(null); if (walletAppKit.isChainFileLocked()) { informationalAlert("Already running", "This application is already running and cannot be started twice."); Platform.exit(); return; } primaryStage.show(); WalletSetPasswordController.initEstimatedKeyDerivationTime(); walletAppKit.addListener(new Service.Listener() { @Override public void failed(Service.State from, Throwable failure) { GuiUtils.crashAlert(failure); } }, Platform::runLater); walletAppKit.startAsync(); } public void setupWalletKit(@Nullable DeterministicSeed seed) { // If seed is non-null it means we are restoring from backup. File appDataDirectory = AppDataDirectory.get(applicationName).toFile(); walletAppKit = new WalletAppKit(network, preferredOutputScriptType, keyChainGroupStructure, appDataDirectory, walletFileName) { @Override protected void onSetupCompleted() { Platform.runLater(controller::onBitcoinSetup); } }; // Now configure and start the appkit. This will take a second or two - we could show a temporary splash screen // or progress widget to keep the user engaged whilst we initialise, but we don't. if (network == BitcoinNetwork.REGTEST) { walletAppKit.connectToLocalHost(); // You should run a regtest mode bitcoind locally. } walletAppKit.setDownloadListener(controller.progressBarUpdater()) .setBlockingStartup(false) .setUserAgent(applicationName, "1.0"); if (seed != null) walletAppKit.restoreWalletFromSeed(seed); } @Override public void stop() throws Exception { walletAppKit.stopAsync(); walletAppKit.awaitTerminated(); // Forcibly terminate the JVM because Orchid likes to spew non-daemon threads everywhere. Runtime.getRuntime().exit(0); } protected String suffixFromNetwork(BitcoinNetwork network) { switch(network) { case MAINNET: return "main"; case TESTNET: return "test"; case SIGNET: return "signet"; case REGTEST: return "regtest"; default: throw new IllegalArgumentException("Unsupported network"); } } }
7,872
37.404878
163
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/application/MainWindowController.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.walletfx.application; import javafx.scene.Scene; import javafx.scene.layout.Pane; import org.bitcoinj.core.listeners.DownloadProgressTracker; import org.bitcoinj.walletfx.overlay.OverlayableStackPaneController; /** * Abstract controller class for a wallet application's main window (i.e. the one that is the primary @{code Stage}) */ public abstract class MainWindowController extends OverlayableStackPaneController { protected Scene scene; public Scene scene() { return scene; } public abstract void controllerStart(Pane mainUI, String cssResourceName); public abstract void onBitcoinSetup(); public abstract void restoreFromSeedAnimation(); public abstract DownloadProgressTracker progressBarUpdater(); }
1,386
32.02381
116
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/utils/GuiUtils.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.walletfx.utils; import javafx.animation.*; import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.effect.GaussianBlur; import javafx.scene.layout.Pane; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.util.Duration; import java.io.IOException; import java.net.URL; import java.util.Objects; import java.util.function.BiConsumer; import static org.bitcoinj.base.internal.Preconditions.checkState; import static org.bitcoinj.walletfx.utils.WTUtils.unchecked; public class GuiUtils { public static void runAlert(BiConsumer<Stage, AlertWindowController> setup) { try { // JavaFX2 doesn't actually have a standard alert template. Instead the Scene Builder app will create FXML // files for an alert window for you, and then you customise it as you see fit. I guess it makes sense in // an odd sort of way. Stage dialogStage = new Stage(); dialogStage.initModality(Modality.APPLICATION_MODAL); FXMLLoader loader = new FXMLLoader(GuiUtils.class.getResource("alert.fxml")); Pane pane = loader.load(); AlertWindowController controller = loader.getController(); setup.accept(dialogStage, controller); dialogStage.setScene(new Scene(pane)); dialogStage.showAndWait(); } catch (IOException e) { // We crashed whilst trying to show the alert dialog (this should never happen). Give up! throw new RuntimeException(e); } } public static void crashAlert(Throwable t) { t.printStackTrace(); Throwable rootCause = findRootCause(t); Runnable r = () -> { runAlert((stage, controller) -> controller.crashAlert(stage, rootCause.toString())); Platform.exit(); }; if (Platform.isFxApplicationThread()) r.run(); else Platform.runLater(r); } /** Show a GUI alert box for any unhandled exceptions that propagate out of this thread. */ public static void handleCrashesOnThisThread() { Thread.currentThread().setUncaughtExceptionHandler((thread, exception) -> GuiUtils.crashAlert(findRootCause(exception))); } public static void informationalAlert(String message, String details, Object... args) { String formattedDetails = String.format(details, args); Runnable r = () -> runAlert((stage, controller) -> controller.informational(stage, message, formattedDetails)); if (Platform.isFxApplicationThread()) r.run(); else Platform.runLater(r); } public static final int UI_ANIMATION_TIME_MSEC = 600; public static final Duration UI_ANIMATION_TIME = Duration.millis(UI_ANIMATION_TIME_MSEC); public static Animation fadeIn(Node ui) { return fadeIn(ui, 0); } public static Animation fadeIn(Node ui, int delayMillis) { ui.setCache(true); FadeTransition ft = new FadeTransition(Duration.millis(UI_ANIMATION_TIME_MSEC), ui); ft.setFromValue(0.0); ft.setToValue(1.0); ft.setOnFinished(ev -> ui.setCache(false)); ft.setDelay(Duration.millis(delayMillis)); ft.play(); return ft; } public static Animation fadeOut(Node ui) { FadeTransition ft = new FadeTransition(Duration.millis(UI_ANIMATION_TIME_MSEC), ui); ft.setFromValue(ui.getOpacity()); ft.setToValue(0.0); ft.play(); return ft; } public static Animation fadeOutAndRemove(Pane parentPane, Node... nodes) { Animation animation = fadeOut(nodes[0]); animation.setOnFinished(actionEvent -> parentPane.getChildren().removeAll(nodes)); return animation; } public static Animation fadeOutAndRemove(Duration duration, Pane parentPane, Node... nodes) { nodes[0].setCache(true); FadeTransition ft = new FadeTransition(duration, nodes[0]); ft.setFromValue(nodes[0].getOpacity()); ft.setToValue(0.0); ft.setOnFinished(actionEvent -> parentPane.getChildren().removeAll(nodes)); ft.play(); return ft; } public static void blurOut(Node node) { GaussianBlur blur = new GaussianBlur(0.0); node.setEffect(blur); Timeline timeline = new Timeline(); KeyValue kv = new KeyValue(blur.radiusProperty(), 10.0); KeyFrame kf = new KeyFrame(Duration.millis(UI_ANIMATION_TIME_MSEC), kv); timeline.getKeyFrames().add(kf); timeline.play(); } public static void blurIn(Node node) { GaussianBlur blur = (GaussianBlur) node.getEffect(); Timeline timeline = new Timeline(); KeyValue kv = new KeyValue(blur.radiusProperty(), 0.0); KeyFrame kf = new KeyFrame(Duration.millis(UI_ANIMATION_TIME_MSEC), kv); timeline.getKeyFrames().add(kf); timeline.setOnFinished(actionEvent -> node.setEffect(null)); timeline.play(); } public static ScaleTransition zoomIn(Node node) { return zoomIn(node, 0); } public static ScaleTransition zoomIn(Node node, int delayMillis) { return scaleFromTo(node, 0.95, 1.0, delayMillis); } public static ScaleTransition explodeOut(Node node) { return scaleFromTo(node, 1.0, 1.05, 0); } private static ScaleTransition scaleFromTo(Node node, double from, double to, int delayMillis) { ScaleTransition scale = new ScaleTransition(Duration.millis(UI_ANIMATION_TIME_MSEC / 2), node); scale.setFromX(from); scale.setFromY(from); scale.setToX(to); scale.setToY(to); scale.setDelay(Duration.millis(delayMillis)); scale.play(); return scale; } /** * A useful helper for development purposes. Used as a switch for loading files from local disk, allowing live * editing whilst the app runs without rebuilds. */ public static URL getResource(Class<?> clazz, String name) { if (false) return unchecked(() -> new URL("file:///your/path/here/src/main/wallettemplate/" + name)); else return clazz.getResource(name); } public static void checkGuiThread() { checkState(Platform.isFxApplicationThread()); } private static Throwable findRootCause(Throwable throwable) { Throwable rootCause = Objects.requireNonNull(throwable); while (rootCause.getCause() != null && rootCause.getCause() != rootCause) { rootCause = rootCause.getCause(); } return rootCause; } }
7,305
36.854922
129
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/utils/BitcoinUIModel.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.walletfx.utils; import org.bitcoinj.base.Address; import org.bitcoinj.base.Coin; import org.bitcoinj.core.listeners.DownloadProgressTracker; import org.bitcoinj.wallet.Wallet; import javafx.application.Platform; import javafx.beans.property.ReadOnlyDoubleProperty; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleObjectProperty; import java.time.Instant; import java.util.Date; /** * A class that exposes relevant bitcoin stuff as JavaFX bindable properties. */ public class BitcoinUIModel { private SimpleObjectProperty<Address> address = new SimpleObjectProperty<>(); private SimpleObjectProperty<Coin> balance = new SimpleObjectProperty<>(Coin.ZERO); private SimpleDoubleProperty syncProgress = new SimpleDoubleProperty(-1); private ProgressBarUpdater syncProgressUpdater = new ProgressBarUpdater(); public BitcoinUIModel() { } public BitcoinUIModel(Wallet wallet) { setWallet(wallet); } public final void setWallet(Wallet wallet) { wallet.addChangeEventListener(Platform::runLater, w -> updateBalance(wallet)); wallet.addCurrentKeyChangeEventListener(Platform::runLater, () -> updateAddress(wallet)); updateBalance(wallet); updateAddress(wallet); } private void updateBalance(Wallet wallet) { balance.set(wallet.getBalance()); } private void updateAddress(Wallet wallet) { address.set(wallet.currentReceiveAddress()); } private class ProgressBarUpdater extends DownloadProgressTracker { @Override protected void progress(double pct, int blocksLeft, Instant time) { super.progress(pct, blocksLeft, time); Platform.runLater(() -> syncProgress.set(pct / 100.0)); } @Override protected void doneDownload() { super.doneDownload(); Platform.runLater(() -> syncProgress.set(1.0)); } } public DownloadProgressTracker getDownloadProgressTracker() { return syncProgressUpdater; } public ReadOnlyDoubleProperty syncProgressProperty() { return syncProgress; } public ReadOnlyObjectProperty<Address> addressProperty() { return address; } public ReadOnlyObjectProperty<Coin> balanceProperty() { return balance; } }
3,003
32.752809
97
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/utils/QRCodeImages.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.walletfx.utils; import com.google.zxing.BarcodeFormat; import com.google.zxing.Writer; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import javafx.scene.image.Image; import javafx.scene.image.WritableImage; import javafx.scene.paint.Color; /** * Utility for creating Images from QR Codes */ public class QRCodeImages { /** * Create an Image from a Bitcoin URI * @param uri Bitcoin URI * @param width width of image * @param height height of image * @return a javafx Image */ public static Image imageFromString(String uri, int width, int height) { return imageFromMatrix(matrixFromString(uri, width, height)); } /** * Create a BitMatrix from a Bitcoin URI * @param uri Bitcoin URI * @return A BitMatrix for the QRCode for the URI */ private static BitMatrix matrixFromString(String uri, int width, int height) { Writer qrWriter = new QRCodeWriter(); BitMatrix matrix; try { matrix = qrWriter.encode(uri, BarcodeFormat.QR_CODE, width, height); } catch (WriterException e) { throw new RuntimeException(e); } return matrix; } /** * Create a JavaFX Image from a BitMatrix * @param matrix the matrix * @return the QRCode Image */ private static Image imageFromMatrix(BitMatrix matrix) { int height = matrix.getHeight(); int width = matrix.getWidth(); WritableImage image = new WritableImage(width, height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { Color color = matrix.get(x,y) ? Color.BLACK : Color.WHITE; image.getPixelWriter().setColor(x, y, color); } } return image; } }
2,510
31.61039
82
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/utils/KeyDerivationTasks.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.walletfx.utils; import org.bitcoinj.crypto.AesKey; import org.bitcoinj.crypto.KeyCrypterScrypt; import com.google.common.util.concurrent.Uninterruptibles; import javafx.beans.property.ReadOnlyDoubleProperty; import javafx.concurrent.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.*; import java.time.Duration; import java.util.concurrent.TimeUnit; import static org.bitcoinj.walletfx.utils.GuiUtils.checkGuiThread; /** * Background tasks for pumping a progress meter and deriving an AES key using scrypt. */ public class KeyDerivationTasks { private static final Logger log = LoggerFactory.getLogger(KeyDerivationTasks.class); public final Task<AesKey> keyDerivationTask; public final ReadOnlyDoubleProperty progress; private final Task<Void> progressTask; private volatile int timeTakenMsec = -1; public KeyDerivationTasks(KeyCrypterScrypt scrypt, String password, @Nullable Duration targetTime) { keyDerivationTask = new Task<>() { @Override protected AesKey call() throws Exception { long start = System.currentTimeMillis(); try { log.info("Started key derivation"); AesKey result = scrypt.deriveKey(password); timeTakenMsec = (int) (System.currentTimeMillis() - start); log.info("Key derivation done in {}ms", timeTakenMsec); return result; } catch (Throwable e) { log.error("Exception during key derivation", e); throw e; } } }; // And the fake progress meter ... if the vals were calculated correctly progress bar should reach 100% // a brief moment after the keys were derived successfully. progressTask = new Task<>() { private AesKey aesKey; @Override protected Void call() throws Exception { if (targetTime != null) { long startTime = System.currentTimeMillis(); long curTime; long targetTimeMillis = targetTime.toMillis(); while ((curTime = System.currentTimeMillis()) < startTime + targetTimeMillis) { double progress = (curTime - startTime) / (double) targetTimeMillis; updateProgress(progress, 1.0); // 60fps would require 16msec sleep here. Uninterruptibles.sleepUninterruptibly(20, TimeUnit.MILLISECONDS); } // Wait for the encryption thread before switching back to main UI. updateProgress(1.0, 1.0); } else { updateProgress(-1, -1); } aesKey = keyDerivationTask.get(); return null; } @Override protected void succeeded() { checkGuiThread(); onFinish(aesKey, timeTakenMsec); } }; progress = progressTask.progressProperty(); } public void start() { new Thread(keyDerivationTask, "Key derivation").start(); new Thread(progressTask, "Progress ticker").start(); } protected void onFinish(AesKey aesKey, int timeTakenMsec) { } }
4,040
36.416667
111
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/utils/ThrottledRunLater.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.walletfx.utils; import javafx.application.Platform; import java.util.concurrent.atomic.AtomicBoolean; /** * A simple wrapper around {@link Platform#runLater(Runnable)} which will do nothing if the previous * invocation of runLater didn't execute on the JavaFX UI thread yet. In this way you can avoid flooding * the event loop if you have a background thread that for whatever reason wants to update the UI very * frequently. Without this class you could end up bloating up memory usage and causing the UI to stutter * if the UI thread couldn't keep up with your background worker. */ public class ThrottledRunLater implements Runnable { private final Runnable runnable; private final AtomicBoolean pending = new AtomicBoolean(); /** Created this way, the no-args runLater will execute this classes run method. */ public ThrottledRunLater() { this.runnable = null; } /** Created this way, the no-args runLater will execute the given runnable. */ public ThrottledRunLater(Runnable runnable) { this.runnable = runnable; } public void runLater(Runnable runnable) { if (!pending.getAndSet(true)) { Platform.runLater(() -> { pending.set(false); runnable.run(); }); } } public void runLater() { runLater(runnable != null ? runnable : this); } @Override public void run() { } }
2,076
33.04918
105
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/utils/AlertWindowController.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.walletfx.utils; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.stage.Stage; public class AlertWindowController { public Label messageLabel; public Label detailsLabel; public Button okButton; public Button cancelButton; public Button actionButton; /** Initialize this alert dialog for information about a crash. */ public void crashAlert(Stage stage, String crashMessage) { messageLabel.setText("Unfortunately, we screwed up and the app crashed. Sorry about that!"); detailsLabel.setText(crashMessage); cancelButton.setVisible(false); actionButton.setVisible(false); okButton.setOnAction(actionEvent -> stage.close()); } /** Initialize this alert for general information: OK button only, nothing happens on dismissal. */ public void informational(Stage stage, String message, String details) { messageLabel.setText(message); detailsLabel.setText(details); cancelButton.setVisible(false); actionButton.setVisible(false); okButton.setOnAction(actionEvent -> stage.close()); } }
1,777
35.285714
103
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/utils/WTUtils.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.walletfx.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Some generic utilities to make Java a bit less annoying. */ public class WTUtils { private static final Logger log = LoggerFactory.getLogger(WTUtils.class); public interface UncheckedRun<T> { public T run() throws Throwable; } public interface UncheckedRunnable { public void run() throws Throwable; } public static <T> T unchecked(UncheckedRun<T> run) { try { return run.run(); } catch (Throwable throwable) { throw new RuntimeException(throwable); } } public static void uncheck(UncheckedRunnable run) { try { run.run(); } catch (Throwable throwable) { throw new RuntimeException(throwable); } } public static void ignoreAndLog(UncheckedRunnable runnable) { try { runnable.run(); } catch (Throwable t) { log.error("Ignoring error", t); } } public static <T> T ignoredAndLogged(UncheckedRun<T> runnable) { try { return runnable.run(); } catch (Throwable t) { log.error("Ignoring error", t); return null; } } public static boolean didThrow(UncheckedRun run) { try { run.run(); return false; } catch (Throwable throwable) { return true; } } public static boolean didThrow(UncheckedRunnable run) { try { run.run(); return false; } catch (Throwable throwable) { return true; } } }
2,312
25.586207
77
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/utils/TextFieldValidator.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.walletfx.utils; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.scene.Scene; import javafx.scene.control.TextInputControl; import java.util.function.Predicate; public class TextFieldValidator { public final BooleanProperty valid = new SimpleBooleanProperty(false); public TextFieldValidator(TextInputControl control, Predicate<String> validator) { this.valid.set(validator.test(control.getText())); apply(control, valid.get()); control.textProperty().addListener((observableValue, prev, current) -> { boolean nowValid = validator.test(current); if (nowValid == valid.get()) return; valid.set(nowValid); }); valid.addListener(o -> apply(control, valid.get())); } private static void apply(TextInputControl textField, boolean nowValid) { if (nowValid) { textField.getStyleClass().remove("validation_error"); } else { textField.getStyleClass().add("validation_error"); } } public static void configureScene(Scene scene) { final String file = TextFieldValidator.class.getResource("text-validation.css").toString(); scene.getStylesheets().add(file); } }
1,922
35.283019
99
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/utils/easing/EasingMode.java
/* * The MIT License (MIT) * * Copyright (c) 2013, Christian Schudt * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.bitcoinj.walletfx.utils.easing; /** * Defines the three easing modes, ease-in, ease-out and ease-both. * * @author Christian Schudt */ public enum EasingMode { EASE_IN, EASE_OUT, EASE_BOTH }
1,371
36.081081
80
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/utils/easing/ElasticInterpolator.java
/* * The MIT License (MIT) * * Copyright (c) 2013, Christian Schudt * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.bitcoinj.walletfx.utils.easing; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleDoubleProperty; /** * <p>This interpolator simulates an elastic behavior.</p> * <p>The following curve illustrates the interpolation.</p> * {@code * <svg style="width:300px;" xmlns="http://www.w3.org/2000/svg" viewBox="-2 -40 124 140"> * <line style="stroke: rgb(187, 187, 187); stroke-width: 1px;" y2="60" y1="0" x2="0" x1="0"/> * <text style="font-size: 12px; fill: rgb(187, 187, 187);" y="6" x="2">x</text> * <line style="stroke: rgb(187, 187, 187); stroke-width: 1px;" y2="60" y1="60" x2="120" x1="0"/> * <text style="font-size: 12px; fill: rgb(187, 187, 187);" y="57" x="115">t</text> * <path style="fill: rgba(255, 255, 255, 0);stroke: black;stroke-width: 2px;" * d="M0,60 L1.2,54.8 2.4,47.7 3.6,39.4 4.8,30.4 6.0,21.2 7.2,12.2 8.4,3.9 9.6,-3.6 10.8,-9.9 12.0,-15.0 13.2,-18.7 14.4,-21.1 15.6,-22.3 16.8,-22.2 18.0,-21.2 19.2,-19.4 20.4,-16.9 21.6,-13.9 22.8,-10.8 24.0,-7.5 25.2,-4.3 26.4,-1.4 27.6,1.3 28.8,3.5 30.0,5.3 31.2,6.6 32.4,7.5 33.6,7.9 34.8,7.9 36.0,7.5 37.2,6.8 38.4,6.0 39.6,4.9 40.8,3.8 42.0,2.7 43.2,1.5 44.4,0.5 45.6,-0.5 46.8,-1.2 48.0,-1.9 49.2,-2.3 50.4,-2.6 51.6,-2.8 52.8,-2.8 54.0,-2.7 55.2,-2.4 56.4,-2.1 57.6,-1.7 58.8,-1.3 60.0,-0.9 61.2,-0.5 62.4,-0.2 63.6,0.2 64.8,0.4 66.0,0.7 67.2,0.8 68.4,0.9 69.6,1.0 70.8,1.0 72.0,0.9 73.2,0.9 74.4,0.7 75.6,0.6 76.8,0.5 78.0,0.3 79.2,0.2 80.4,0.1 81.6,-0.1 82.8,-0.2 84.0,-0.2 85.2,-0.3 86.4,-0.3 87.6,-0.3 88.8,-0.3 90.0,-0.3 91.2,-0.3 92.4,-0.3 93.6,-0.2 94.8,-0.2 96.0,-0.1 97.2,-0.1 98.4,-0.0 99.6,0.0 100.8,0.1 102.0,0.1 103.2,0.1 104.4,0.1 105.6,0.1 106.8,0.1 108.0,0.1 109.2,0.1 110.4,0.1 111.6,0.1 112.8,0.1 114.0,0.0 115.2,0.0 116.4,0.0 117.6,-0.0 118.8,-0.0 120.0,0.0"/> * </svg>} * <p>The math in this class is taken from * <a href="http://www.robertpenner.com/easing/">http://www.robertpenner.com/easing/</a>.</p> * * @author Christian Schudt */ public class ElasticInterpolator extends EasingInterpolator { /** * The amplitude. */ private DoubleProperty amplitude = new SimpleDoubleProperty(this, "amplitude", 1); /** * The number of oscillations. */ private DoubleProperty oscillations = new SimpleDoubleProperty(this, "oscillations", 3); /** * Default constructor. Initializes the interpolator with ease out mode. */ public ElasticInterpolator() { this(EasingMode.EASE_OUT); } /** * Constructs the interpolator with a specific easing mode. * * @param easingMode The easing mode. */ public ElasticInterpolator(EasingMode easingMode) { super(easingMode); } /** * Sets the easing mode. * * @param easingMode The easing mode. * @see #easingModeProperty() */ public ElasticInterpolator(EasingMode easingMode, double amplitude, double oscillations) { super(easingMode); this.amplitude.set(amplitude); this.oscillations.set(oscillations); } /** * The oscillations property. Defines number of oscillations. * * @return The property. * @see #getOscillations() * @see #setOscillations(double) */ public DoubleProperty oscillationsProperty() { return oscillations; } /** * The amplitude. The minimum value is 1. If this value is &lt; 1 it will be set to 1 during animation. * * @return The property. * @see #getAmplitude() * @see #setAmplitude(double) */ public DoubleProperty amplitudeProperty() { return amplitude; } /** * Gets the amplitude. * * @return The amplitude. * @see #amplitudeProperty() */ public double getAmplitude() { return amplitude.get(); } /** * Sets the amplitude. * * @param amplitude The amplitude. * @see #amplitudeProperty() */ public void setAmplitude(final double amplitude) { this.amplitude.set(amplitude); } /** * Gets the number of oscillations. * * @return The oscillations. * @see #oscillationsProperty() */ public double getOscillations() { return oscillations.get(); } /** * Sets the number of oscillations. * * @param oscillations The oscillations. * @see #oscillationsProperty() */ public void setOscillations(final double oscillations) { this.oscillations.set(oscillations); } @Override protected double baseCurve(double v) { if (v == 0) { return 0; } if (v == 1) { return 1; } double p = 1.0 / oscillations.get(); double a = amplitude.get(); double s; if (a < Math.abs(1)) { a = 1; s = p / 4; } else { s = p / (2 * Math.PI) * Math.asin(1 / a); } return -(a * Math.pow(2, 10 * (v -= 1)) * Math.sin((v - s) * (2 * Math.PI) / p)); } }
6,160
35.455621
987
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/utils/easing/EasingInterpolator.java
/* * The MIT License (MIT) * * Copyright (c) 2013, Christian Schudt * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.bitcoinj.walletfx.utils.easing; import javafx.animation.Interpolator; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; /** * The abstract base class for all easing interpolators. * * @author Christian Schudt */ public abstract class EasingInterpolator extends Interpolator { /** * The easing mode. */ private ObjectProperty<EasingMode> easingMode = new SimpleObjectProperty<>(EasingMode.EASE_OUT); /** * Constructs the interpolator with a specific easing mode. * * @param easingMode The easing mode. */ public EasingInterpolator(EasingMode easingMode) { this.easingMode.set(easingMode); } /** * The easing mode property. * * @return The property. * @see #getEasingMode() * @see #setEasingMode(EasingMode) */ public ObjectProperty<EasingMode> easingModeProperty() { return easingMode; } /** * Gets the easing mode. * * @return The easing mode. * @see #easingModeProperty() */ public EasingMode getEasingMode() { return easingMode.get(); } /** * Sets the easing mode. * * @param easingMode The easing mode. * @see #easingModeProperty() */ public void setEasingMode(EasingMode easingMode) { this.easingMode.set(easingMode); } /** * Defines the base curve for the interpolator. * The base curve is then transformed into an easing-in, easing-out easing-both curve. * * @param v The normalized value/time/progress of the interpolation (between 0 and 1). * @return The resulting value of the function, should return a value between 0 and 1. * @see Interpolator#curve(double) */ protected abstract double baseCurve(final double v); /** * Curves the function depending on the easing mode. * * @param v The normalized value (between 0 and 1). * @return The resulting value of the function. */ @Override protected final double curve(final double v) { switch (easingMode.get()) { case EASE_IN: return baseCurve(v); case EASE_OUT: return 1 - baseCurve(1 - v); case EASE_BOTH: if (v <= 0.5) { return baseCurve(2 * v) / 2; } else { return (2 - baseCurve(2 * (1 - v))) / 2; } } return baseCurve(v); } }
3,673
30.401709
100
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/controls/NotificationBarPane.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.walletfx.controls; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ObservableDoubleValue; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.util.Duration; import org.bitcoinj.walletfx.utils.GuiUtils; import org.bitcoinj.walletfx.utils.easing.EasingMode; import org.bitcoinj.walletfx.utils.easing.ElasticInterpolator; import javax.annotation.Nullable; /** * Wraps the given Node in a BorderPane and allows a thin bar to slide in from the bottom or top, squeezing the content * node. The API allows different "items" to be added/removed and they will be displayed one at a time, fading between * them when the topmost is removed. Each item is meant to be used for e.g. a background task and can contain a button * and/or a progress bar. */ public class NotificationBarPane extends BorderPane { public static final Duration ANIM_IN_DURATION = GuiUtils.UI_ANIMATION_TIME.multiply(2); public static final Duration ANIM_OUT_DURATION = GuiUtils.UI_ANIMATION_TIME; private HBox bar; private Label label; private double barHeight; private ProgressBar progressBar; public class Item { public final SimpleStringProperty label; @Nullable public final ObservableDoubleValue progress; public Item(String label, @Nullable ObservableDoubleValue progress) { this.label = new SimpleStringProperty(label); this.progress = progress; } public void cancel() { items.remove(this); } } public final ObservableList<Item> items; public NotificationBarPane(Node content) { super(content); progressBar = new ProgressBar(); label = new Label("infobar!"); bar = new HBox(label); bar.setMinHeight(0.0); bar.getStyleClass().add("info-bar"); bar.setFillHeight(true); setBottom(bar); // Figure out the height of the bar based on the CSS. Must wait until after we've been added to the parent node. sceneProperty().addListener(o -> { if (getParent() == null) return; getParent().applyCss(); getParent().layout(); barHeight = bar.getHeight(); bar.setPrefHeight(0.0); }); items = FXCollections.observableArrayList(); items.addListener((ListChangeListener<? super Item>) change -> { config(); showOrHide(); }); } private void config() { if (items.isEmpty()) return; Item item = items.get(0); bar.getChildren().clear(); label.textProperty().bind(item.label); label.setMaxWidth(Double.MAX_VALUE); HBox.setHgrow(label, Priority.ALWAYS); bar.getChildren().add(label); if (item.progress != null) { progressBar.setMinWidth(200); progressBar.progressProperty().bind(item.progress); bar.getChildren().add(progressBar); } } private void showOrHide() { if (items.isEmpty()) animateOut(); else animateIn(); } public boolean isShowing() { return bar.getPrefHeight() > 0; } private void animateIn() { animate(barHeight); } private void animateOut() { animate(0.0); } private Timeline timeline; protected void animate(Number target) { if (timeline != null) { timeline.stop(); timeline = null; } Duration duration; Interpolator interpolator; if (target.intValue() > 0) { interpolator = new ElasticInterpolator(EasingMode.EASE_OUT, 1, 2); duration = ANIM_IN_DURATION; } else { interpolator = Interpolator.EASE_OUT; duration = ANIM_OUT_DURATION; } KeyFrame kf = new KeyFrame(duration, new KeyValue(bar.prefHeightProperty(), target, interpolator)); timeline = new Timeline(kf); timeline.setOnFinished(x -> timeline = null); timeline.play(); } public Item pushItem(String string, @Nullable ObservableDoubleValue progress) { Item i = new Item(string, progress); items.add(i); return i; } }
5,300
32.764331
120
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/controls/BitcoinAddressValidator.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.walletfx.controls; import org.bitcoinj.base.exceptions.AddressFormatException; import javafx.scene.Node; import javafx.scene.control.TextField; import org.bitcoinj.base.AddressParser; import org.bitcoinj.walletfx.utils.TextFieldValidator; /** * Given a text field, some network params and optionally some nodes, will make the text field an angry red colour * if the address is invalid for those params, and enable/disable the nodes. */ public class BitcoinAddressValidator { private final AddressParser.Strict parser; private Node[] nodes; public BitcoinAddressValidator(AddressParser.Strict parser, TextField field, Node... nodes) { this.parser = parser; this.nodes = nodes; // Handle the red highlighting, but don't highlight in red just when the field is empty because that makes // the example/prompt address hard to read. new TextFieldValidator(field, text -> text.isEmpty() || testAddr(text)); // However we do want the buttons to be disabled when empty so we apply a different test there. field.textProperty().addListener((observableValue, prev, current) -> toggleButtons(current)); toggleButtons(field.getText()); } private void toggleButtons(String current) { boolean valid = testAddr(current); for (Node n : nodes) n.setDisable(!valid); } private boolean testAddr(String text) { try { parser.parseAddress(text); return true; } catch (AddressFormatException e) { return false; } } }
2,210
35.245902
114
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/org/bitcoinj/walletfx/controls/ClickableBitcoinAddress.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.walletfx.controls; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import javafx.beans.binding.StringExpression; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; import javafx.scene.control.Tooltip; import javafx.scene.effect.DropShadow; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.Clipboard; import javafx.scene.input.ClipboardContent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import org.bitcoinj.base.Address; import org.bitcoinj.uri.BitcoinURI; import org.bitcoinj.walletfx.overlay.OverlayController; import org.bitcoinj.walletfx.overlay.OverlayableStackPaneController; import org.bitcoinj.walletfx.utils.GuiUtils; import org.bitcoinj.walletfx.utils.QRCodeImages; import de.jensd.fx.fontawesome.AwesomeDude; import de.jensd.fx.fontawesome.AwesomeIcon; import static javafx.beans.binding.Bindings.convert; /** * A custom control that implements a clickable, copyable Bitcoin address. Clicking it opens a local wallet app. The * address looks like a blue hyperlink. Next to it there are two icons, one that copies to the clipboard and another * that shows a QRcode. */ public class ClickableBitcoinAddress extends AnchorPane implements OverlayController<ClickableBitcoinAddress> { @FXML protected Label addressLabel; @FXML protected ContextMenu addressMenu; @FXML protected Label copyWidget; @FXML protected Label qrCode; protected SimpleObjectProperty<Address> address = new SimpleObjectProperty<>(); private final StringExpression addressStr; private OverlayableStackPaneController rootController; private String appName = "app-name"; @Override public void initOverlay(OverlayableStackPaneController overlayableStackPaneController, OverlayableStackPaneController.OverlayUI<? extends OverlayController<ClickableBitcoinAddress>> ui) { rootController = overlayableStackPaneController; } /** * @param theAppName The application name to use in Bitcoin URIs */ public void setAppName(String theAppName) { appName = theAppName; } public ClickableBitcoinAddress() { try { FXMLLoader loader = new FXMLLoader(getClass().getResource("bitcoin_address.fxml")); loader.setRoot(this); loader.setController(this); // The following line is supposed to help Scene Builder, although it doesn't seem to be needed for me. loader.setClassLoader(getClass().getClassLoader()); loader.load(); AwesomeDude.setIcon(copyWidget, AwesomeIcon.COPY); Tooltip.install(copyWidget, new Tooltip("Copy address to clipboard")); AwesomeDude.setIcon(qrCode, AwesomeIcon.QRCODE); Tooltip.install(qrCode, new Tooltip("Show a barcode scannable with a mobile phone for this address")); addressStr = convert(address); addressLabel.textProperty().bind(addressStr); } catch (IOException e) { throw new RuntimeException(e); } } public String uri() { return BitcoinURI.convertToBitcoinURI(address.get(), null, appName, null); } public Address getAddress() { return address.get(); } public void setAddress(Address address) { this.address.set(address); } public ObjectProperty<Address> addressProperty() { return address; } @FXML protected void copyAddress(ActionEvent event) { // User clicked icon or menu item. Clipboard clipboard = Clipboard.getSystemClipboard(); ClipboardContent content = new ClipboardContent(); content.putString(addressStr.get()); content.putHtml(String.format("<a href='%s'>%s</a>", uri(), addressStr.get())); clipboard.setContent(content); } @FXML protected void requestMoney(MouseEvent event) { if (event.getButton() == MouseButton.SECONDARY || (event.getButton() == MouseButton.PRIMARY && event.isMetaDown())) { // User right clicked or the Mac equivalent. Show the context menu. addressMenu.show(addressLabel, event.getScreenX(), event.getScreenY()); } else { // User left clicked. try { Desktop.getDesktop().browse(URI.create(uri())); } catch (IOException e) { GuiUtils.informationalAlert("Opening wallet app failed", "Perhaps you don't have one installed?"); } } } @FXML protected void copyWidgetClicked(MouseEvent event) { copyAddress(null); } @FXML protected void showQRCode(MouseEvent event) { Image qrImage = QRCodeImages.imageFromString(uri(), 320, 240); ImageView view = new ImageView(qrImage); view.setEffect(new DropShadow()); // Embed the image in a pane to ensure the drop-shadow interacts with the fade nicely, otherwise it looks weird. // Then fix the width/height to stop it expanding to fill the parent, which would result in the image being // non-centered on the screen. Finally fade/blur it in. Pane pane = new Pane(view); pane.setMaxSize(qrImage.getWidth(), qrImage.getHeight()); final OverlayableStackPaneController.OverlayUI<ClickableBitcoinAddress> overlay = rootController.overlayUI(pane, this); view.setOnMouseClicked(event1 -> overlay.done()); } }
6,365
36.447059
191
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/wallettemplate/Main.java
/* * Copyright by the original author or authors. * * 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. */ package wallettemplate; import javafx.application.Application; import javafx.stage.Stage; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.ScriptType; import org.bitcoinj.walletfx.application.AppDelegate; /** * Proxy JavaFX {@link Application} that delegates all functionality * to {@link WalletTemplate} */ public class Main extends Application { private static final BitcoinNetwork network = BitcoinNetwork.TESTNET; private static final ScriptType PREFERRED_OUTPUT_SCRIPT_TYPE = ScriptType.P2WPKH; private static final String APP_NAME = "WalletTemplate"; private final AppDelegate delegate; public static void main(String[] args) { launch(args); } public Main() { delegate = new WalletTemplate(APP_NAME, network, PREFERRED_OUTPUT_SCRIPT_TYPE); } @Override public void init() throws Exception { delegate.init(this); } @Override public void start(Stage primaryStage) throws Exception { delegate.start(primaryStage); } @Override public void stop() throws Exception { delegate.stop(); } }
1,737
28.457627
87
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/wallettemplate/WalletSettingsController.java
/* * Copyright by the original author or authors. * * 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. */ package wallettemplate; import org.bitcoinj.base.internal.InternalUtils; import org.bitcoinj.crypto.AesKey; import org.bitcoinj.crypto.MnemonicCode; import org.bitcoinj.wallet.DeterministicSeed; import com.google.common.util.concurrent.Service; import javafx.application.Platform; import javafx.beans.binding.BooleanBinding; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.DatePicker; import javafx.scene.control.TextArea; import org.bitcoinj.walletfx.application.WalletApplication; import org.bitcoinj.walletfx.overlay.OverlayController; import org.bitcoinj.walletfx.overlay.OverlayableStackPaneController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.bitcoinj.walletfx.utils.TextFieldValidator; import javax.annotation.Nullable; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.time.ZoneOffset; import java.util.List; import java.util.Objects; import static javafx.beans.binding.Bindings.*; import static org.bitcoinj.walletfx.utils.GuiUtils.checkGuiThread; import static org.bitcoinj.walletfx.utils.GuiUtils.informationalAlert; import static org.bitcoinj.walletfx.utils.WTUtils.didThrow; import static org.bitcoinj.walletfx.utils.WTUtils.unchecked; public class WalletSettingsController implements OverlayController<WalletSettingsController> { private static final Logger log = LoggerFactory.getLogger(WalletSettingsController.class); @FXML Button passwordButton; @FXML DatePicker datePicker; @FXML TextArea wordsArea; @FXML Button restoreButton; private WalletApplication app; private OverlayableStackPaneController rootController; private OverlayableStackPaneController.OverlayUI<? extends OverlayController<WalletSettingsController>> overlayUI; private AesKey aesKey; @Override public void initOverlay(OverlayableStackPaneController overlayableStackPaneController, OverlayableStackPaneController.OverlayUI<? extends OverlayController<WalletSettingsController>> ui) { rootController = overlayableStackPaneController; overlayUI = ui; } // Note: NOT called by FXMLLoader! public void initialize(@Nullable AesKey aesKey) { app = WalletApplication.instance(); DeterministicSeed seed = app.walletAppKit().wallet().getKeyChainSeed(); if (aesKey == null) { if (seed.isEncrypted()) { log.info("Wallet is encrypted, requesting password first."); // Delay execution of this until after we've finished initialising this screen. Platform.runLater(this::askForPasswordAndRetry); return; } } else { this.aesKey = aesKey; seed = seed.decrypt(Objects.requireNonNull(app.walletAppKit().wallet().getKeyCrypter()), "", aesKey); // Now we can display the wallet seed as appropriate. passwordButton.setText("Remove password"); } // Set the date picker to show the birthday of this wallet. Instant creationTime = seed.creationTime().get(); LocalDate origDate = creationTime.atZone(ZoneId.systemDefault()).toLocalDate(); datePicker.setValue(origDate); // Set the mnemonic seed words. final List<String> mnemonicCode = seed.getMnemonicCode(); Objects.requireNonNull(mnemonicCode); // Already checked for encryption. String origWords = InternalUtils.SPACE_JOINER.join(mnemonicCode); wordsArea.setText(origWords); // Validate words as they are being typed. MnemonicCode codec = unchecked(MnemonicCode::new); TextFieldValidator validator = new TextFieldValidator(wordsArea, text -> !didThrow(() -> codec.check(InternalUtils.splitter(" ").splitToList(text))) ); // Clear the date picker if the user starts editing the words, if it contained the current wallets date. // This forces them to set the birthday field when restoring. wordsArea.textProperty().addListener(o -> { if (origDate.equals(datePicker.getValue())) datePicker.setValue(null); }); BooleanBinding datePickerIsInvalid = or( datePicker.valueProperty().isNull(), createBooleanBinding(() -> datePicker.getValue().isAfter(LocalDate.now()) , /* depends on */ datePicker.valueProperty()) ); // Don't let the user click restore if the words area contains the current wallet words, or are an invalid set, // or if the date field isn't set, or if it's in the future. restoreButton.disableProperty().bind( or( or( not(validator.valid), equal(origWords, wordsArea.textProperty()) ), datePickerIsInvalid ) ); // Highlight the date picker in red if it's empty or in the future, so the user knows why restore is disabled. datePickerIsInvalid.addListener((dp, old, cur) -> { if (cur) { datePicker.getStyleClass().add("validation_error"); } else { datePicker.getStyleClass().remove("validation_error"); } }); } private void askForPasswordAndRetry() { OverlayableStackPaneController.OverlayUI<WalletPasswordController> pwd = rootController.overlayUI("wallet_password.fxml"); pwd.controller.aesKeyProperty().addListener((observable, old, cur) -> { // We only get here if the user found the right password. If they don't or they cancel, we end up back on // the main UI screen. checkGuiThread(); OverlayableStackPaneController.OverlayUI<WalletSettingsController> screen = rootController.overlayUI("wallet_settings.fxml"); screen.controller.initialize(cur); }); } public void closeClicked(ActionEvent event) { overlayUI.done(); } public void restoreClicked(ActionEvent event) { // Don't allow a restore unless this wallet is presently empty. We don't want to end up with two wallets, too // much complexity, even though WalletAppKit will keep the current one as a backup file in case of disaster. if (app.walletAppKit().wallet().getBalance().value > 0) { informationalAlert("Wallet is not empty", "You must empty this wallet out before attempting to restore an older one, as mixing wallets " + "together can lead to invalidated backups."); return; } if (aesKey != null) { // This is weak. We should encrypt the new seed here. informationalAlert("Wallet is encrypted", "After restore, the wallet will no longer be encrypted and you must set a new password."); } log.info("Attempting wallet restore using seed '{}' from date {}", wordsArea.getText(), datePicker.getValue()); informationalAlert("Wallet restore in progress", "Your wallet will now be resynced from the Bitcoin network. This can take a long time for old wallets."); overlayUI.done(); app.mainWindowController().restoreFromSeedAnimation(); Instant birthday = datePicker.getValue().atStartOfDay().toInstant(ZoneOffset.UTC); DeterministicSeed seed = DeterministicSeed.ofMnemonic(InternalUtils.splitter(" ").splitToList(wordsArea.getText()),"", birthday); // Shut down bitcoinj and restart it with the new seed. app.walletAppKit().addListener(new Service.Listener() { @Override public void terminated(Service.State from) { app.setupWalletKit(seed); app.walletAppKit().startAsync(); } }, Platform::runLater); app.walletAppKit().stopAsync(); } public void passwordButtonClicked(ActionEvent event) { if (aesKey == null) { rootController.overlayUI("wallet_set_password.fxml"); } else { app.walletAppKit().wallet().decrypt(aesKey); informationalAlert("Wallet decrypted", "A password will no longer be required to send money or edit settings."); passwordButton.setText("Set password"); aesKey = null; } } }
9,107
43
192
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/wallettemplate/MainController.java
/* * Copyright by the original author or authors. * * 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. */ package wallettemplate; import javafx.beans.binding.Binding; import javafx.beans.binding.Bindings; import javafx.beans.value.ObservableValue; import javafx.scene.Scene; import javafx.scene.input.KeyCombination; import javafx.scene.layout.Pane; import org.bitcoinj.core.listeners.DownloadProgressTracker; import org.bitcoinj.base.Coin; import org.bitcoinj.base.utils.MonetaryFormat; import javafx.animation.FadeTransition; import javafx.animation.ParallelTransition; import javafx.animation.TranslateTransition; import javafx.event.ActionEvent; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.util.Duration; import org.bitcoinj.walletfx.application.MainWindowController; import org.bitcoinj.walletfx.application.WalletApplication; import org.bitcoinj.walletfx.utils.GuiUtils; import org.bitcoinj.walletfx.utils.TextFieldValidator; import org.bitcoinj.walletfx.controls.ClickableBitcoinAddress; import org.bitcoinj.walletfx.controls.NotificationBarPane; import org.bitcoinj.walletfx.utils.BitcoinUIModel; import org.bitcoinj.walletfx.utils.easing.EasingMode; import org.bitcoinj.walletfx.utils.easing.ElasticInterpolator; /** * Gets created auto-magically by FXMLLoader via reflection. The widget fields are set to the GUI controls they're named * after. This class handles all the updates and event handling for the main UI. */ public class MainController extends MainWindowController { public HBox controlsBox; public Label balance; public Button sendMoneyOutBtn; public ClickableBitcoinAddress addressControl; private final BitcoinUIModel model = new BitcoinUIModel(); private NotificationBarPane.Item syncItem; private static final MonetaryFormat MONETARY_FORMAT = MonetaryFormat.BTC.noCode(); private WalletApplication app; private NotificationBarPane notificationBar; // Called by FXMLLoader. public void initialize() { app = WalletApplication.instance(); scene = new Scene(uiStack); TextFieldValidator.configureScene(scene); // Special case of initOverlay that passes null as the 2nd parameter because ClickableBitcoinAddress is loaded by FXML // TODO: Extract QRCode Pane to separate reusable class that is a more standard OverlayController instance addressControl.initOverlay(this, null); addressControl.setAppName(app.applicationName()); addressControl.setOpacity(0.0); } @Override public void controllerStart(Pane mainUI, String cssResourceName) { this.mainUI = mainUI; // Configure the window with a StackPane so we can overlay things on top of the main UI, and a // NotificationBarPane so we can slide messages and progress bars in from the bottom. Note that // ordering of the construction and connection matters here, otherwise we get (harmless) CSS error // spew to the logs. notificationBar = new NotificationBarPane(mainUI); // Add CSS that we need. cssResourceName will be loaded from the same package as this class. scene.getStylesheets().add(getClass().getResource(cssResourceName).toString()); uiStack.getChildren().add(notificationBar); scene.getAccelerators().put(KeyCombination.valueOf("Shortcut+F"), () -> app.walletAppKit().peerGroup().getDownloadPeer().close()); } @Override public void onBitcoinSetup() { model.setWallet(app.walletAppKit().wallet()); addressControl.addressProperty().bind(model.addressProperty()); balance.textProperty().bind(createBalanceStringBinding(model.balanceProperty())); // Don't let the user click send money when the wallet is empty. sendMoneyOutBtn.disableProperty().bind(model.balanceProperty().isEqualTo(Coin.ZERO)); showBitcoinSyncMessage(); model.syncProgressProperty().addListener(x -> { if (model.syncProgressProperty().get() >= 1.0) { readyToGoAnimation(); if (syncItem != null) { syncItem.cancel(); syncItem = null; } } else if (syncItem == null) { showBitcoinSyncMessage(); } }); } private static String formatCoin(Coin coin) { return MONETARY_FORMAT.format(coin).toString(); } private static Binding<String> createBalanceStringBinding(ObservableValue<Coin> coinProperty) { return Bindings.createStringBinding(() -> formatCoin(coinProperty.getValue()), coinProperty); } private void showBitcoinSyncMessage() { syncItem = notificationBar.pushItem("Synchronising with the Bitcoin network", model.syncProgressProperty()); } public void sendMoneyOut(ActionEvent event) { // Hide this UI and show the send money UI. This UI won't be clickable until the user dismisses send_money. overlayUI("send_money.fxml"); } public void settingsClicked(ActionEvent event) { OverlayUI<WalletSettingsController> screen = overlayUI("wallet_settings.fxml"); screen.controller.initialize(null); } public void primaryClicked(ActionEvent event) { GuiUtils.informationalAlert("Unused button #1", "You can hook this up in your app"); } public void secondaryClicked(ActionEvent event) { GuiUtils.informationalAlert("Unused button #2", "You can hook this up in your app"); } @Override public void restoreFromSeedAnimation() { // Buttons slide out ... TranslateTransition leave = new TranslateTransition(Duration.millis(1200), controlsBox); leave.setByY(80.0); leave.play(); } public void readyToGoAnimation() { // Buttons slide in and clickable address appears simultaneously. TranslateTransition arrive = new TranslateTransition(Duration.millis(1200), controlsBox); arrive.setInterpolator(new ElasticInterpolator(EasingMode.EASE_OUT, 1, 2)); arrive.setToY(0.0); FadeTransition reveal = new FadeTransition(Duration.millis(1200), addressControl); reveal.setToValue(1.0); ParallelTransition group = new ParallelTransition(arrive, reveal); group.setDelay(NotificationBarPane.ANIM_OUT_DURATION); group.setCycleCount(1); group.play(); } @Override public DownloadProgressTracker progressBarUpdater() { return model.getDownloadProgressTracker(); } }
7,085
41.178571
138
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/wallettemplate/WalletTemplate.java
/* * Copyright by the original author or authors. * * 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. */ package wallettemplate; import javafx.fxml.FXMLLoader; import javafx.scene.layout.Pane; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.ScriptType; import org.bitcoinj.walletfx.application.WalletApplication; import java.io.IOException; import java.net.URL; /** * Template implementation of WalletApplication */ public class WalletTemplate extends WalletApplication { public WalletTemplate(String applicationName, BitcoinNetwork network, ScriptType preferredOutputScriptType) { super(applicationName, network, preferredOutputScriptType); } @Override protected MainController loadController() throws IOException { // Load the GUI. The MainController class will be automagically created and wired up. URL location = getClass().getResource("main.fxml"); FXMLLoader loader = new FXMLLoader(location); Pane mainUI = loader.load(); MainController controller = loader.getController(); controller.controllerStart(mainUI, "wallet.css"); return controller; } }
1,673
33.163265
113
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/wallettemplate/WalletSetPasswordController.java
/* * Copyright by the original author or authors. * * 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. */ package wallettemplate; import javafx.event.*; import javafx.fxml.*; import javafx.scene.control.*; import javafx.scene.layout.*; import org.bitcoinj.crypto.AesKey; import org.bitcoinj.crypto.*; import org.bitcoinj.wallet.*; import org.bitcoinj.walletfx.application.WalletApplication; import org.bitcoinj.walletfx.overlay.OverlayController; import org.bitcoinj.walletfx.overlay.OverlayableStackPaneController; import org.slf4j.*; import com.google.protobuf.ByteString; import java.time.Duration; import java.util.concurrent.*; import org.bitcoinj.walletfx.utils.KeyDerivationTasks; import static org.bitcoinj.walletfx.utils.GuiUtils.*; public class WalletSetPasswordController implements OverlayController<WalletSetPasswordController> { private static final Logger log = LoggerFactory.getLogger(WalletSetPasswordController.class); public PasswordField pass1, pass2; public ProgressIndicator progressMeter; public GridPane widgetGrid; public Button closeButton; public Label explanationLabel; private WalletApplication app; private OverlayableStackPaneController rootController; private OverlayableStackPaneController.OverlayUI<? extends OverlayController<WalletSetPasswordController>> overlayUI; // These params were determined empirically on a top-range (as of 2014) MacBook Pro with native scrypt support, // using the scryptenc command line tool from the original scrypt distribution, given a memory limit of 40mb. public static final Protos.ScryptParameters SCRYPT_PARAMETERS = Protos.ScryptParameters.newBuilder() .setP(6) .setR(8) .setN(32768) .setSalt(ByteString.copyFrom(KeyCrypterScrypt.randomSalt())) .build(); @Override public void initOverlay(OverlayableStackPaneController overlayableStackPaneController, OverlayableStackPaneController.OverlayUI<? extends OverlayController<WalletSetPasswordController>> ui) { rootController = overlayableStackPaneController; overlayUI = ui; } public void initialize() { app = WalletApplication.instance(); progressMeter.setOpacity(0); } private static Duration estimatedKeyDerivationTime = null; /** * Initialize the {@code estimatedKeyDerivationTime} static field if not already initialized * <p> * This is run in the background after startup. If we haven't recorded it before, do a key derivation to see * how long it takes. This helps us produce better progress feedback, as on Windows we don't currently have a * native Scrypt impl and the Java version is ~3 times slower, plus it depends a lot on CPU speed. */ public static void initEstimatedKeyDerivationTime() { if (estimatedKeyDerivationTime == null) { CompletableFuture .supplyAsync(WalletSetPasswordController::estimateKeyDerivationTime) .thenAccept(duration -> estimatedKeyDerivationTime = duration); } } /** * Estimate key derivation time with no side effects * @return duration in milliseconds */ private static Duration estimateKeyDerivationTime() { log.info("Doing background test key derivation"); KeyCrypterScrypt scrypt = new KeyCrypterScrypt(SCRYPT_PARAMETERS); long start = System.currentTimeMillis(); scrypt.deriveKey("test password"); long msec = System.currentTimeMillis() - start; log.info("Background test key derivation took {}msec", msec); return Duration.ofMillis(msec); } @FXML public void setPasswordClicked(ActionEvent event) { if (!pass1.getText().equals(pass2.getText())) { informationalAlert("Passwords do not match", "Try re-typing your chosen passwords."); return; } String password = pass1.getText(); // This is kind of arbitrary and we could do much more to help people pick strong passwords. if (password.length() < 4) { informationalAlert("Password too short", "You need to pick a password at least five characters or longer."); return; } fadeIn(progressMeter); fadeOut(widgetGrid); fadeOut(explanationLabel); fadeOut(closeButton); KeyCrypterScrypt scrypt = new KeyCrypterScrypt(SCRYPT_PARAMETERS); // Deriving the actual key runs on a background thread. 500msec is empirical on my laptop (actual val is more like 333 but we give padding time). KeyDerivationTasks tasks = new KeyDerivationTasks(scrypt, password, estimatedKeyDerivationTime) { @Override protected final void onFinish(AesKey aesKey, int timeTakenMsec) { // Write the target time to the wallet so we can make the progress bar work when entering the password. WalletPasswordController.setTargetTime(Duration.ofMillis(timeTakenMsec)); // The actual encryption part doesn't take very long as most private keys are derived on demand. log.info("Key derived, now encrypting"); app.walletAppKit().wallet().encrypt(scrypt, aesKey); log.info("Encryption done"); informationalAlert("Wallet encrypted", "You can remove the password at any time from the settings screen."); overlayUI.done(); } }; progressMeter.progressProperty().bind(tasks.progress); tasks.start(); } public void closeClicked(ActionEvent event) { overlayUI.done(); } }
6,204
41.5
195
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/wallettemplate/WalletPasswordController.java
/* * Copyright by the original author or authors. * * 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. */ package wallettemplate; import javafx.application.Platform; import org.bitcoinj.crypto.AesKey; import org.bitcoinj.crypto.KeyCrypterScrypt; import com.google.protobuf.ByteString; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.ProgressIndicator; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import org.bitcoinj.walletfx.application.WalletApplication; import org.bitcoinj.walletfx.overlay.OverlayController; import org.bitcoinj.walletfx.overlay.OverlayableStackPaneController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.bitcoinj.walletfx.utils.KeyDerivationTasks; import java.nio.ByteBuffer; import java.time.Duration; import java.util.Objects; import static org.bitcoinj.walletfx.utils.GuiUtils.*; /** * User interface for entering a password on demand, e.g. to send money. Also used when encrypting a wallet. Shows a * progress meter as we scrypt the password. */ public class WalletPasswordController implements OverlayController<WalletPasswordController> { private static final Logger log = LoggerFactory.getLogger(WalletPasswordController.class); @FXML HBox buttonsBox; @FXML PasswordField pass1; @FXML ImageView padlockImage; @FXML ProgressIndicator progressMeter; @FXML GridPane widgetGrid; @FXML Label explanationLabel; private WalletApplication app; private OverlayableStackPaneController rootController; private OverlayableStackPaneController.OverlayUI<? extends OverlayController<WalletPasswordController>> overlayUI; private SimpleObjectProperty<AesKey> aesKey = new SimpleObjectProperty<>(); @Override public void initOverlay(OverlayableStackPaneController overlayableStackPaneController, OverlayableStackPaneController.OverlayUI<? extends OverlayController<WalletPasswordController>> ui) { rootController = overlayableStackPaneController; overlayUI = ui; } public void initialize() { app = WalletApplication.instance(); progressMeter.setOpacity(0); Platform.runLater(pass1::requestFocus); } @FXML void confirmClicked(ActionEvent event) { String password = pass1.getText(); if (password.isEmpty() || password.length() < 4) { informationalAlert("Bad password", "The password you entered is empty or too short."); return; } final KeyCrypterScrypt keyCrypter = (KeyCrypterScrypt) app.walletAppKit().wallet().getKeyCrypter(); Objects.requireNonNull(keyCrypter); // We should never arrive at this GUI if the wallet isn't actually encrypted. KeyDerivationTasks tasks = new KeyDerivationTasks(keyCrypter, password, getTargetTime()) { @Override protected final void onFinish(AesKey aesKey, int timeTakenMsec) { checkGuiThread(); if (app.walletAppKit().wallet().checkAESKey(aesKey)) { WalletPasswordController.this.aesKey.set(aesKey); } else { log.warn("User entered incorrect password"); fadeOut(progressMeter); fadeIn(widgetGrid); fadeIn(explanationLabel); fadeIn(buttonsBox); informationalAlert("Wrong password", "Please try entering your password again, carefully checking for typos or spelling errors."); } } }; progressMeter.progressProperty().bind(tasks.progress); tasks.start(); fadeIn(progressMeter); fadeOut(widgetGrid); fadeOut(explanationLabel); fadeOut(buttonsBox); } public void cancelClicked(ActionEvent event) { overlayUI.done(); } public ReadOnlyObjectProperty<AesKey> aesKeyProperty() { return aesKey; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static final String TAG = WalletPasswordController.class.getName() + ".target-time"; // Writes the given time to the wallet as a tag so we can find it again in this class. public static void setTargetTime(Duration targetTime) { ByteString bytes = ByteString.copyFrom(longToByteArray(targetTime.toMillis())); WalletApplication.instance().walletAppKit().wallet().setTag(TAG, bytes); } // Reads target time or throws if not set yet (should never happen). public static Duration getTargetTime() throws IllegalArgumentException { return Duration.ofMillis(longFromByteArray(WalletApplication.instance().walletAppKit().wallet().getTag(TAG).toByteArray())); } private static byte[] longToByteArray(long val) { return ByteBuffer.allocate(8).putLong(val).array(); } private static long longFromByteArray(byte[] bytes) { return ByteBuffer.wrap(bytes).getLong(); } }
5,777
39.125
192
java
bitcoinj
bitcoinj-master/wallettemplate/src/main/java/wallettemplate/SendMoneyController.java
/* * Copyright by the original author or authors. * * 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. */ package wallettemplate; import javafx.application.Platform; import javafx.scene.layout.HBox; import org.bitcoinj.base.Address; import org.bitcoinj.base.Coin; import org.bitcoinj.crypto.AesKey; import org.bitcoinj.core.*; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.wallet.SendRequest; import org.bitcoinj.wallet.Wallet; import javafx.event.ActionEvent; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import org.bitcoinj.walletfx.application.WalletApplication; import org.bitcoinj.walletfx.overlay.OverlayController; import org.bitcoinj.walletfx.overlay.OverlayableStackPaneController; import org.bitcoinj.walletfx.controls.BitcoinAddressValidator; import org.bitcoinj.walletfx.utils.TextFieldValidator; import org.bitcoinj.walletfx.utils.WTUtils; import static org.bitcoinj.base.internal.Preconditions.checkState; import static org.bitcoinj.walletfx.utils.GuiUtils.*; public class SendMoneyController implements OverlayController<SendMoneyController> { public Button sendBtn; public Button cancelBtn; public TextField address; public Label titleLabel; public TextField amountEdit; public Label btcLabel; private WalletApplication app; private OverlayableStackPaneController rootController; private OverlayableStackPaneController.OverlayUI<? extends OverlayController<SendMoneyController>> overlayUI; private Wallet.SendResult sendResult; private AesKey aesKey; @Override public void initOverlay(OverlayableStackPaneController overlayableStackPaneController, OverlayableStackPaneController.OverlayUI<? extends OverlayController<SendMoneyController>> ui) { rootController = overlayableStackPaneController; overlayUI = ui; } // Called by FXMLLoader public void initialize() { app = WalletApplication.instance(); Coin balance = app.walletAppKit().wallet().getBalance(); checkState(!balance.isZero()); new BitcoinAddressValidator(app.walletAppKit().wallet(), address, sendBtn); new TextFieldValidator(amountEdit, text -> !WTUtils.didThrow(() -> checkState(Coin.parseCoin(text).compareTo(balance) <= 0))); amountEdit.setText(balance.toPlainString()); address.setPromptText(new ECKey().toAddress(app.preferredOutputScriptType(), app.network()).toString()); } public void cancel(ActionEvent event) { overlayUI.done(); } public void send(ActionEvent event) { // Address exception cannot happen as we validated it beforehand. try { Coin amount = Coin.parseCoin(amountEdit.getText()); Address destination = app.walletAppKit().wallet().parseAddress(address.getText()); SendRequest req; if (amount.equals(app.walletAppKit().wallet().getBalance())) req = SendRequest.emptyWallet(destination); else req = SendRequest.to(destination, amount); req.aesKey = aesKey; // Don't make the user wait for confirmations for now, as the intention is they're sending it // their own money! req.allowUnconfirmed(); sendResult = app.walletAppKit().wallet().sendCoins(req); sendResult.awaitRelayed().whenComplete((result, t) -> { if (t == null) { Platform.runLater(() -> overlayUI.done()); } else { // We died trying to empty the wallet. crashAlert(t); } }); sendResult.transaction().getConfidence().addEventListener((tx, reason) -> { if (reason == TransactionConfidence.Listener.ChangeReason.SEEN_PEERS) updateTitleForBroadcast(); }); sendBtn.setDisable(true); address.setDisable(true); ((HBox)amountEdit.getParent()).getChildren().remove(amountEdit); ((HBox)btcLabel.getParent()).getChildren().remove(btcLabel); updateTitleForBroadcast(); } catch (InsufficientMoneyException e) { informationalAlert("Could not empty the wallet", "You may have too little money left in the wallet to make a transaction."); overlayUI.done(); } catch (ECKey.KeyIsEncryptedException e) { askForPasswordAndRetry(); } } private void askForPasswordAndRetry() { OverlayableStackPaneController.OverlayUI<WalletPasswordController> pwd = rootController.overlayUI("wallet_password.fxml"); final String addressStr = address.getText(); final String amountStr = amountEdit.getText(); pwd.controller.aesKeyProperty().addListener((observable, old, cur) -> { // We only get here if the user found the right password. If they don't or they cancel, we end up back on // the main UI screen. By now the send money screen is history so we must recreate it. checkGuiThread(); OverlayableStackPaneController.OverlayUI<SendMoneyController> screen = rootController.overlayUI("send_money.fxml"); screen.controller.aesKey = cur; screen.controller.address.setText(addressStr); screen.controller.amountEdit.setText(amountStr); screen.controller.send(null); }); } private void updateTitleForBroadcast() { final int peers = sendResult.transaction().getConfidence().numBroadcastPeers(); titleLabel.setText(String.format("Broadcasting ... seen by %d peers", peers)); } }
6,237
42.929577
187
java
bitcoinj
bitcoinj-master/integration-test/src/test/java/org/bitcoinj/core/FilteredBlockAndPartialMerkleTreeTest.java
/* * Copyright 2012 Matt Corallo * 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. */ package org.bitcoinj.core; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Coin; import org.bitcoinj.base.LegacyAddress; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.Buffers; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.core.TransactionConfidence.ConfidenceType; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.store.MemoryBlockStore; import org.bitcoinj.testing.FakeTxBuilder; import org.bitcoinj.testing.InboundMessageQueuer; import org.bitcoinj.testing.TestWithPeerGroup; import org.bitcoinj.wallet.Wallet; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.math.BigInteger; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import static org.bitcoinj.base.internal.ByteUtils.writeInt32LE; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @RunWith(value = Parameterized.class) public class FilteredBlockAndPartialMerkleTreeTest extends TestWithPeerGroup { private static final BitcoinSerializer SERIALIZER = new BitcoinSerializer(TESTNET); @Parameterized.Parameters public static Collection<ClientType[]> parameters() { return Arrays.asList(new ClientType[] {ClientType.NIO_CLIENT_MANAGER}, new ClientType[] {ClientType.BLOCKING_CLIENT_MANAGER}); } public FilteredBlockAndPartialMerkleTreeTest(ClientType clientType) { super(clientType); } @Before public void setUp() throws Exception { MemoryBlockStore store = new MemoryBlockStore(TESTNET.getGenesisBlock()); // Cheat and place the previous block (block 100000) at the head of the block store without supporting blocks store.put(new StoredBlock(SERIALIZER.makeBlock(ByteBuffer.wrap(ByteUtils.parseHex("0100000050120119172a610421a6c3011dd330d9df07b63616c2cc1f1cd00200000000006657a9252aacd5c0b2940996ecff952228c3067cc38d4885efb5a4ac4247e9f337221b4d4c86041b0f2b5710"))), BigInteger.ONE, 100_000)); store.setChainHead(store.get(Sha256Hash.wrap("000000000003ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506"))); wallet = Wallet.createBasic(BitcoinNetwork.TESTNET); wallet.importKeys(Arrays.asList(ECKey.fromPublicOnly(ByteUtils.parseHex("04b27f7e9475ccf5d9a431cb86d665b8302c140144ec2397fce792f4a4e7765fecf8128534eaa71df04f93c74676ae8279195128a1506ebf7379d23dab8fca0f63")), ECKey.fromPublicOnly(ByteUtils.parseHex("04732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ec")), ECKey.fromPublicOnly(ByteUtils.parseHex("04cfb4113b3387637131ebec76871fd2760fc430dd16de0110f0eb07bb31ffac85e2607c189cb8582ea1ccaeb64ffd655409106589778f3000fdfe3263440b0350")), ECKey.fromPublicOnly(ByteUtils.parseHex("04b2f30018908a59e829c1534bfa5010d7ef7f79994159bba0f534d863ef9e4e973af6a8de20dc41dbea50bc622263ec8a770b2c9406599d39e4c9afe61f8b1613")))); super.setUp(store); } @After public void tearDown() { super.tearDown(); } @Test public void deserializeFilteredBlock() { // Random real block (000000000000dab0130bbcc991d3d7ae6b81aa6f50a798888dfe62337458dc45) // With one tx FilteredBlock block = FilteredBlock.read(ByteBuffer.wrap(ByteUtils.parseHex("0100000079cda856b143d9db2c1caff01d1aecc8630d30625d10e8b4b8b0000000000000b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f196367291b4d4c86041b8fa45d630100000001b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f19630101"))); // Check that the header was properly deserialized assertEquals(Sha256Hash.wrap("000000000000dab0130bbcc991d3d7ae6b81aa6f50a798888dfe62337458dc45"), block.getBlockHeader().getHash()); // Check that the partial merkle tree is correct List<Sha256Hash> txesMatched = block.getTransactionHashes(); assertEquals(1, txesMatched.size()); assertTrue(txesMatched.contains(Sha256Hash.wrap("63194f18be0af63f2c6bc9dc0f777cbefed3d9415c4af83f3ee3a3d669c00cb5"))); // Check round tripping. assertEquals(block, FilteredBlock.read(ByteBuffer.wrap(block.serialize()))); } @Test public void createFilteredBlock() throws Exception { Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true)); ECKey key1 = new ECKey(); ECKey key2 = new ECKey(); Transaction tx1 = FakeTxBuilder.createFakeTx(Coin.COIN, key1); Transaction tx2 = FakeTxBuilder.createFakeTx(TESTNET.network(), Coin.FIFTY_COINS, key2.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)); Block block = FakeTxBuilder.makeSolvedTestBlock(TESTNET.getGenesisBlock(), LegacyAddress.fromBase58("msg2t2V2sWNd85LccoddtWysBTR8oPnkzW", BitcoinNetwork.TESTNET), tx1, tx2); BloomFilter filter = new BloomFilter(4, 0.1, 1); filter.insert(key1); filter.insert(key2); FilteredBlock filteredBlock = filter.applyAndUpdate(block); assertEquals(4, filteredBlock.getTransactionCount()); // This call triggers verification of the just created data. List<Sha256Hash> txns = filteredBlock.getTransactionHashes(); assertTrue(txns.contains(tx1.getTxId())); assertTrue(txns.contains(tx2.getTxId())); } private Sha256Hash numAsHash(int num) { byte[] bits = new byte[32]; bits[0] = (byte) num; return Sha256Hash.wrap(bits); } @Test(expected = VerificationException.class) public void merkleTreeMalleability() { List<Sha256Hash> hashes = new ArrayList<>(); for (byte i = 1; i <= 10; i++) hashes.add(numAsHash(i)); hashes.add(numAsHash(9)); hashes.add(numAsHash(10)); byte[] includeBits = new byte[2]; ByteUtils.setBitLE(includeBits, 9); ByteUtils.setBitLE(includeBits, 10); PartialMerkleTree pmt = PartialMerkleTree.buildFromLeaves(includeBits, hashes); List<Sha256Hash> matchedHashes = new ArrayList<>(); pmt.getTxnHashAndMerkleRoot(matchedHashes); } @Test public void serializeDownloadBlockWithWallet() throws Exception { // First we create all the necessary objects, including lots of serialization and double-checks // Note that all serialized forms here are generated by Bitcoin Core/pulled from block explorer Block block = SERIALIZER.makeBlock(ByteBuffer.wrap(ByteUtils.parseHex("0100000006e533fd1ada86391f3f6c343204b0d278d4aaec1c0b20aa27ba0300000000006abbb3eb3d733a9fe18967fd7d4c117e4ccbbac5bec4d910d900b3ae0793e77f54241b4d4c86041b4089cc9b0c01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b010dffffffff0100f2052a01000000434104b27f7e9475ccf5d9a431cb86d665b8302c140144ec2397fce792f4a4e7765fecf8128534eaa71df04f93c74676ae8279195128a1506ebf7379d23dab8fca0f63ac000000000100000001d992e5a888a86d4c7a6a69167a4728ee69497509740fc5f456a24528c340219a000000008b483045022100f0519bdc9282ff476da1323b8ef7ffe33f495c1a8d52cc522b437022d83f6a230220159b61d197fbae01b4a66622a23bc3f1def65d5fa24efd5c26fa872f3a246b8e014104839f9023296a1fabb133140128ca2709f6818c7d099491690bd8ac0fd55279def6a2ceb6ab7b5e4a71889b6e739f09509565eec789e86886f6f936fa42097adeffffffff02000fe208010000001976a914948c765a6914d43f2a7ac177da2c2f6b52de3d7c88ac00e32321000000001976a9140c34f4e29ab5a615d5ea28d4817f12b137d62ed588ac0000000001000000059daf0abe7a92618546a9dbcfd65869b6178c66ec21ccfda878c1175979cfd9ef000000004a493046022100c2f7f25be5de6ce88ac3c1a519514379e91f39b31ddff279a3db0b1a229b708b022100b29efbdbd9837cc6a6c7318aa4900ed7e4d65662c34d1622a2035a3a5534a99a01ffffffffd516330ebdf075948da56db13d22632a4fb941122df2884397dda45d451acefb0000000048473044022051243debe6d4f2b433bee0cee78c5c4073ead0e3bde54296dbed6176e128659c022044417bfe16f44eb7b6eb0cdf077b9ce972a332e15395c09ca5e4f602958d266101ffffffffe1f5aa33961227b3c344e57179417ce01b7ccd421117fe2336289b70489883f900000000484730440220593252bb992ce3c85baf28d6e3aa32065816271d2c822398fe7ee28a856bc943022066d429dd5025d3c86fd8fd8a58e183a844bd94aa312cefe00388f57c85b0ca3201ffffffffe207e83718129505e6a7484831442f668164ae659fddb82e9e5421a081fb90d50000000049483045022067cf27eb733e5bcae412a586b25a74417c237161a084167c2a0b439abfebdcb2022100efcc6baa6824b4c5205aa967e0b76d31abf89e738d4b6b014e788c9a8cccaf0c01ffffffffe23b8d9d80a9e9d977fab3c94dbe37befee63822443c3ec5ae5a713ede66c3940000000049483045022020f2eb35036666b1debe0d1d2e77a36d5d9c4e96c1dba23f5100f193dbf524790221008ce79bc1321fb4357c6daee818038d41544749127751726e46b2b320c8b565a201ffffffff0200ba1dd2050000001976a914366a27645806e817a6cd40bc869bdad92fe5509188ac40420f00000000001976a914ee8bd501094a7d5ca318da2506de35e1cb025ddc88ac0000000001000000010abad2dc0c9b4b1dbb023077da513f81e5a71788d8680fca98ef1c37356c459c000000004a493046022100a894e521c87b3dbe23007079db4ac2896e9e791f8b57317ba6c0d99a7becd27a022100bc40981393eafeb33e89079f857c728701a9af4523c3f857cd96a500f240780901ffffffff024026ee22010000001976a914d28f9cefb58c1f7a5f97aa6b79047585f58fbd4388acc0cb1707000000001976a9142229481696e417aa5f51ad751d8cd4c6a669e4fe88ac000000000100000001f66d89b3649e0b18d84db056930676cb81c0168042fc4324c3682e252ea9410d0000000048473044022038e0b55b37c9253bfeda59c76c0134530f91fb586d6eb21738a77a984f370a44022048d4d477aaf97ef9c8275bbc5cb19b9c8a0e9b1f9fdafdd39bc85bf6c2f04a4d01ffffffff024041a523010000001976a914955f70ac8792b48b7bd52b15413bd8500ecf32c888ac00f36f06000000001976a91486116d15f3dbb23a2b58346f36e6ec2d867eba2b88ac00000000010000000126c384984f63446a4f2be8dd6531ba9837bd5f2c3d37403c5f51fb9192ee754e010000008b48304502210083af8324456f052ff1b2597ff0e6a8cce8b006e379a410cf781be7874a2691c2022072259e2f7292960dea0ffc361bbad0b861f719beb8550476f22ce0f82c023449014104f3ed46a81cba02af0593e8572a9130adb0d348b538c829ccaaf8e6075b78439b2746a76891ce7ba71abbcbb7ca76e8a220782738a6789562827c1065b0ce911dffffffff02c0dd9107000000001976a91463d4dd1b29d95ed601512b487bfc1c49d84d057988ac00a0491a010000001976a91465746bef92511df7b34abf71c162efb7ae353de388ac0000000001000000011b56cf3aab3286d582c055a42af3a911ee08423f276da702bb67f1222ac1a5b6000000008c4930460221009e9fba682e162c9627b96b7df272006a727988680b956c61baff869f0907b8fb022100a9c19adc7c36144bafe526630783845e5cb9554d30d3edfb56f0740274d507f30141046e0efbfac7b1615ad553a6f097615bc63b7cdb3b8e1cb3263b619ba63740012f51c7c5b09390e3577e377b7537e61226e315f95f926444fc5e5f2978c112e448ffffffff02c0072b11010000001976a914b73e9e01933351ca076faf8e0d94dd58079d0b1f88ac80b63908000000001976a9141aca0bdf0d2cee63db19aa4a484f45a4e26a880c88ac000000000100000001251b187504ea873b2c3915fad401f7a7734cc13567e0417708e86294a29f4f68010000008b4830450221009bef423141ed1ae60d0a5bcaa57b1673fc96001f0d4e105535cca817ba5a7724022037c399bd30374f22481ffc81327cfca4951c7264b227f765fcd6a429f3d9d2080141044d0d1b4f194c31a73dbce41c42b4b3946849117c5bb320467e014bad3b1532f28a9a1568ba7108f188e7823b6e618e91d974306701379a27b9339e646e156e7bffffffff02c00fd103010000001976a914ef7f5d9e1bc6ed68cfe0b1db9d8f09cef0f3ba4a88ac004dd208000000001976a914c22420641cea028c9e06c4d9104c1646f8b1769088ac0000000001000000013486dd5f0a2f3efcc04f64cb03872c021f98ee39f514747ce5336b874bbe47a7010000008b48304502201cadddc2838598fee7dc35a12b340c6bde8b389f7bfd19a1252a17c4b5ed2d71022100c1a251bbecb14b058a8bd77f65de87e51c47e95904f4c0e9d52eddc21c1415ac014104fe7df86d58aafa9246ca6fd30c905714533c25f700e2329b8ecec8aa52083b844baa3a8acd5d6b9732dcb39079bb56ba2711a3580dec824955fce0596a460c11ffffffff02c011f6e1000000001976a91490fac83c9adde91d670dde8755f8b475ab9e427d88acc0f9df15000000001976a91437f691b3e8ee5dcb56c2e31af4c80caa2df3b09b88ac00000000010000000170016bd1274b795b262f32a53003a4714b22b62f9057adf5fbe6ed939003b5190100000089463043022061456499582170a94d6b54308f792e37dad28bf0ed7aa61021f0301d2774d378021f4224b33f707efd810a01dd34ea86d6069cd599cc435513a0eef8c83c137bf7014104a2c95d6b98e745448eb45ed0ba95cf24dd7c3b16386e1028e24a0358ee4afc33e2f0199139853edaf32845d8a42254c75f7dc8add3286c682c650fbd93f0a4a1ffffffff02001bd2b7000000001976a9141b11c6acaa5223013f3a3240fdb024ecd9f8135488ac8023ad18000000001976a914ada27ca87bbaa1ee6fb1cb61bb0a29baaf6da2c988ac000000000100000001c8ff91f031ec6a5aba4baee6549e61dd01f26f61b70e2f1574f24cd680f464ad000000008b48304502210082235e21a2300022738dabb8e1bbd9d19cfb1e7ab8c30a23b0afbb8d178abcf3022024bf68e256c534ddfaf966bf908deb944305596f7bdcc38d69acad7f9c868724014104174f9eef1157dc1ad5eac198250b70d1c3b04b2fca12ad1483f07358486f02909b088bbc83f4de55f767f6cdf9d424aa02b5eeaffa08394d39b717895fc08d0affffffff0200ea3b43000000001976a914fb32df708f0610901f6d1b6df8c9c368fe0d981c88ac800f1777000000001976a914462c501c70fb996d15ac0771e7fc8d3ca3f7201888ac000000000100000001c67323867de802402e780a70e0deba3c708c4d87497e17590afee9c321f1c680010000008a473044022042734b25f54845d662e6499b75ff8529ff47f42fd224498a9f752d212326dbfa0220523e4b7b570bbb1f3af02baa2c04ea8eb7b0fccb1522cced130b666ae9a9d014014104b5a23b922949877e9eaf7512897ed091958e2e8cf05b0d0eb9064e7976043fde6023b4e2c188b7e38ef94eec6845dc4933f5e8635f1f6a3702290956aa9e284bffffffff0280041838030000001976a91436e5884215f7d3044be5d37bdd8c987d9d942c8488ac404b4c00000000001976a91460085d6838f8a44a21a0de56ff963cfa6242a96188ac00000000"))); FilteredBlock filteredBlock = FilteredBlock.read(ByteBuffer.wrap(ByteUtils.parseHex("0100000006e533fd1ada86391f3f6c343204b0d278d4aaec1c0b20aa27ba0300000000006abbb3eb3d733a9fe18967fd7d4c117e4ccbbac5bec4d910d900b3ae0793e77f54241b4d4c86041b4089cc9b0c000000084c30b63cfcdc2d35e3329421b9805ef0c6565d35381ca857762ea0b3a5a128bbca5065ff9617cbcba45eb23726df6498a9b9cafed4f54cbab9d227b0035ddefbbb15ac1d57d0182aaee61c74743a9c4f785895e563909bafec45c9a2b0ff3181d77706be8b1dcc91112eada86d424e2d0a8907c3488b6e44fda5a74a25cbc7d6bb4fa04245f4ac8a1a571d5537eac24adca1454d65eda446055479af6c6d4dd3c9ab658448c10b6921b7a4ce3021eb22ed6bb6a7fde1e5bcc4b1db6615c6abc5ca042127bfaf9f44ebce29cb29c6df9d05b47f35b2edff4f0064b578ab741fa78276222651209fe1a2c4c0fa1c58510aec8b090dd1eb1f82f9d261b8273b525b02ff1a"))); // Block 100001 assertEquals(Sha256Hash.wrap("00000000000080b66c911bd5ba14a74260057311eaeb1982802f7010f1a9f090"), block.getHash()); assertEquals(block.getHash(), filteredBlock.getHash()); List<Sha256Hash> txHashList = filteredBlock.getTransactionHashes(); assertEquals(4, txHashList.size()); // Four transactions (0, 1, 2, 6) from block 100001 Transaction tx0 = TESTNET.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(ByteUtils.parseHex("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b010dffffffff0100f2052a01000000434104b27f7e9475ccf5d9a431cb86d665b8302c140144ec2397fce792f4a4e7765fecf8128534eaa71df04f93c74676ae8279195128a1506ebf7379d23dab8fca0f63ac00000000"))); assertEquals(Sha256Hash.wrap("bb28a1a5b3a02e7657a81c38355d56c6f05e80b9219432e3352ddcfc3cb6304c"), tx0.getTxId()); assertEquals(tx0.getTxId(), txHashList.get(0)); Transaction tx1 = TESTNET.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(ByteUtils.parseHex("0100000001d992e5a888a86d4c7a6a69167a4728ee69497509740fc5f456a24528c340219a000000008b483045022100f0519bdc9282ff476da1323b8ef7ffe33f495c1a8d52cc522b437022d83f6a230220159b61d197fbae01b4a66622a23bc3f1def65d5fa24efd5c26fa872f3a246b8e014104839f9023296a1fabb133140128ca2709f6818c7d099491690bd8ac0fd55279def6a2ceb6ab7b5e4a71889b6e739f09509565eec789e86886f6f936fa42097adeffffffff02000fe208010000001976a914948c765a6914d43f2a7ac177da2c2f6b52de3d7c88ac00e32321000000001976a9140c34f4e29ab5a615d5ea28d4817f12b137d62ed588ac00000000"))); assertEquals(Sha256Hash.wrap("fbde5d03b027d2b9ba4cf5d4fecab9a99864df2637b25ea4cbcb1796ff6550ca"), tx1.getTxId()); assertEquals(tx1.getTxId(), txHashList.get(1)); Transaction tx2 = TESTNET.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(ByteUtils.parseHex("01000000059daf0abe7a92618546a9dbcfd65869b6178c66ec21ccfda878c1175979cfd9ef000000004a493046022100c2f7f25be5de6ce88ac3c1a519514379e91f39b31ddff279a3db0b1a229b708b022100b29efbdbd9837cc6a6c7318aa4900ed7e4d65662c34d1622a2035a3a5534a99a01ffffffffd516330ebdf075948da56db13d22632a4fb941122df2884397dda45d451acefb0000000048473044022051243debe6d4f2b433bee0cee78c5c4073ead0e3bde54296dbed6176e128659c022044417bfe16f44eb7b6eb0cdf077b9ce972a332e15395c09ca5e4f602958d266101ffffffffe1f5aa33961227b3c344e57179417ce01b7ccd421117fe2336289b70489883f900000000484730440220593252bb992ce3c85baf28d6e3aa32065816271d2c822398fe7ee28a856bc943022066d429dd5025d3c86fd8fd8a58e183a844bd94aa312cefe00388f57c85b0ca3201ffffffffe207e83718129505e6a7484831442f668164ae659fddb82e9e5421a081fb90d50000000049483045022067cf27eb733e5bcae412a586b25a74417c237161a084167c2a0b439abfebdcb2022100efcc6baa6824b4c5205aa967e0b76d31abf89e738d4b6b014e788c9a8cccaf0c01ffffffffe23b8d9d80a9e9d977fab3c94dbe37befee63822443c3ec5ae5a713ede66c3940000000049483045022020f2eb35036666b1debe0d1d2e77a36d5d9c4e96c1dba23f5100f193dbf524790221008ce79bc1321fb4357c6daee818038d41544749127751726e46b2b320c8b565a201ffffffff0200ba1dd2050000001976a914366a27645806e817a6cd40bc869bdad92fe5509188ac40420f00000000001976a914ee8bd501094a7d5ca318da2506de35e1cb025ddc88ac00000000"))); assertEquals(Sha256Hash.wrap("8131ffb0a2c945ecaf9b9063e59558784f9c3a74741ce6ae2a18d0571dac15bb"), tx2.getTxId()); assertEquals(tx2.getTxId(), txHashList.get(2)); Transaction tx3 = TESTNET.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(ByteUtils.parseHex("01000000011b56cf3aab3286d582c055a42af3a911ee08423f276da702bb67f1222ac1a5b6000000008c4930460221009e9fba682e162c9627b96b7df272006a727988680b956c61baff869f0907b8fb022100a9c19adc7c36144bafe526630783845e5cb9554d30d3edfb56f0740274d507f30141046e0efbfac7b1615ad553a6f097615bc63b7cdb3b8e1cb3263b619ba63740012f51c7c5b09390e3577e377b7537e61226e315f95f926444fc5e5f2978c112e448ffffffff02c0072b11010000001976a914b73e9e01933351ca076faf8e0d94dd58079d0b1f88ac80b63908000000001976a9141aca0bdf0d2cee63db19aa4a484f45a4e26a880c88ac00000000"))); assertEquals(Sha256Hash.wrap("c5abc61566dbb1c4bce5e1fda7b66bed22eb2130cea4b721690bc1488465abc9"), tx3.getTxId()); assertEquals(tx3.getTxId(),txHashList.get(3)); BloomFilter filter = wallet.getBloomFilter(wallet.getKeyChainGroupSize()*2, 0.001, 0xDEADBEEF); // Compare the serialized bloom filter to a known-good value assertArrayEquals(ByteUtils.parseHex("0e1b091ca195e45a9164889b6bc46a09000000efbeadde02"), filter.serialize()); // Create a peer. peerGroup.start(); InboundMessageQueuer p1 = connectPeer(1); assertEquals(1, peerGroup.numConnectedPeers()); // Send an inv for block 100001 InventoryMessage inv = new InventoryMessage(); inv.addBlock(block); inbound(p1, inv); // Check that we properly requested the correct FilteredBlock Object getData = outbound(p1); assertTrue(getData instanceof GetDataMessage); assertEquals(1, ((GetDataMessage) getData).getItems().size()); assertEquals(block.getHash(), ((GetDataMessage) getData).getItems().get(0).hash); assertEquals(InventoryItem.Type.FILTERED_BLOCK, ((GetDataMessage) getData).getItems().get(0).type); // Check that we then immediately pinged. Object ping = outbound(p1); assertTrue(ping instanceof Ping); // Respond with transactions and the filtered block inbound(p1, filteredBlock); inbound(p1, tx0); inbound(p1, tx1); inbound(p1, tx2); inbound(p1, tx3); inbound(p1, ((Ping) ping).pong()); pingAndWait(p1); Set<Transaction> transactions = wallet.getTransactions(false); assertEquals(4, transactions.size()); for (Transaction tx : transactions) { assertEquals(ConfidenceType.BUILDING, tx.getConfidence().getConfidenceType()); assertEquals(1, tx.getConfidence().getDepthInBlocks()); assertTrue(tx.getAppearsInHashes().keySet().contains(block.getHash())); assertEquals(1, tx.getAppearsInHashes().size()); } // Peer 1 goes away. closePeer(peerOf(p1)); } @Test public void parseHugeDeclaredSizePartialMerkleTree() { final byte[] bits = new byte[1]; bits[0] = 0x3f; final List<Sha256Hash> hashes = new ArrayList<>(); hashes.add(Sha256Hash.wrap("0000000000000000000000000000000000000000000000000000000000000001")); hashes.add(Sha256Hash.wrap("0000000000000000000000000000000000000000000000000000000000000002")); hashes.add(Sha256Hash.wrap("0000000000000000000000000000000000000000000000000000000000000003")); PartialMerkleTree pmt = new PartialMerkleTree(3, hashes, bits) { public ByteBuffer write(ByteBuffer buf) throws BufferOverflowException { writeInt32LE(getTransactionCount(), buf); // Add Integer.MAX_VALUE instead of hashes.size() VarInt.of(Integer.MAX_VALUE).write(buf); for (Sha256Hash hash : hashes) hash.write(buf); Buffers.writeLengthPrefixedBytes(buf, bits); return buf; } @Override public int getMessageSize() { return super.getMessageSize() + 4; // adjust for the longer VarInt } }; byte[] serializedPmt = pmt.serialize(); try { PartialMerkleTree.read(ByteBuffer.wrap(serializedPmt)); fail("We expect BufferUnderflowException with the fixed code and OutOfMemoryError with the buggy code, so this is weird"); } catch (BufferUnderflowException e) { //Expected, do nothing } } }
22,748
85.828244
6,700
java
bitcoinj
bitcoinj-master/integration-test/src/test/java/org/bitcoinj/core/PeerTest.java
/* * Copyright 2011 Google Inc. * * 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. */ package org.bitcoinj.core; import com.google.common.collect.Lists; import com.google.common.util.concurrent.Uninterruptibles; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Coin; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.core.listeners.BlocksDownloadedEventListener; import org.bitcoinj.core.listeners.PreMessageReceivedEventListener; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.testing.InboundMessageQueuer; import org.bitcoinj.testing.TestWithNetworkConnections; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.Wallet; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import javax.annotation.Nullable; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.nio.channels.CancelledKeyException; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static org.bitcoinj.base.Coin.COIN; import static org.bitcoinj.base.Coin.valueOf; import static org.bitcoinj.testing.FakeTxBuilder.createFakeBlock; import static org.bitcoinj.testing.FakeTxBuilder.createFakeTx; import static org.bitcoinj.testing.FakeTxBuilder.makeSolvedTestBlock; import static org.bitcoinj.testing.FakeTxBuilder.roundTripTransaction; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @RunWith(value = Parameterized.class) public class PeerTest extends TestWithNetworkConnections { private Peer peer; private InboundMessageQueuer writeTarget; private static final int OTHER_PEER_CHAIN_HEIGHT = 110; private final AtomicBoolean fail = new AtomicBoolean(false); @Parameterized.Parameters public static Collection<ClientType[]> parameters() { return Arrays.asList(new ClientType[] {ClientType.NIO_CLIENT_MANAGER}, new ClientType[] {ClientType.BLOCKING_CLIENT_MANAGER}, new ClientType[] {ClientType.NIO_CLIENT}, new ClientType[] {ClientType.BLOCKING_CLIENT}); } public PeerTest(ClientType clientType) { super(clientType); } @Override @Before public void setUp() throws Exception { super.setUp(); VersionMessage ver = new VersionMessage(TESTNET, 100); InetSocketAddress address = new InetSocketAddress(InetAddress.getLoopbackAddress(), 4000); peer = new Peer(TESTNET, ver, PeerAddress.simple(address), blockChain); peer.addWallet(wallet); } @Override @After public void tearDown() throws Exception { super.tearDown(); assertFalse(fail.get()); } private void connect() throws Exception { connectWithVersion(70001, Services.NODE_NETWORK); } private void connectWithVersion(int version, int flags) throws Exception { VersionMessage peerVersion = new VersionMessage(TESTNET, OTHER_PEER_CHAIN_HEIGHT); peerVersion.clientVersion = version; peerVersion.localServices = Services.of(flags); writeTarget = connect(peer, peerVersion); } // Check that it runs through the event loop and shut down correctly @Test public void shutdown() throws Exception { closePeer(peer); } @Test public void chainDownloadEnd2End() throws Exception { // A full end-to-end test of the chain download process, with a new block being solved in the middle. Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true)); Block b1 = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); Block b3 = makeSolvedTestBlock(b2); Block b4 = makeSolvedTestBlock(b3); Block b5 = makeSolvedTestBlock(b4); connect(); peer.startBlockChainDownload(); GetBlocksMessage getblocks = (GetBlocksMessage)outbound(writeTarget); assertEquals(blockStore.getChainHead().getHeader().getHash(), getblocks.getLocator().get(0)); assertEquals(Sha256Hash.ZERO_HASH, getblocks.getStopHash()); // Remote peer sends us an inv with some blocks. InventoryMessage inv = new InventoryMessage(); inv.addBlock(b2); inv.addBlock(b3); // We do a getdata on them. inbound(writeTarget, inv); GetDataMessage getdata = (GetDataMessage)outbound(writeTarget); assertEquals(b2.getHash(), getdata.getItems().get(0).hash); assertEquals(b3.getHash(), getdata.getItems().get(1).hash); assertEquals(2, getdata.getItems().size()); // Remote peer sends us the blocks. The act of doing a getdata for b3 results in getting an inv with just the // best chain head in it. inbound(writeTarget, b2); inbound(writeTarget, b3); inv = new InventoryMessage(); inv.addBlock(b5); // We request the head block. inbound(writeTarget, inv); getdata = (GetDataMessage)outbound(writeTarget); assertEquals(b5.getHash(), getdata.getItems().get(0).hash); assertEquals(1, getdata.getItems().size()); // Peer sends us the head block. The act of receiving the orphan block triggers a getblocks to fill in the // rest of the chain. inbound(writeTarget, b5); getblocks = (GetBlocksMessage)outbound(writeTarget); assertEquals(b5.getHash(), getblocks.getStopHash()); assertEquals(b3.getHash(), getblocks.getLocator().getHashes().get(0)); // At this point another block is solved and broadcast. The inv triggers a getdata but we do NOT send another // getblocks afterwards, because that would result in us receiving the same set of blocks twice which is a // timewaste. The getblocks message that would have been generated is set to be the same as the previous // because we walk backwards down the orphan chain and then discover we already asked for those blocks, so // nothing is done. Block b6 = makeSolvedTestBlock(b5); inv = new InventoryMessage(); inv.addBlock(b6); inbound(writeTarget, inv); getdata = (GetDataMessage)outbound(writeTarget); assertEquals(1, getdata.getItems().size()); assertEquals(b6.getHash(), getdata.getItems().get(0).hash); inbound(writeTarget, b6); assertNull(outbound(writeTarget)); // Nothing is sent at this point. // We're still waiting for the response to the getblocks (b3,b5) sent above. inv = new InventoryMessage(); inv.addBlock(b4); inv.addBlock(b5); inbound(writeTarget, inv); getdata = (GetDataMessage)outbound(writeTarget); assertEquals(1, getdata.getItems().size()); assertEquals(b4.getHash(), getdata.getItems().get(0).hash); // We already have b5 from before, so it's not requested again. inbound(writeTarget, b4); assertNull(outbound(writeTarget)); // b5 and b6 are now connected by the block chain and we're done. assertNull(outbound(writeTarget)); closePeer(peer); } // Check that an inventory tickle is processed correctly when downloading missing blocks is active. @Test public void invTickle() throws Exception { connect(); Block b1 = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS).block; blockChain.add(b1); // Make a missing block. Block b2 = makeSolvedTestBlock(b1); Block b3 = makeSolvedTestBlock(b2); inbound(writeTarget, b3); InventoryMessage inv = new InventoryMessage(); InventoryItem item = new InventoryItem(InventoryItem.Type.BLOCK, b3.getHash()); inv.addItem(item); inbound(writeTarget, inv); GetBlocksMessage getblocks = (GetBlocksMessage)outbound(writeTarget); BlockLocator expectedLocator = new BlockLocator(); expectedLocator = expectedLocator.add(b1.getHash()); expectedLocator = expectedLocator.add(TESTNET.getGenesisBlock().getHash()); assertEquals(getblocks.getLocator(), expectedLocator); assertEquals(getblocks.getStopHash(), b3.getHash()); assertNull(outbound(writeTarget)); } // Check that an inv to a peer that is not set to download missing blocks does nothing. @Test public void invNoDownload() throws Exception { // Don't download missing blocks. peer.setDownloadData(false); connect(); // Make a missing block that we receive. Block b1 = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); // Receive an inv. InventoryMessage inv = new InventoryMessage(); InventoryItem item = new InventoryItem(InventoryItem.Type.BLOCK, b2.getHash()); inv.addItem(item); inbound(writeTarget, inv); // Peer does nothing with it. assertNull(outbound(writeTarget)); } @Test public void invDownloadTx() throws Exception { connect(); peer.setDownloadData(true); // Make a transaction and tell the peer we have it. Coin value = COIN; Transaction tx = createFakeTx(TESTNET.network(), value, address); InventoryMessage inv = new InventoryMessage(); InventoryItem item = new InventoryItem(InventoryItem.Type.TRANSACTION, tx.getTxId()); inv.addItem(item); inbound(writeTarget, inv); // Peer hasn't seen it before, so will ask for it. GetDataMessage getdata = (GetDataMessage) outbound(writeTarget); assertEquals(1, getdata.getItems().size()); assertEquals(tx.getTxId(), getdata.getItems().get(0).hash); inbound(writeTarget, tx); // Ask for the dependency, it's not in the mempool (in chain). getdata = (GetDataMessage) outbound(writeTarget); inbound(writeTarget, new NotFoundMessage(getdata.getItems())); pingAndWait(writeTarget); assertEquals(value, wallet.getBalance(Wallet.BalanceType.ESTIMATED)); } @Test public void invDownloadTxMultiPeer() throws Exception { // Check co-ordination of which peer to download via the memory pool. VersionMessage ver = new VersionMessage(TESTNET, 100); InetSocketAddress address = new InetSocketAddress(InetAddress.getLoopbackAddress(), 4242); Peer peer2 = new Peer(TESTNET, ver, PeerAddress.simple(address), blockChain); peer2.addWallet(wallet); VersionMessage peerVersion = new VersionMessage(TESTNET, OTHER_PEER_CHAIN_HEIGHT); peerVersion.clientVersion = 70001; peerVersion.localServices = Services.of(Services.NODE_NETWORK); connect(); InboundMessageQueuer writeTarget2 = connect(peer2, peerVersion); // Make a tx and advertise it to one of the peers. Coin value = COIN; Transaction tx = createFakeTx(TESTNET.network(), value, this.address); InventoryMessage inv = new InventoryMessage(); InventoryItem item = new InventoryItem(InventoryItem.Type.TRANSACTION, tx.getTxId()); inv.addItem(item); inbound(writeTarget, inv); // We got a getdata message. GetDataMessage message = (GetDataMessage)outbound(writeTarget); assertEquals(1, message.getItems().size()); assertEquals(tx.getTxId(), message.getItems().get(0).hash); assertNotEquals(0, tx.getConfidence().numBroadcastPeers()); // Advertising to peer2 results in no getdata message. inbound(writeTarget2, inv); pingAndWait(writeTarget2); assertNull(outbound(writeTarget2)); } // Check that inventory message containing blocks we want is processed correctly. @Test public void newBlock() throws Exception { Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true)); Block b1 = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS).block; blockChain.add(b1); final Block b2 = makeSolvedTestBlock(b1); // Receive notification of a new block. final InventoryMessage inv = new InventoryMessage(); InventoryItem item = new InventoryItem(InventoryItem.Type.BLOCK, b2.getHash()); inv.addItem(item); final AtomicInteger newBlockMessagesReceived = new AtomicInteger(0); connect(); // Round-trip a ping so that we never see the response verack if we attach too quick pingAndWait(writeTarget); peer.addPreMessageReceivedEventListener(Threading.SAME_THREAD, new PreMessageReceivedEventListener() { @Override public synchronized Message onPreMessageReceived(Peer p, Message m) { if (p != peer) fail.set(true); if (m instanceof Pong) return m; int newValue = newBlockMessagesReceived.incrementAndGet(); if (newValue == 1 && !inv.equals(m)) fail.set(true); else if (newValue == 2 && !b2.equals(m)) fail.set(true); else if (newValue > 3) fail.set(true); return m; } }); peer.addBlocksDownloadedEventListener(Threading.SAME_THREAD, new BlocksDownloadedEventListener() { @Override public synchronized void onBlocksDownloaded(Peer p, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft) { int newValue = newBlockMessagesReceived.incrementAndGet(); if (newValue != 3 || p != peer || !block.equals(b2) || blocksLeft != OTHER_PEER_CHAIN_HEIGHT - 2) fail.set(true); } }); long height = peer.getBestHeight(); inbound(writeTarget, inv); pingAndWait(writeTarget); assertEquals(height + 1, peer.getBestHeight()); // Response to the getdata message. inbound(writeTarget, b2); pingAndWait(writeTarget); Threading.waitForUserCode(); pingAndWait(writeTarget); assertEquals(3, newBlockMessagesReceived.get()); GetDataMessage getdata = (GetDataMessage) outbound(writeTarget); List<InventoryItem> items = getdata.getItems(); assertEquals(1, items.size()); assertEquals(b2.getHash(), items.get(0).hash); assertEquals(InventoryItem.Type.BLOCK, items.get(0).type); } // Check that it starts downloading the block chain correctly on request. @Test public void startBlockChainDownload() throws Exception { Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true)); Block b1 = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); blockChain.add(b2); connect(); fail.set(true); peer.addChainDownloadStartedEventListener(Threading.SAME_THREAD, (p, blocksLeft) -> { if (p == peer && blocksLeft == 108) fail.set(false); }); peer.startBlockChainDownload(); BlockLocator expectedLocator = new BlockLocator(); expectedLocator = expectedLocator.add(b2.getHash()); expectedLocator = expectedLocator.add(b1.getHash()); expectedLocator = expectedLocator.add(TESTNET.getGenesisBlock().getHash()); GetBlocksMessage message = (GetBlocksMessage) outbound(writeTarget); assertEquals(message.getLocator(), expectedLocator); assertEquals(Sha256Hash.ZERO_HASH, message.getStopHash()); } @Test public void getBlock() throws Exception { Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true)); connect(); Block b1 = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); Block b3 = makeSolvedTestBlock(b2); // Request the block. Future<Block> resultFuture = peer.getBlock(b3.getHash()); assertFalse(resultFuture.isDone()); // Peer asks for it. GetDataMessage message = (GetDataMessage) outbound(writeTarget); assertEquals(message.getItems().get(0).hash, b3.getHash()); assertFalse(resultFuture.isDone()); // Peer receives it. inbound(writeTarget, b3); Block b = resultFuture.get(); assertEquals(b, b3); } @Test public void getLargeBlock() throws Exception { Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true)); connect(); Block b1 = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS).block; blockChain.add(b1); Block b2 = makeSolvedTestBlock(b1); Transaction t = new Transaction(); t.addInput(b1.getTransactions().get(0).getOutput(0)); t.addOutput(new TransactionOutput(t, Coin.ZERO, new byte[Block.MAX_BLOCK_SIZE - 1000])); b2.addTransaction(t); // Request the block. Future<Block> resultFuture = peer.getBlock(b2.getHash()); assertFalse(resultFuture.isDone()); // Peer asks for it. GetDataMessage message = (GetDataMessage) outbound(writeTarget); assertEquals(message.getItems().get(0).hash, b2.getHash()); assertFalse(resultFuture.isDone()); // Peer receives it. inbound(writeTarget, b2); Block b = resultFuture.get(); assertEquals(b, b2); } @Test public void fastCatchup() throws Exception { Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true)); connect(); TimeUtils.setMockClock(); // Check that blocks before the fast catchup point are retrieved using getheaders, and after using getblocks. // This test is INCOMPLETE because it does not check we handle >2000 blocks correctly. Block b1 = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS).block; blockChain.add(b1); TimeUtils.rollMockClock(Duration.ofMinutes(10)); // 10 minutes later. Block b2 = makeSolvedTestBlock(b1); b2.setTime(TimeUtils.currentTime()); b2.solve(); TimeUtils.rollMockClock(Duration.ofMinutes(10)); // 10 minutes later. Block b3 = makeSolvedTestBlock(b2); b3.setTime(TimeUtils.currentTime()); b3.solve(); TimeUtils.rollMockClock(Duration.ofMinutes(10)); Block b4 = makeSolvedTestBlock(b3); b4.setTime(TimeUtils.currentTime()); b4.solve(); // Request headers until the last 2 blocks. peer.setFastDownloadParameters( false, TimeUtils.currentTime().minusSeconds(600 * 2).plusSeconds(1) ); peer.startBlockChainDownload(); GetHeadersMessage getheaders = (GetHeadersMessage) outbound(writeTarget); BlockLocator expectedLocator = new BlockLocator(); expectedLocator = expectedLocator.add(b1.getHash()); expectedLocator = expectedLocator.add(TESTNET.getGenesisBlock().getHash()); assertEquals(getheaders.getLocator(), expectedLocator); assertEquals(getheaders.getStopHash(), Sha256Hash.ZERO_HASH); // Now send all the headers. HeadersMessage headers = new HeadersMessage(b2.cloneAsHeader(), b3.cloneAsHeader(), b4.cloneAsHeader()); // We expect to be asked for b3 and b4 again, but this time, with a body. expectedLocator = new BlockLocator(); expectedLocator = expectedLocator.add(b2.getHash()); expectedLocator = expectedLocator.add(b1.getHash()); expectedLocator = expectedLocator.add(TESTNET.getGenesisBlock().getHash()); inbound(writeTarget, headers); GetBlocksMessage getblocks = (GetBlocksMessage) outbound(writeTarget); assertEquals(expectedLocator, getblocks.getLocator()); assertEquals(Sha256Hash.ZERO_HASH, getblocks.getStopHash()); // We're supposed to get an inv here. InventoryMessage inv = new InventoryMessage(); inv.addItem(new InventoryItem(InventoryItem.Type.BLOCK, b3.getHash())); inbound(writeTarget, inv); GetDataMessage getdata = (GetDataMessage) outbound(writeTarget); assertEquals(b3.getHash(), getdata.getItems().get(0).hash); // All done. inbound(writeTarget, b3); pingAndWait(writeTarget); closePeer(peer); TimeUtils.clearMockClock(); } @Test public void pingPong() throws Exception { connect(); TimeUtils.setMockClock(); // No ping pong happened yet. assertFalse(peer.lastPingInterval().isPresent()); assertFalse(peer.pingInterval().isPresent()); CompletableFuture<Duration> future = peer.sendPing(); assertFalse(peer.lastPingInterval().isPresent()); assertFalse(peer.pingInterval().isPresent()); assertFalse(future.isDone()); Ping pingMsg = (Ping) outbound(writeTarget); TimeUtils.rollMockClock(Duration.ofSeconds(5)); // The pong is returned. inbound(writeTarget, pingMsg.pong()); pingAndWait(writeTarget); assertTrue(future.isDone()); Duration elapsed = future.get(); assertTrue(elapsed.toMillis() + " ms", elapsed.toMillis() > 1000); assertEquals(elapsed, peer.lastPingInterval().get()); assertEquals(elapsed, peer.pingInterval().get()); // Do it again and make sure it affects the average. CompletableFuture<Duration> future2 = peer.sendPing(); pingMsg = (Ping) outbound(writeTarget); TimeUtils.rollMockClock(Duration.ofSeconds(50)); inbound(writeTarget, pingMsg.pong()); Duration elapsed2 = future2.get(); assertEquals(elapsed2, peer.lastPingInterval().get()); assertEquals(Duration.ofMillis(7250), peer.pingInterval().get()); TimeUtils.clearMockClock(); } @Test public void recursiveDependencyDownloadDisabled() throws Exception { peer.setDownloadTxDependencies(false); connect(); // Check that if we request dependency download to be disabled and receive a relevant tx, things work correctly. Transaction tx = createFakeTx(TESTNET.network(), COIN, address); final Transaction[] result = new Transaction[1]; wallet.addCoinsReceivedEventListener((wallet, tx1, prevBalance, newBalance) -> result[0] = tx1); inbound(writeTarget, tx); pingAndWait(writeTarget); assertEquals(tx, result[0]); } @Test public void recursiveDependencyDownload() throws Exception { connect(); // Check that we can download all dependencies of an unconfirmed relevant transaction from the mempool. ECKey to = new ECKey(); final Transaction[] onTx = new Transaction[1]; peer.addOnTransactionBroadcastListener(Threading.SAME_THREAD, (peer1, t) -> onTx[0] = t); // Make some fake transactions in the following graph: // t1 -> t2 -> [t5] // -> t3 -> t4 -> [t6] // -> [t7] // -> [t8] // The ones in brackets are assumed to be in the chain and are represented only by hashes. Transaction t2 = createFakeTx(COIN, to); Sha256Hash t5hash = t2.getInput(0).getOutpoint().hash(); Transaction t4 = createFakeTx(COIN, new ECKey()); Sha256Hash t6hash = t4.getInput(0).getOutpoint().hash(); t4.addOutput(COIN, new ECKey()); Transaction t3 = new Transaction(); t3.addInput(t4.getOutput(0)); t3.addOutput(COIN, new ECKey()); Transaction t1 = new Transaction(); t1.addInput(t2.getOutput(0)); t1.addInput(t3.getOutput(0)); Sha256Hash t7hash = Sha256Hash.wrap("2b801dd82f01d17bbde881687bf72bc62e2faa8ab8133d36fcb8c3abe7459da6"); t1.addInput(new TransactionInput(t1, new byte[]{}, new TransactionOutPoint(0, t7hash))); Sha256Hash t8hash = Sha256Hash.wrap("3b801dd82f01d17bbde881687bf72bc62e2faa8ab8133d36fcb8c3abe7459da6"); t1.addInput(new TransactionInput(t1, new byte[]{}, new TransactionOutPoint(1, t8hash))); t1.addOutput(COIN, to); t1 = roundTripTransaction(t1); t2 = roundTripTransaction(t2); t3 = roundTripTransaction(t3); t4 = roundTripTransaction(t4); // Announce the first one. Wait for it to be downloaded. InventoryMessage inv = new InventoryMessage(); inv.addTransaction(t1); inbound(writeTarget, inv); GetDataMessage getdata = (GetDataMessage) outbound(writeTarget); Threading.waitForUserCode(); assertEquals(t1.getTxId(), getdata.getItems().get(0).hash); inbound(writeTarget, t1); pingAndWait(writeTarget); assertEquals(t1, onTx[0]); // We want its dependencies so ask for them. CompletableFuture<List<Transaction>> futures = peer.downloadDependencies(t1); assertFalse(futures.isDone()); // It will recursively ask for the dependencies of t1: t2, t3, t7, t8. getdata = (GetDataMessage) outbound(writeTarget); assertEquals(4, getdata.getItems().size()); assertEquals(t2.getTxId(), getdata.getItems().get(0).hash); assertEquals(t3.getTxId(), getdata.getItems().get(1).hash); assertEquals(t7hash, getdata.getItems().get(2).hash); assertEquals(t8hash, getdata.getItems().get(3).hash); // Deliver the requested transactions. inbound(writeTarget, t2); inbound(writeTarget, t3); NotFoundMessage notFound = new NotFoundMessage(); notFound.addItem(new InventoryItem(InventoryItem.Type.TRANSACTION, t7hash)); notFound.addItem(new InventoryItem(InventoryItem.Type.TRANSACTION, t8hash)); inbound(writeTarget, notFound); assertFalse(futures.isDone()); // It will recursively ask for the dependencies of t2: t5 and t4, but not t3 because it already found t4. getdata = (GetDataMessage) outbound(writeTarget); assertEquals(getdata.getItems().get(0).hash, t2.getInput(0).getOutpoint().hash()); // t5 isn't found and t4 is. notFound = new NotFoundMessage(); notFound.addItem(new InventoryItem(InventoryItem.Type.TRANSACTION, t5hash)); inbound(writeTarget, notFound); assertFalse(futures.isDone()); // Request t4 ... getdata = (GetDataMessage) outbound(writeTarget); assertEquals(t4.getTxId(), getdata.getItems().get(0).hash); inbound(writeTarget, t4); // Continue to explore the t4 branch and ask for t6, which is in the chain. getdata = (GetDataMessage) outbound(writeTarget); assertEquals(t6hash, getdata.getItems().get(0).hash); notFound = new NotFoundMessage(); notFound.addItem(new InventoryItem(InventoryItem.Type.TRANSACTION, t6hash)); inbound(writeTarget, notFound); pingAndWait(writeTarget); // That's it, we explored the entire tree. assertTrue(futures.isDone()); List<Transaction> results = futures.get(); assertEquals(3, results.size()); assertTrue(results.contains(t2)); assertTrue(results.contains(t3)); assertTrue(results.contains(t4)); } @Test public void recursiveDependencyDownload_depthLimited() throws Exception { peer.setDownloadTxDependencies(1); // Depth limit connect(); // Make some fake transactions in the following graph: // t1 -> t2 -> t3 -> [t4] // The ones in brackets are assumed to be in the chain and are represented only by hashes. Sha256Hash t4hash = Sha256Hash.wrap("2b801dd82f01d17bbde881687bf72bc62e2faa8ab8133d36fcb8c3abe7459da6"); Transaction t3 = new Transaction(); t3.addInput(new TransactionInput(t3, new byte[]{}, new TransactionOutPoint(0, t4hash))); t3.addOutput(COIN, new ECKey()); t3 = roundTripTransaction(t3); Transaction t2 = new Transaction(); t2.addInput(t3.getOutput(0)); t2.addOutput(COIN, new ECKey()); t2 = roundTripTransaction(t2); Transaction t1 = new Transaction(); t1.addInput(t2.getOutput(0)); t1.addOutput(COIN, new ECKey()); t1 = roundTripTransaction(t1); // Announce the first one. Wait for it to be downloaded. InventoryMessage inv = new InventoryMessage(); inv.addTransaction(t1); inbound(writeTarget, inv); GetDataMessage getdata = (GetDataMessage) outbound(writeTarget); Threading.waitForUserCode(); assertEquals(t1.getTxId(), getdata.getItems().get(0).hash); inbound(writeTarget, t1); pingAndWait(writeTarget); // We want its dependencies so ask for them. CompletableFuture<List<Transaction>> futures = peer.downloadDependencies(t1); assertFalse(futures.isDone()); // level 1 getdata = (GetDataMessage) outbound(writeTarget); assertEquals(1, getdata.getItems().size()); assertEquals(t2.getTxId(), getdata.getItems().get(0).hash); inbound(writeTarget, t2); // no level 2 getdata = (GetDataMessage) outbound(writeTarget); assertNull(getdata); // That's it, now double check what we've got pingAndWait(writeTarget); assertTrue(futures.isDone()); List<Transaction> results = futures.get(); assertEquals(1, results.size()); assertTrue(results.contains(t2)); } @Test public void timeLockedTransactionNew() throws Exception { connectWithVersion(70001, Services.NODE_NETWORK); // Test that if we receive a relevant transaction that has a lock time, it doesn't result in a notification // until we explicitly opt in to seeing those. Wallet wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH); ECKey key = wallet.freshReceiveKey(); peer.addWallet(wallet); final Transaction[] vtx = new Transaction[1]; wallet.addCoinsReceivedEventListener((wallet1, tx, prevBalance, newBalance) -> vtx[0] = tx); // Send a normal relevant transaction, it's received correctly. Transaction t1 = createFakeTx(COIN, key); inbound(writeTarget, t1); GetDataMessage getdata = (GetDataMessage) outbound(writeTarget); inbound(writeTarget, new NotFoundMessage(getdata.getItems())); pingAndWait(writeTarget); Threading.waitForUserCode(); assertNotNull(vtx[0]); vtx[0] = null; // Send a timelocked transaction, nothing happens. Transaction t2 = createFakeTx(valueOf(2, 0), key); t2.setLockTime(999999); inbound(writeTarget, t2); Threading.waitForUserCode(); assertNull(vtx[0]); // Now we want to hear about them. Send another, we are told about it. wallet.setAcceptRiskyTransactions(true); inbound(writeTarget, t2); getdata = (GetDataMessage) outbound(writeTarget); inbound(writeTarget, new NotFoundMessage(getdata.getItems())); pingAndWait(writeTarget); Threading.waitForUserCode(); assertEquals(t2, vtx[0]); } @Test public void rejectTimeLockedDependency() throws Exception { // Check that we also verify the lock times of dependencies. Otherwise an attacker could still build a tx that // looks legitimate and useful but won't actually ever confirm, by sending us a normal tx that spends a // timelocked tx. checkTimeLockedDependency(false); } @Test public void acceptTimeLockedDependency() throws Exception { checkTimeLockedDependency(true); } private void checkTimeLockedDependency(boolean shouldAccept) throws Exception { // Initial setup. connectWithVersion(70001, Services.NODE_NETWORK); Wallet wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH); ECKey key = wallet.freshReceiveKey(); wallet.setAcceptRiskyTransactions(shouldAccept); peer.addWallet(wallet); final Transaction[] vtx = new Transaction[1]; wallet.addCoinsReceivedEventListener((wallet1, tx, prevBalance, newBalance) -> vtx[0] = tx); // t1 -> t2 [locked] -> t3 (not available) Transaction t2 = new Transaction(); t2.setLockTime(999999); // Add a fake input to t3 that goes nowhere. Sha256Hash t3 = Sha256Hash.of("abc".getBytes(StandardCharsets.UTF_8)); t2.addInput(new TransactionInput(t2, new byte[]{}, new TransactionOutPoint(0, t3))); t2.getInput(0).setSequenceNumber(0xDEADBEEF); t2.addOutput(COIN, new ECKey()); Transaction t1 = new Transaction(); t1.addInput(t2.getOutput(0)); t1.addOutput(COIN, key); // Make it relevant. // Announce t1. InventoryMessage inv = new InventoryMessage(); inv.addTransaction(t1); inbound(writeTarget, inv); // Send it. GetDataMessage getdata = (GetDataMessage) outbound(writeTarget); assertEquals(t1.getTxId(), getdata.getItems().get(0).hash); inbound(writeTarget, t1); // Nothing arrived at our event listener yet. assertNull(vtx[0]); // We request t2. getdata = (GetDataMessage) outbound(writeTarget); assertEquals(t2.getTxId(), getdata.getItems().get(0).hash); inbound(writeTarget, t2); // We request t3. getdata = (GetDataMessage) outbound(writeTarget); assertEquals(t3, getdata.getItems().get(0).hash); // Can't find it: bottom of tree. NotFoundMessage notFound = new NotFoundMessage(); notFound.addItem(new InventoryItem(InventoryItem.Type.TRANSACTION, t3)); inbound(writeTarget, notFound); pingAndWait(writeTarget); Threading.waitForUserCode(); // We're done but still not notified because it was timelocked. if (shouldAccept) assertNotNull(vtx[0]); else assertNull(vtx[0]); } @Test public void disconnectOldVersions1() throws Exception { // Set up the connection with an old version. final CompletableFuture<Void> connectedFuture = new CompletableFuture<>(); final CompletableFuture<Void> disconnectedFuture = new CompletableFuture<>(); peer.addConnectedEventListener((peer, peerCount) -> connectedFuture.complete(null)); peer.addDisconnectedEventListener((peer, peerCount) -> disconnectedFuture.complete(null)); connectWithVersion(500, Services.NODE_NETWORK); // We must wait uninterruptibly here because connect[WithVersion] generates a peer that interrupts the current // thread when it disconnects. Uninterruptibles.getUninterruptibly(connectedFuture); Uninterruptibles.getUninterruptibly(disconnectedFuture); try { peer.writeTarget.writeBytes(new byte[1]); fail(); } catch (IOException e) { assertTrue((e.getCause() != null && e.getCause() instanceof CancelledKeyException) || (e instanceof SocketException && e.getMessage().equals("Socket is closed"))); } } @Test public void exceptionListener() throws Exception { wallet.addCoinsReceivedEventListener((wallet, tx, prevBalance, newBalance) -> { throw new NullPointerException("boo!"); }); final Throwable[] throwables = new Throwable[1]; Threading.uncaughtExceptionHandler = (thread, throwable) -> throwables[0] = throwable; // In real usage we're not really meant to adjust the uncaught exception handler after stuff started happening // but in the unit test environment other tests have just run so the thread is probably still kicking around. // Force it to crash so it'll be recreated with our new handler. Threading.USER_THREAD.execute(() -> { throw new RuntimeException(); }); connect(); Transaction t1 = new Transaction(); t1.addInput(new TransactionInput(t1, new byte[0], TransactionOutPoint.UNCONNECTED)); t1.addOutput(COIN, new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)); Transaction t2 = new Transaction(); t2.addInput(t1.getOutput(0)); t2.addOutput(COIN, wallet.currentChangeAddress()); inbound(writeTarget, t2); final InventoryItem inventoryItem = new InventoryItem(InventoryItem.Type.TRANSACTION, t2.getInput(0).getOutpoint().hash()); final NotFoundMessage nfm = new NotFoundMessage(Lists.newArrayList(inventoryItem)); inbound(writeTarget, nfm); pingAndWait(writeTarget); Threading.waitForUserCode(); assertTrue(throwables[0] instanceof NullPointerException); Threading.uncaughtExceptionHandler = null; } @Test public void badMessage() throws Exception { // Bring up an actual network connection and feed it bogus data. final CompletableFuture<Void> result = new CompletableFuture<>(); Threading.uncaughtExceptionHandler = (thread, throwable) -> result.completeExceptionally(throwable); connect(); // Writes out a verack+version. final CompletableFuture<Void> peerDisconnected = new CompletableFuture<>(); writeTarget.peer.addDisconnectedEventListener((p, peerCount) -> peerDisconnected.complete(null)); MessageSerializer serializer = TESTNET.getDefaultSerializer(); // Now write some bogus truncated message. ByteArrayOutputStream out = new ByteArrayOutputStream(); serializer.serialize("inv", new InventoryMessage() { @Override public void bitcoinSerializeToStream(OutputStream stream) throws IOException { // Add some hashes. addItem(new InventoryItem(InventoryItem.Type.TRANSACTION, Sha256Hash.of(new byte[] { 1 }))); addItem(new InventoryItem(InventoryItem.Type.TRANSACTION, Sha256Hash.of(new byte[] { 2 }))); addItem(new InventoryItem(InventoryItem.Type.TRANSACTION, Sha256Hash.of(new byte[] { 3 }))); // Write out a copy that's truncated in the middle. ByteArrayOutputStream bos = new ByteArrayOutputStream(); super.bitcoinSerializeToStream(bos); byte[] bits = bos.toByteArray(); bits = Arrays.copyOf(bits, bits.length / 2); stream.write(bits); } }.serialize(), out); writeTarget.writeTarget.writeBytes(out.toByteArray()); try { result.get(); fail(); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof ProtocolException); } peerDisconnected.get(); try { peer.writeTarget.writeBytes(new byte[1]); fail(); } catch (IOException e) { assertTrue((e.getCause() != null && e.getCause() instanceof CancelledKeyException) || (e instanceof SocketException && e.getMessage().equals("Socket is closed"))); } } }
40,629
44.857788
134
java
bitcoinj
bitcoinj-master/integration-test/src/test/java/org/bitcoinj/core/TransactionBroadcastTest.java
/* * Copyright 2013 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. */ package org.bitcoinj.core; import com.google.common.util.concurrent.AtomicDouble; import org.bitcoinj.base.Address; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.testing.FakeTxBuilder; import org.bitcoinj.testing.InboundMessageQueuer; import org.bitcoinj.testing.TestWithPeerGroup; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.SendRequest; import org.bitcoinj.wallet.Wallet; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import java.util.Objects; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import static org.bitcoinj.base.Coin.CENT; import static org.bitcoinj.base.Coin.COIN; import static org.bitcoinj.base.Coin.FIFTY_COINS; import static org.bitcoinj.base.Coin.valueOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @RunWith(value = Parameterized.class) public class TransactionBroadcastTest extends TestWithPeerGroup { @Parameterized.Parameters public static Collection<ClientType[]> parameters() { return Arrays.asList(new ClientType[] {ClientType.NIO_CLIENT_MANAGER}, new ClientType[] {ClientType.BLOCKING_CLIENT_MANAGER}); } public TransactionBroadcastTest(ClientType clientType) { super(clientType); } @Override @Before public void setUp() throws Exception { TimeUtils.setMockClock(); // Use mock clock super.setUp(); // Fix the random permutation that TransactionBroadcast uses to shuffle the peers. TransactionBroadcast.random = new Random(0); peerGroup.setMinBroadcastConnections(2); peerGroup.start(); } @Override @After public void tearDown() { super.tearDown(); TimeUtils.clearMockClock(); } @Test public void fourPeers() throws Exception { InboundMessageQueuer[] channels = { connectPeer(1), connectPeer(2), connectPeer(3), connectPeer(4) }; Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network()); tx.getConfidence().setSource(TransactionConfidence.Source.SELF); TransactionBroadcast broadcast = new TransactionBroadcast(peerGroup, tx); final AtomicDouble lastProgress = new AtomicDouble(); broadcast.setProgressCallback(lastProgress::set); CompletableFuture<TransactionBroadcast> future = broadcast.broadcastAndAwaitRelay(); assertFalse(future.isDone()); assertEquals(0.0, lastProgress.get(), 0.0); // We expect two peers to receive a tx message, and at least one of the others must announce for the future to // complete successfully. Message[] messages = { outbound(channels[0]), outbound(channels[1]), outbound(channels[2]), outbound(channels[3]) }; // 0 and 3 are randomly selected to receive the broadcast. assertEquals(tx, messages[0]); assertEquals(tx, messages[3]); assertNull(messages[1]); assertNull(messages[2]); Threading.waitForUserCode(); assertFalse(future.isDone()); assertEquals(0.0, lastProgress.get(), 0.0); inbound(channels[1], InventoryMessage.with(tx)); future.get(); Threading.waitForUserCode(); assertEquals(1.0, lastProgress.get(), 0.0); // There is no response from the Peer as it has nothing to do. assertNull(outbound(channels[1])); } @Test public void lateProgressCallback() throws Exception { // Check that if we register a progress callback on a broadcast after the broadcast has started, it's invoked // immediately with the latest state. This avoids API users writing accidentally racy code when they use // a convenience method like peerGroup.broadcastTransaction. InboundMessageQueuer[] channels = { connectPeer(1), connectPeer(2), connectPeer(3), connectPeer(4) }; Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network(), CENT, address); tx.getConfidence().setSource(TransactionConfidence.Source.SELF); TransactionBroadcast broadcast = peerGroup.broadcastTransaction(tx); inbound(channels[1], InventoryMessage.with(tx)); pingAndWait(channels[1]); final AtomicDouble p = new AtomicDouble(); broadcast.setProgressCallback(p::set, Threading.SAME_THREAD); assertEquals(1.0, p.get(), 0.01); } @Test public void rejectHandling() throws Exception { InboundMessageQueuer[] channels = { connectPeer(0), connectPeer(1), connectPeer(2), connectPeer(3), connectPeer(4) }; Transaction tx = FakeTxBuilder.createFakeTx(TESTNET.network()); TransactionBroadcast broadcast = new TransactionBroadcast(peerGroup, tx); CompletableFuture<TransactionBroadcast> future = broadcast.broadcastAndAwaitRelay(); // 0 and 3 are randomly selected to receive the broadcast. assertEquals(tx, outbound(channels[1])); assertEquals(tx, outbound(channels[2])); assertEquals(tx, outbound(channels[4])); RejectMessage reject = new RejectMessage(RejectMessage.RejectCode.DUST, tx.getTxId(), "tx", "dust"); inbound(channels[1], reject); inbound(channels[4], reject); try { future.get(); fail(); } catch (ExecutionException e) { assertEquals(RejectedTransactionException.class, e.getCause().getClass()); } } @Test public void retryFailedBroadcast() throws Exception { // If we create a spend, it's sent to a peer that swallows it, and the peergroup is removed/re-added then // the tx should be broadcast again. InboundMessageQueuer p1 = connectPeer(1); connectPeer(2); // Send ourselves a bit of money. Block b1 = FakeTxBuilder.makeSolvedTestBlock(blockStore, address); inbound(p1, b1); assertNull(outbound(p1)); assertEquals(FIFTY_COINS, wallet.getBalance()); // Now create a spend, and expect the announcement on p1. Address dest = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, dest, COIN); assertFalse(sendResult.awaitRelayed().isDone()); Transaction t1; { Message m; while (!((m = outbound(p1)) instanceof Transaction)); t1 = (Transaction) m; } assertFalse(sendResult.awaitRelayed().isDone()); // p1 eats it :( A bit later the PeerGroup is taken down. peerGroup.removeWallet(wallet); peerGroup.addWallet(wallet); // We want to hear about it again. Now, because we've disabled the randomness for the unit tests it will // re-appear on p1 again. Of course in the real world it would end up with a different set of peers and // select randomly so we get a second chance. Transaction t2 = (Transaction) outbound(p1); assertEquals(t1, t2); } @Test public void peerGroupWalletIntegration() throws Exception { // Make sure we can create spends, and that they are announced. Then do the same with offline mode. // Set up connections and block chain. VersionMessage ver = new VersionMessage(TESTNET, 2); ver.localServices = Services.of(Services.NODE_NETWORK); InboundMessageQueuer p1 = connectPeer(1, ver); InboundMessageQueuer p2 = connectPeer(2); // Send ourselves a bit of money. Block b1 = FakeTxBuilder.makeSolvedTestBlock(blockStore, address); inbound(p1, b1); pingAndWait(p1); assertNull(outbound(p1)); assertEquals(FIFTY_COINS, wallet.getBalance()); // Check that the wallet informs us of changes in confidence as the transaction ripples across the network. final Transaction[] transactions = new Transaction[1]; wallet.addTransactionConfidenceEventListener((wallet, tx) -> transactions[0] = tx); // Now create a spend, and expect the announcement on p1. Address dest = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET); Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, dest, COIN); assertNotNull(sendResult.transaction()); Threading.waitForUserCode(); assertFalse(sendResult.awaitRelayed().isDone()); assertEquals(transactions[0], sendResult.transaction()); assertEquals(0, transactions[0].getConfidence().numBroadcastPeers()); transactions[0] = null; Transaction t1; { peerGroup.waitForJobQueue(); Message m = outbound(p1); // Hack: bloom filters are recalculated asynchronously to sending transactions to avoid lock // inversion, so we might or might not get the filter/mempool message first or second. while (!(m instanceof Transaction)) m = outbound(p1); t1 = (Transaction) m; } assertNotNull(t1); // 49 BTC in change. assertEquals(valueOf(49, 0), t1.getValueSentToMe(wallet)); // The future won't complete until it's heard back from the network on p2. InventoryMessage inv = new InventoryMessage(); inv.addTransaction(t1); inbound(p2, inv); pingAndWait(p2); Threading.waitForUserCode(); assertTrue(sendResult.awaitRelayed().isDone()); assertEquals(transactions[0], sendResult.transaction()); assertEquals(1, transactions[0].getConfidence().numBroadcastPeers()); // Confirm it. Block b2 = FakeTxBuilder.createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS, t1).block; inbound(p1, b2); pingAndWait(p1); assertNull(outbound(p1)); // Do the same thing with an offline transaction. peerGroup.removeWallet(wallet); SendRequest req = SendRequest.to(dest, valueOf(2, 0)); Transaction t3 = Objects.requireNonNull(wallet.sendCoinsOffline(req)); assertNull(outbound(p1)); // Nothing sent. // Add the wallet to the peer group (simulate initialization). Transactions should be announced. peerGroup.addWallet(wallet); // Transaction announced to the first peer. No extra Bloom filter because no change address was needed. assertEquals(t3.getTxId(), ((Transaction) outbound(p1)).getTxId()); } }
11,539
43.045802
125
java
bitcoinj
bitcoinj-master/integration-test/src/test/java/org/bitcoinj/core/PeerGroupTest.java
/* * 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. */ package org.bitcoinj.core; import com.google.common.collect.Lists; import org.bitcoinj.base.Address; import org.bitcoinj.base.Coin; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.internal.Stopwatch; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.core.listeners.DownloadProgressTracker; import org.bitcoinj.core.listeners.PeerConnectedEventListener; import org.bitcoinj.core.listeners.PeerDisconnectedEventListener; import org.bitcoinj.core.listeners.PreMessageReceivedEventListener; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.net.discovery.PeerDiscovery; import org.bitcoinj.net.discovery.PeerDiscoveryException; import org.bitcoinj.testing.FakeTxBuilder; import org.bitcoinj.testing.InboundMessageQueuer; import org.bitcoinj.testing.TestWithPeerGroup; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.Wallet; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import java.net.BindException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.nio.ByteBuffer; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static org.bitcoinj.base.Coin.COIN; import static org.bitcoinj.base.Coin.valueOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; // TX announcement and broadcast is tested in TransactionBroadcastTest. @RunWith(value = Parameterized.class) public class PeerGroupTest extends TestWithPeerGroup { private static final int BLOCK_HEIGHT_GENESIS = 0; private BlockingQueue<Peer> connectedPeers; private BlockingQueue<Peer> disconnectedPeers; private PeerConnectedEventListener connectedListener = new PeerConnectedEventListener() { @Override public void onPeerConnected(Peer peer, int peerCount) { connectedPeers.add(peer); } }; private PeerDisconnectedEventListener disconnectedListener = new PeerDisconnectedEventListener() { @Override public void onPeerDisconnected(Peer peer, int peerCount) { disconnectedPeers.add(peer); } }; private PreMessageReceivedEventListener preMessageReceivedListener; private Map<Peer, AtomicInteger> peerToMessageCount; @Parameterized.Parameters public static Collection<ClientType[]> parameters() { return Arrays.asList(new ClientType[] {ClientType.NIO_CLIENT_MANAGER}, new ClientType[] {ClientType.BLOCKING_CLIENT_MANAGER}); } public PeerGroupTest(ClientType clientType) { super(clientType); } @Override @Before public void setUp() throws Exception { super.setUp(); peerToMessageCount = new HashMap<>(); connectedPeers = new LinkedBlockingQueue<>(); disconnectedPeers = new LinkedBlockingQueue<>(); preMessageReceivedListener = (peer, m) -> { AtomicInteger messageCount = peerToMessageCount.get(peer); if (messageCount == null) { messageCount = new AtomicInteger(0); peerToMessageCount.put(peer, messageCount); } messageCount.incrementAndGet(); // Just pass the message right through for further processing. return m; }; } @Override @After public void tearDown() { super.tearDown(); } @Test public void listener() throws Exception { peerGroup.addConnectedEventListener(connectedListener); peerGroup.addDisconnectedEventListener(disconnectedListener); peerGroup.addPreMessageReceivedEventListener(preMessageReceivedListener); peerGroup.start(); // Create a couple of peers. InboundMessageQueuer p1 = connectPeer(1); InboundMessageQueuer p2 = connectPeer(2); connectedPeers.take(); connectedPeers.take(); pingAndWait(p1); pingAndWait(p2); Threading.waitForUserCode(); assertEquals(0, disconnectedPeers.size()); p1.close(); disconnectedPeers.take(); assertEquals(0, disconnectedPeers.size()); p2.close(); disconnectedPeers.take(); assertEquals(0, disconnectedPeers.size()); assertTrue(peerGroup.removeConnectedEventListener(connectedListener)); assertFalse(peerGroup.removeConnectedEventListener(connectedListener)); assertTrue(peerGroup.removeDisconnectedEventListener(disconnectedListener)); assertFalse(peerGroup.removeDisconnectedEventListener(disconnectedListener)); assertTrue(peerGroup.removePreMessageReceivedEventListener(preMessageReceivedListener)); assertFalse(peerGroup.removePreMessageReceivedEventListener(preMessageReceivedListener)); } @Test public void peerDiscoveryPolling() throws InterruptedException { // Check that if peer discovery fails, we keep trying until we have some nodes to talk with. final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean result = new AtomicBoolean(); peerGroup.addPeerDiscovery(new PeerDiscovery() { @Override public List<InetSocketAddress> getPeers(long services, Duration unused) throws PeerDiscoveryException { if (!result.getAndSet(true)) { // Pretend we are not connected to the internet. throw new PeerDiscoveryException("test failure"); } else { // Return a bogus address. latch.countDown(); return Arrays.asList(new InetSocketAddress("localhost", 1)); } } @Override public void shutdown() { } }); peerGroup.start(); latch.await(); // Check that we did indeed throw an exception. If we got here it means we threw and then PeerGroup tried // again a bit later. assertTrue(result.get()); } // Utility method to create a PeerDiscovery with a certain number of addresses. private PeerDiscovery createPeerDiscovery(int nrOfAddressesWanted, int port) { final List<InetSocketAddress> addresses = new ArrayList<>(nrOfAddressesWanted); for (int addressNr = 0; addressNr < nrOfAddressesWanted; addressNr++) { // make each address unique by using the counter to increment the port. addresses.add(new InetSocketAddress("localhost", port + addressNr)); } return new PeerDiscovery() { public List<InetSocketAddress> getPeers(long services, Duration unused) throws PeerDiscoveryException { return addresses; } public void shutdown() { } }; } @Test public void multiplePeerDiscovery() { peerGroup.setMaxPeersToDiscoverCount(98); peerGroup.addPeerDiscovery(createPeerDiscovery(1, 0)); peerGroup.addPeerDiscovery(createPeerDiscovery(2, 100)); peerGroup.addPeerDiscovery(createPeerDiscovery(96, 200)); peerGroup.addPeerDiscovery(createPeerDiscovery(3, 300)); peerGroup.addPeerDiscovery(createPeerDiscovery(1, 400)); peerGroup.addDiscoveredEventListener(peerAddresses -> assertEquals(99, peerAddresses.size())); peerGroup.start(); } @Test public void receiveTxBroadcast() throws Exception { // Check that when we receive transactions on all our peers, we do the right thing. peerGroup.start(); // Create a couple of peers. InboundMessageQueuer p1 = connectPeer(1); InboundMessageQueuer p2 = connectPeer(2); // Check the peer accessors. assertEquals(2, peerGroup.numConnectedPeers()); Set<Peer> tmp = new HashSet<>(peerGroup.getConnectedPeers()); Set<Peer> expectedPeers = new HashSet<>(); expectedPeers.add(peerOf(p1)); expectedPeers.add(peerOf(p2)); assertEquals(tmp, expectedPeers); Coin value = COIN; Transaction t1 = FakeTxBuilder.createFakeTx(UNITTEST.network(), value, address); InventoryMessage inv = new InventoryMessage(); inv.addTransaction(t1); // Note: we start with p2 here to verify that transactions are downloaded from whichever peer announces first // which does not have to be the same as the download peer (which is really the "block download peer"). inbound(p2, inv); assertTrue(outbound(p2) instanceof GetDataMessage); inbound(p1, inv); assertNull(outbound(p1)); // Only one peer is used to download. inbound(p2, t1); assertNull(outbound(p1)); // Asks for dependency. GetDataMessage getdata = (GetDataMessage) outbound(p2); assertNotNull(getdata); inbound(p2, new NotFoundMessage(getdata.getItems())); pingAndWait(p2); assertEquals(value, wallet.getBalance(Wallet.BalanceType.ESTIMATED)); } @Test public void receiveTxBroadcastOnAddedWallet() throws Exception { // Check that when we receive transactions on all our peers, we do the right thing. peerGroup.start(); // Create a peer. InboundMessageQueuer p1 = connectPeer(1); Wallet wallet2 = Wallet.createDeterministic(UNITTEST.network(), ScriptType.P2PKH); ECKey key2 = wallet2.freshReceiveKey(); Address address2 = key2.toAddress(ScriptType.P2PKH, UNITTEST.network()); peerGroup.addWallet(wallet2); blockChain.addWallet(wallet2); assertEquals(BloomFilter.class, waitForOutbound(p1).getClass()); assertEquals(MemoryPoolMessage.class, waitForOutbound(p1).getClass()); Coin value = COIN; Transaction t1 = FakeTxBuilder.createFakeTx(UNITTEST.network(), value, address2); InventoryMessage inv = new InventoryMessage(); inv.addTransaction(t1); inbound(p1, inv); assertTrue(outbound(p1) instanceof GetDataMessage); inbound(p1, t1); // Asks for dependency. GetDataMessage getdata = (GetDataMessage) outbound(p1); assertNotNull(getdata); inbound(p1, new NotFoundMessage(getdata.getItems())); pingAndWait(p1); assertEquals(value, wallet2.getBalance(Wallet.BalanceType.ESTIMATED)); } @Test public void singleDownloadPeer1() throws Exception { // Check that we don't attempt to retrieve blocks on multiple peers. peerGroup.start(); // Create a couple of peers. InboundMessageQueuer p1 = connectPeer(1); InboundMessageQueuer p2 = connectPeer(2); assertEquals(2, peerGroup.numConnectedPeers()); // Set up a little block chain. We heard about b1 but not b2 (it is pending download). b3 is solved whilst we // are downloading the chain. Block b1 = FakeTxBuilder.createFakeBlock(blockStore, BLOCK_HEIGHT_GENESIS).block; blockChain.add(b1); Block b2 = FakeTxBuilder.makeSolvedTestBlock(b1); Block b3 = FakeTxBuilder.makeSolvedTestBlock(b2); // Peer 1 and 2 receives an inv advertising a newly solved block. InventoryMessage inv = new InventoryMessage(); inv.addBlock(b3); // Only peer 1 tries to download it. inbound(p1, inv); pingAndWait(p1); assertTrue(outbound(p1) instanceof GetDataMessage); assertNull(outbound(p2)); // Peer 1 goes away, peer 2 becomes the download peer and thus queries the remote mempool. final CompletableFuture<Void> p1CloseFuture = new CompletableFuture<>(); peerOf(p1).addDisconnectedEventListener((peer, peerCount) -> p1CloseFuture.complete(null)); closePeer(peerOf(p1)); p1CloseFuture.get(); // Peer 2 fetches it next time it hears an inv (should it fetch immediately?). inbound(p2, inv); assertTrue(outbound(p2) instanceof GetDataMessage); } @Test public void singleDownloadPeer2() throws Exception { // Check that we don't attempt multiple simultaneous block chain downloads, when adding a new peer in the // middle of an existing chain download. // Create a couple of peers. peerGroup.start(); // Create a couple of peers. InboundMessageQueuer p1 = connectPeer(1); // Set up a little block chain. Block b1 = FakeTxBuilder.createFakeBlock(blockStore, BLOCK_HEIGHT_GENESIS).block; Block b2 = FakeTxBuilder.makeSolvedTestBlock(b1); Block b3 = FakeTxBuilder.makeSolvedTestBlock(b2); // Expect a zero hash getblocks on p1. This is how the process starts. peerGroup.startBlockChainDownload(new DownloadProgressTracker()); peerGroup.startBlockChainDownloadFromPeer(peerGroup.getConnectedPeers().iterator().next()); GetBlocksMessage getblocks = (GetBlocksMessage) outbound(p1); assertEquals(Sha256Hash.ZERO_HASH, getblocks.getStopHash()); // We give back an inv with some blocks in it. InventoryMessage inv = new InventoryMessage(); inv.addBlock(b1); inv.addBlock(b2); inv.addBlock(b3); inbound(p1, inv); assertTrue(outbound(p1) instanceof GetDataMessage); // We hand back the first block. inbound(p1, b1); // Now we successfully connect to another peer. There should be no messages sent. InboundMessageQueuer p2 = connectPeer(2); Message message = outbound(p2); assertNull(message == null ? "" : message.toString(), message); } @Test public void transactionConfidence() throws Exception { // Checks that we correctly count how many peers broadcast a transaction, so we can establish some measure of // its trustworthyness assuming an untampered with internet connection. peerGroup.start(); final Transaction[] event = new Transaction[1]; final TransactionConfidence[] confEvent = new TransactionConfidence[1]; peerGroup.addOnTransactionBroadcastListener(Threading.SAME_THREAD, (peer, t) -> event[0] = t); InboundMessageQueuer p1 = connectPeer(1); InboundMessageQueuer p2 = connectPeer(2); InboundMessageQueuer p3 = connectPeer(3); Transaction tx = FakeTxBuilder.createFakeTx(UNITTEST.network(), valueOf(20, 0), address); InventoryMessage inv = new InventoryMessage(); inv.addTransaction(tx); assertEquals(0, tx.getConfidence().numBroadcastPeers()); assertFalse(tx.getConfidence().lastBroadcastTime().isPresent()); // Peer 2 advertises the tx but does not receive it yet. inbound(p2, inv); assertTrue(outbound(p2) instanceof GetDataMessage); assertEquals(1, tx.getConfidence().numBroadcastPeers()); assertNull(event[0]); // Peer 1 advertises the tx, we don't do anything as it's already been requested. inbound(p1, inv); assertNull(outbound(p1)); // Peer 2 gets sent the tx and requests the dependency. inbound(p2, tx); assertTrue(outbound(p2) instanceof GetDataMessage); tx = event[0]; // We want to use the canonical copy delivered by the PeerGroup from now on. assertNotNull(tx); event[0] = null; // Peer 1 (the download peer) advertises the tx, we download it. inbound(p1, inv); // returns getdata inbound(p1, tx); // returns nothing after a queue drain. // Two peers saw this tx hash. assertEquals(2, tx.getConfidence().numBroadcastPeers()); assertTrue(tx.getConfidence().wasBroadcastBy(peerOf(p1).getAddress())); assertTrue(tx.getConfidence().wasBroadcastBy(peerOf(p2).getAddress())); assertTrue(tx.getConfidence().lastBroadcastTime().isPresent()); tx.getConfidence().addEventListener((confidence, reason) -> confEvent[0] = confidence); // A straggler reports in. inbound(p3, inv); pingAndWait(p3); Threading.waitForUserCode(); assertEquals(tx.getTxId(), confEvent[0].getTransactionHash()); assertEquals(3, tx.getConfidence().numBroadcastPeers()); assertTrue(tx.getConfidence().wasBroadcastBy(peerOf(p3).getAddress())); } @Test public void testWalletCatchupTime() { // Check the fast catchup time was initialized to something around the current runtime minus a week. // The wallet was already added to the peer in setup. final int WEEK = 86400 * 7; final Instant now = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS); peerGroup.start(); assertTrue(peerGroup.fastCatchupTime().isAfter(now.minusSeconds(WEEK).minusSeconds(10000))); Wallet w2 = Wallet.createDeterministic(UNITTEST.network(), ScriptType.P2PKH); ECKey key1 = new ECKey(); key1.setCreationTime(now.minus(1, ChronoUnit.DAYS)); // One day ago. w2.importKey(key1); peerGroup.addWallet(w2); peerGroup.waitForJobQueue(); assertEquals(peerGroup.fastCatchupTime(), now.minusSeconds(86400).minusSeconds(WEEK)); // Adding a key to the wallet should update the fast catchup time, but asynchronously and in the background // due to the need to avoid complicated lock inversions. ECKey key2 = new ECKey(); key2.setCreationTime(now.minusSeconds(100000)); w2.importKey(key2); peerGroup.waitForJobQueue(); assertEquals(peerGroup.fastCatchupTime(),now.minusSeconds(WEEK).minusSeconds(100000)); } @Test public void noPings() throws Exception { peerGroup.start(); peerGroup.setPingIntervalMsec(0); VersionMessage versionMessage = new VersionMessage(UNITTEST, 2); versionMessage.clientVersion = ProtocolVersion.BLOOM_FILTER.intValue(); versionMessage.localServices = Services.of(Services.NODE_NETWORK); connectPeer(1, versionMessage); peerGroup.waitForPeers(1).get(); assertFalse(peerGroup.getConnectedPeers().get(0).lastPingInterval().isPresent()); } @Test public void pings() throws Exception { peerGroup.start(); peerGroup.setPingIntervalMsec(100); VersionMessage versionMessage = new VersionMessage(UNITTEST, 2); versionMessage.clientVersion = ProtocolVersion.BLOOM_FILTER.intValue(); versionMessage.localServices = Services.of(Services.NODE_NETWORK); InboundMessageQueuer p1 = connectPeer(1, versionMessage); Ping ping = (Ping) waitForOutbound(p1); inbound(p1, ping.pong()); pingAndWait(p1); assertTrue(peerGroup.getConnectedPeers().get(0).lastPingInterval().isPresent()); // The call to outbound should block until a ping arrives. ping = (Ping) waitForOutbound(p1); inbound(p1, ping.pong()); assertTrue(peerGroup.getConnectedPeers().get(0).lastPingInterval().isPresent()); } @Test public void downloadPeerSelection() throws Exception { peerGroup.start(); VersionMessage v1 = new VersionMessage(UNITTEST, 2); v1.clientVersion = ProtocolVersion.WITNESS_VERSION.intValue(); v1.localServices = Services.of(Services.NODE_NETWORK | Services.NODE_BLOOM | Services.NODE_WITNESS); VersionMessage v2 = new VersionMessage(UNITTEST, 4); v2.clientVersion = ProtocolVersion.WITNESS_VERSION.intValue(); v2.localServices = Services.of(Services.NODE_NETWORK | Services.NODE_BLOOM | Services.NODE_WITNESS); assertNull(peerGroup.getDownloadPeer()); Peer p1 = connectPeer(0, v1).peer; assertEquals(2, peerGroup.getMostCommonChainHeight()); assertEquals(2, peerGroup.selectDownloadPeer(peerGroup.getConnectedPeers()).getBestHeight()); assertEquals(p1, peerGroup.getDownloadPeer()); connectPeer(1, v1); assertEquals(2, peerGroup.getMostCommonChainHeight()); // No change. assertEquals(2, peerGroup.selectDownloadPeer(peerGroup.getConnectedPeers()).getBestHeight()); Peer p2 = connectPeer(2, v2).peer; assertEquals(2, peerGroup.getMostCommonChainHeight()); // No change yet. assertEquals(2, peerGroup.selectDownloadPeer(peerGroup.getConnectedPeers()).getBestHeight()); connectPeer(3, v2); assertEquals(0, peerGroup.getMostCommonChainHeight()); // Most common height tied between two... assertNull(peerGroup.selectDownloadPeer(peerGroup.getConnectedPeers())); // ...so no peer would be selected. connectPeer(4, v2); assertEquals(4, peerGroup.getMostCommonChainHeight()); // Now we have a new winner... assertEquals(4, peerGroup.selectDownloadPeer(peerGroup.getConnectedPeers()).getBestHeight()); assertEquals(p1, peerGroup.getDownloadPeer()); // ...but the download peer doesn't change unless it misbehaves. // New peer with a higher protocol version but same chain height. // TODO: When PeerGroup.selectDownloadPeer.PREFERRED_VERSION is not equal to vMinRequiredProtocolVersion, // reenable this test /*VersionMessage versionMessage4 = new VersionMessage(UNITTEST, 3); versionMessage4.clientVersion = 100000; versionMessage4.localServices = Services.NODE_NETWORK; InboundMessageQueuer d = connectPeer(5, versionMessage4); assertEquals(d.peer, peerGroup.getDownloadPeer());*/ } @Test public void peerTimeoutTest() throws Exception { final Duration timeout = Duration.ofMillis(100); peerGroup.start(); peerGroup.setConnectTimeout(timeout); final CompletableFuture<Void> peerConnectedFuture = new CompletableFuture<>(); final CompletableFuture<Void> peerDisconnectedFuture = new CompletableFuture<>(); peerGroup.addConnectedEventListener(Threading.SAME_THREAD, (peer, peerCount) -> peerConnectedFuture.complete(null)); peerGroup.addDisconnectedEventListener(Threading.SAME_THREAD, (peer, peerCount) -> peerDisconnectedFuture.complete(null)); // connect to peer but don't do handshake Stopwatch watch = Stopwatch.start(); // before connection so we don't get elapsed < timeout connectPeerWithoutVersionExchange(0); // wait for disconnect (plus a bit more, in case test server is overloaded) try { peerDisconnectedFuture.get(timeout.plusMillis(200).toMillis(), TimeUnit.MILLISECONDS); } catch (TimeoutException e) { // the checks below suffice for this case too } // check things after disconnect assertFalse(peerConnectedFuture.isDone()); // should never have connected watch.stop(); assertTrue(watch.toString(), watch.elapsed().compareTo(timeout) >= 0); // should not disconnect before timeout assertTrue(peerDisconnectedFuture.isDone()); // but should disconnect eventually } @Test @Ignore("disabled for now as this test is too flaky") public void peerPriority() throws Exception { final List<InetSocketAddress> addresses = Lists.newArrayList( new InetSocketAddress("localhost", 2000), new InetSocketAddress("localhost", 2001), new InetSocketAddress("localhost", 2002) ); peerGroup.addConnectedEventListener(connectedListener); peerGroup.addDisconnectedEventListener(disconnectedListener); peerGroup.addPreMessageReceivedEventListener(preMessageReceivedListener); peerGroup.addPeerDiscovery(new PeerDiscovery() { @Override public List<InetSocketAddress> getPeers(long services, Duration unused) throws PeerDiscoveryException { return addresses; } @Override public void shutdown() { } }); peerGroup.setMaxConnections(3); blockJobs = true; jobBlocks.release(2); // startup + first peer discovery peerGroup.start(); jobBlocks.release(3); // One for each peer. handleConnectToPeer(0); handleConnectToPeer(1); handleConnectToPeer(2); connectedPeers.take(); connectedPeers.take(); connectedPeers.take(); addresses.clear(); addresses.addAll(Lists.newArrayList(new InetSocketAddress("localhost", 2003))); stopPeerServer(2); assertEquals(2002, disconnectedPeers.take().getAddress().getPort()); // peer died // discovers, connects to new peer jobBlocks.release(1); handleConnectToPeer(3); assertEquals(2003, connectedPeers.take().getAddress().getPort()); stopPeerServer(1); assertEquals(2001, disconnectedPeers.take().getAddress().getPort()); // peer died // Alternates trying two offline peers jobBlocks.release(10); assertEquals(2001, disconnectedPeers.take().getAddress().getPort()); assertEquals(2002, disconnectedPeers.take().getAddress().getPort()); assertEquals(2001, disconnectedPeers.take().getAddress().getPort()); assertEquals(2002, disconnectedPeers.take().getAddress().getPort()); assertEquals(2001, disconnectedPeers.take().getAddress().getPort()); // Peer 2 comes online startPeerServer(2); jobBlocks.release(1); handleConnectToPeer(2); assertEquals(2002, connectedPeers.take().getAddress().getPort()); jobBlocks.release(6); stopPeerServer(2); assertEquals(2002, disconnectedPeers.take().getAddress().getPort()); // peer died // Peer 2 is tried before peer 1, since it has a lower backoff due to recent success assertEquals(2002, disconnectedPeers.take().getAddress().getPort()); assertEquals(2001, disconnectedPeers.take().getAddress().getPort()); } @Test public void testBloomOnP2PK() throws Exception { // Cover GitHub bug #879. When a relevant transaction with a P2PK output is found, the Bloom filter should be // recalculated to include that transaction hash but not re-broadcast as the remote nodes should have followed // the same procedure. However a new node that's connected should get the fresh filter. peerGroup.start(); final ECKey key = wallet.currentReceiveKey(); // Create a couple of peers. InboundMessageQueuer p1 = connectPeer(1); InboundMessageQueuer p2 = connectPeer(2); // Create a P2PK tx. Transaction tx = FakeTxBuilder.createFakeTx(COIN, key); Transaction tx2 = new Transaction(); tx2.addInput(tx.getOutput(0)); TransactionOutPoint outpoint = tx2.getInput(0).getOutpoint(); assertTrue(p1.lastReceivedFilter.contains(key.getPubKey())); assertTrue(p1.lastReceivedFilter.contains(key.getPubKeyHash())); assertFalse(p1.lastReceivedFilter.contains(tx.getTxId().getBytes())); inbound(p1, tx); // p1 requests dep resolution, p2 is quiet. assertTrue(outbound(p1) instanceof GetDataMessage); final Sha256Hash dephash = tx.getInput(0).getOutpoint().hash(); final InventoryItem inv = new InventoryItem(InventoryItem.Type.TRANSACTION, dephash); inbound(p1, new NotFoundMessage(Collections.singletonList(inv))); assertNull(outbound(p1)); assertNull(outbound(p2)); peerGroup.waitForJobQueue(); // Now we connect p3 and there is a new bloom filter sent, that DOES match the relevant outpoint. InboundMessageQueuer p3 = connectPeer(3); assertTrue(p3.lastReceivedFilter.contains(key.getPubKey())); assertTrue(p3.lastReceivedFilter.contains(key.getPubKeyHash())); assertTrue(p3.lastReceivedFilter.contains(outpoint.serialize())); } @Test public void testBloomResendOnNewKey() throws Exception { // Check that when we add a new key to the wallet, the Bloom filter is re-calculated and re-sent but only once // we exceed the lookahead threshold. peerGroup.start(); // Create a couple of peers. InboundMessageQueuer p1 = connectPeer(1); InboundMessageQueuer p2 = connectPeer(2); peerGroup.waitForJobQueue(); BloomFilter f1 = p1.lastReceivedFilter; ECKey key = null; // We have to run ahead of the lookahead zone for this test. There should only be one bloom filter recalc. for (int i = 0; i < wallet.getKeyChainGroupLookaheadSize() + wallet.getKeyChainGroupLookaheadThreshold() + 1; i++) { key = wallet.freshReceiveKey(); } peerGroup.waitForJobQueue(); BloomFilter bf, f2 = null; while ((bf = (BloomFilter) outbound(p1)) != null) { assertEquals(MemoryPoolMessage.class, outbound(p1).getClass()); f2 = bf; } assertNotNull(key); assertNotNull(f2); assertNull(outbound(p1)); // Check the last filter received. assertNotEquals(f1, f2); assertTrue(f2.contains(key.getPubKey())); assertTrue(f2.contains(key.getPubKeyHash())); assertFalse(f1.contains(key.getPubKey())); assertFalse(f1.contains(key.getPubKeyHash())); } @Test public void waitForNumPeers1() throws Exception { CompletableFuture<List<Peer>> future = peerGroup.waitForPeers(3); peerGroup.start(); assertFalse(future.isDone()); connectPeer(1); assertFalse(future.isDone()); connectPeer(2); assertFalse(future.isDone()); assertTrue(peerGroup.waitForPeers(2).isDone()); // Immediate completion. connectPeer(3); future.get(); assertTrue(future.isDone()); } @Test public void waitForPeersOfVersion() throws Exception { final int bip37ver = ProtocolVersion.BLOOM_FILTER.intValue(); final int bip111ver = ProtocolVersion.BLOOM_FILTER_BIP111.intValue(); CompletableFuture<List<Peer>> future = peerGroup.waitForPeersOfVersion(2, bip111ver); VersionMessage ver1 = new VersionMessage(UNITTEST, 10); ver1.clientVersion = bip37ver; ver1.localServices = Services.of(Services.NODE_NETWORK); VersionMessage ver2 = new VersionMessage(UNITTEST, 10); ver2.clientVersion = bip111ver; ver2.localServices = Services.of(Services.NODE_NETWORK | Services.NODE_BLOOM); peerGroup.start(); assertFalse(future.isDone()); connectPeer(1, ver1); assertFalse(future.isDone()); connectPeer(2, ver2); assertFalse(future.isDone()); assertTrue(peerGroup.waitForPeersOfVersion(1, bip111ver).isDone()); // Immediate completion. connectPeer(3, ver2); future.get(); assertTrue(future.isDone()); } @Test public void waitForPeersWithServiceFlags() throws Exception { CompletableFuture<List<Peer>> future = peerGroup.waitForPeersWithServiceMask(2, 3); VersionMessage ver1 = new VersionMessage(UNITTEST, 10); ver1.clientVersion = 70001; ver1.localServices = Services.of(Services.NODE_NETWORK); VersionMessage ver2 = new VersionMessage(UNITTEST, 10); ver2.clientVersion = 70001; ver2.localServices = Services.of(Services.NODE_NETWORK | 2); peerGroup.start(); assertFalse(future.isDone()); connectPeer(1, ver1); assertTrue(peerGroup.findPeersWithServiceMask(3).isEmpty()); assertFalse(future.isDone()); connectPeer(2, ver2); assertFalse(future.isDone()); assertEquals(1, peerGroup.findPeersWithServiceMask(3).size()); assertTrue(peerGroup.waitForPeersWithServiceMask(1, 0x3).isDone()); // Immediate completion. connectPeer(3, ver2); future.get(); assertTrue(future.isDone()); peerGroup.stop(); } @Test public void preferLocalPeer() throws IOException { // Because we are using the same port (8333 or 18333) that is used by Bitcoin Core // We have to consider 2 cases: // 1. Test are executed on the same machine that is running a full node // 2. Test are executed without any full node running locally // We have to avoid to connecting to real and external services in unit tests // So we skip this test in case we have already something running on port UNITTEST.getPort() // Check that if we have a localhost port 8333 or 18333 then it's used instead of the p2p network. ServerSocket local = null; try { local = new ServerSocket(UNITTEST.getPort(), 100, InetAddress.getLoopbackAddress()); } catch(BindException e) { // Port already in use, skipping this test. return; } try { peerGroup.setUseLocalhostPeerWhenPossible(true); peerGroup.start(); local.accept().close(); // Probe connect local.accept(); // Real connect // If we get here it used the local peer. Check no others are in use. assertEquals(1, peerGroup.getMaxConnections()); assertEquals(PeerAddress.localhost(UNITTEST), peerGroup.getPendingPeers().get(0).getAddress()); } finally { local.close(); } } private <T extends Message> T assertNextMessageIs(InboundMessageQueuer q, Class<T> klass) throws Exception { Message outbound = waitForOutbound(q); assertEquals(klass, outbound.getClass()); return (T) outbound; } @Test public void autoRescanOnKeyExhaustion() throws Exception { // Check that if the last key that was inserted into the bloom filter is seen in some requested blocks, // that the exhausting block is discarded, a new filter is calculated and sent, and then the download resumes. final int NUM_KEYS = 9; // First, grab a load of keys from the wallet, and then recreate it so it forgets that those keys were issued. Wallet shadow = Wallet.fromSeed(wallet.network(), wallet.getKeyChainSeed(), ScriptType.P2PKH); List<ECKey> keys = new ArrayList<>(NUM_KEYS); for (int i = 0; i < NUM_KEYS; i++) { keys.add(shadow.freshReceiveKey()); } peerGroup.start(); InboundMessageQueuer p1 = connectPeer(1); assertTrue(p1.lastReceivedFilter.contains(keys.get(0).getPubKey())); assertTrue(p1.lastReceivedFilter.contains(keys.get(5).getPubKeyHash())); assertFalse(p1.lastReceivedFilter.contains(keys.get(keys.size() - 1).getPubKey())); peerGroup.startBlockChainDownload(null); peerGroup.startBlockChainDownloadFromPeer(peerGroup.getConnectedPeers().iterator().next()); assertNextMessageIs(p1, GetBlocksMessage.class); // Make some transactions and blocks that send money to the wallet thus using up all the keys. List<Block> blocks = new ArrayList<>(); Coin expectedBalance = Coin.ZERO; Block prev = blockStore.getChainHead().getHeader(); for (ECKey key1 : keys) { Address addr = key1.toAddress(ScriptType.P2PKH, UNITTEST.network()); Block next = FakeTxBuilder.makeSolvedTestBlock(prev, FakeTxBuilder.createFakeTx(UNITTEST.network(), Coin.FIFTY_COINS, addr)); expectedBalance = expectedBalance.add(next.getTransactions().get(1).getOutput(0).getValue()); blocks.add(next); prev = next; } // Send the chain that doesn't have all the transactions in it. The blocks after the exhaustion point should all // be ignored. int epoch = wallet.getKeyChainGroupCombinedKeyLookaheadEpochs(); BloomFilter filter = BloomFilter.read(ByteBuffer.wrap(p1.lastReceivedFilter.serialize())); filterAndSend(p1, blocks, filter); Block exhaustionPoint = blocks.get(3); pingAndWait(p1); assertNotEquals(epoch, wallet.getKeyChainGroupCombinedKeyLookaheadEpochs()); // 4th block was end of the lookahead zone and thus was discarded, so we got 3 blocks worth of money (50 each). assertEquals(Coin.FIFTY_COINS.multiply(3), wallet.getBalance()); assertEquals(exhaustionPoint.getPrevBlockHash(), blockChain.getChainHead().getHeader().getHash()); // Await the new filter. peerGroup.waitForJobQueue(); BloomFilter newFilter = assertNextMessageIs(p1, BloomFilter.class); assertNotEquals(filter, newFilter); assertNextMessageIs(p1, MemoryPoolMessage.class); Ping ping = assertNextMessageIs(p1, Ping.class); inbound(p1, ping.pong()); // Await restart of the chain download. GetDataMessage getdata = assertNextMessageIs(p1, GetDataMessage.class); assertEquals(exhaustionPoint.getHash(), getdata.getHashOf(0)); assertEquals(InventoryItem.Type.FILTERED_BLOCK, getdata.getItems().get(0).type); List<Block> newBlocks = blocks.subList(3, blocks.size()); filterAndSend(p1, newBlocks, newFilter); assertNextMessageIs(p1, Ping.class); // It happened again. peerGroup.waitForJobQueue(); newFilter = assertNextMessageIs(p1, BloomFilter.class); assertNextMessageIs(p1, MemoryPoolMessage.class); inbound(p1, assertNextMessageIs(p1, Ping.class).pong()); assertNextMessageIs(p1, GetDataMessage.class); newBlocks = blocks.subList(6, blocks.size()); filterAndSend(p1, newBlocks, newFilter); // Send a non-tx message so the peer knows the filtered block is over and force processing. inbound(p1, Ping.random()); pingAndWait(p1); assertEquals(expectedBalance, wallet.getBalance()); assertEquals(blocks.get(blocks.size() - 1).getHash(), blockChain.getChainHead().getHeader().getHash()); } private void filterAndSend(InboundMessageQueuer p1, List<Block> blocks, BloomFilter filter) { for (Block block : blocks) { FilteredBlock fb = filter.applyAndUpdate(block); inbound(p1, fb); for (Transaction tx : fb.getAssociatedTransactions().values()) inbound(p1, tx); } } @Test public void testMaxOfMostFreq() { assertEquals(0, PeerGroup.maxOfMostFreq(Collections.emptyList())); assertEquals(0, PeerGroup.maxOfMostFreq(Arrays.asList(0, 0, 1))); assertEquals(3, PeerGroup.maxOfMostFreq(Arrays.asList(1, 3, 1, 2, 2, 3, 3))); assertEquals(0, PeerGroup.maxOfMostFreq(Arrays.asList(1, 1, 2, 2))); assertEquals(0, PeerGroup.maxOfMostFreq(Arrays.asList(-1, 1, 1, 2, 2))); assertEquals(1, PeerGroup.maxOfMostFreq(Arrays.asList(1, 1, 2, 2, 1))); assertEquals(-1, PeerGroup.maxOfMostFreq(Arrays.asList(-1, -1, 2, 2, -1))); } }
40,379
44.218365
137
java
bitcoinj
bitcoinj-master/integration-test/src/test/java/org/bitcoinj/testing/TestWithNetworkConnections.java
/* * 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. */ package org.bitcoinj.testing; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Address; import org.bitcoinj.core.BlockChain; import org.bitcoinj.base.Coin; import org.bitcoinj.core.Context; import org.bitcoinj.core.Message; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Peer; import org.bitcoinj.core.Ping; import org.bitcoinj.core.Pong; import org.bitcoinj.core.Services; import org.bitcoinj.core.VersionAck; import org.bitcoinj.core.VersionMessage; import org.bitcoinj.core.listeners.PreMessageReceivedEventListener; import org.bitcoinj.net.BlockingClient; import org.bitcoinj.net.BlockingClientManager; import org.bitcoinj.net.ClientConnectionManager; import org.bitcoinj.net.NioClient; import org.bitcoinj.net.NioClientManager; import org.bitcoinj.net.NioServer; import org.bitcoinj.net.StreamConnection; import org.bitcoinj.net.StreamConnectionFactory; import org.bitcoinj.params.TestNet3Params; import org.bitcoinj.params.UnitTestParams; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.MemoryBlockStore; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.KeyChainGroup; import org.bitcoinj.wallet.Wallet; import javax.annotation.Nullable; import javax.net.SocketFactory; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.time.Duration; import java.util.Random; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * Utility class that makes it easy to work with mock NetworkConnections. */ public class TestWithNetworkConnections { protected static final int TCP_PORT_BASE = 10000 + new Random().nextInt(40000); public static final int PEER_SERVERS = 5; protected static final NetworkParameters UNITTEST = UnitTestParams.get(); protected static final NetworkParameters TESTNET = TestNet3Params.get(); protected BlockStore blockStore; protected BlockChain blockChain; protected Wallet wallet; protected Address address; protected SocketAddress socketAddress; private NioServer[] peerServers = new NioServer[PEER_SERVERS]; private final ClientConnectionManager channels; protected final BlockingQueue<InboundMessageQueuer> newPeerWriteTargetQueue = new LinkedBlockingQueue<>(); public enum ClientType { NIO_CLIENT_MANAGER, BLOCKING_CLIENT_MANAGER, NIO_CLIENT, BLOCKING_CLIENT } private final ClientType clientType; public TestWithNetworkConnections(ClientType clientType) { this.clientType = clientType; if (clientType == ClientType.NIO_CLIENT_MANAGER) channels = new NioClientManager(); else if (clientType == ClientType.BLOCKING_CLIENT_MANAGER) channels = new BlockingClientManager(); else channels = null; } public void setUp() throws Exception { setUp(new MemoryBlockStore(UNITTEST.getGenesisBlock())); } public void setUp(BlockStore blockStore) throws Exception { BriefLogFormatter.init(); Context.propagate(new Context(100, Coin.ZERO, false, false)); this.blockStore = blockStore; // Allow subclasses to override the wallet object with their own. if (wallet == null) { // Reduce the number of keys we need to work with to speed up these tests. KeyChainGroup kcg = KeyChainGroup.builder(UNITTEST.network()).lookaheadSize(4).lookaheadThreshold(2) .fromRandom(ScriptType.P2PKH).build(); wallet = new Wallet(UNITTEST.network(), kcg); address = wallet.freshReceiveAddress(ScriptType.P2PKH); } blockChain = new BlockChain(UNITTEST, wallet, blockStore); startPeerServers(); if (clientType == ClientType.NIO_CLIENT_MANAGER || clientType == ClientType.BLOCKING_CLIENT_MANAGER) { channels.startAsync(); channels.awaitRunning(); } socketAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 1111); } protected void startPeerServers() throws IOException { for (int i = 0 ; i < PEER_SERVERS ; i++) { startPeerServer(i); } } protected void startPeerServer(int i) throws IOException { peerServers[i] = new NioServer(new StreamConnectionFactory() { @Nullable @Override public StreamConnection getNewConnection(InetAddress inetAddress, int port) { return new InboundMessageQueuer(UNITTEST) { @Override public void connectionClosed() { } @Override public void connectionOpened() { newPeerWriteTargetQueue.offer(this); } }; } }, new InetSocketAddress(InetAddress.getLoopbackAddress(), TCP_PORT_BASE + i)); peerServers[i].startAsync(); peerServers[i].awaitRunning(); } public void tearDown() throws Exception { stopPeerServers(); } protected void stopPeerServers() { for (int i = 0 ; i < PEER_SERVERS ; i++) stopPeerServer(i); } protected void stopPeerServer(int i) { peerServers[i].stopAsync(); peerServers[i].awaitTerminated(); } protected InboundMessageQueuer connect(Peer peer, VersionMessage versionMessage) throws Exception { checkArgument(versionMessage.services().has(Services.NODE_NETWORK)); final AtomicBoolean doneConnecting = new AtomicBoolean(false); final Thread thisThread = Thread.currentThread(); peer.addDisconnectedEventListener((p, peerCount) -> { synchronized (doneConnecting) { if (!doneConnecting.get()) thisThread.interrupt(); } }); if (clientType == ClientType.NIO_CLIENT_MANAGER || clientType == ClientType.BLOCKING_CLIENT_MANAGER) channels.openConnection(new InetSocketAddress(InetAddress.getLoopbackAddress(), 2000), peer); else if (clientType == ClientType.NIO_CLIENT) new NioClient(new InetSocketAddress(InetAddress.getLoopbackAddress(), 2000), peer, Duration.ofMillis(100)); else if (clientType == ClientType.BLOCKING_CLIENT) new BlockingClient(new InetSocketAddress(InetAddress.getLoopbackAddress(), 2000), peer, Duration.ofMillis(100), SocketFactory.getDefault(), null); else throw new RuntimeException(); // Claim we are connected to a different IP that what we really are, so tx confidence broadcastBy sets work InboundMessageQueuer writeTarget = newPeerWriteTargetQueue.take(); writeTarget.peer = peer; // Complete handshake with the peer - send/receive version(ack)s, receive bloom filter checkState(!peer.getVersionHandshakeFuture().isDone()); writeTarget.sendMessage(versionMessage); writeTarget.sendMessage(new VersionAck()); try { checkState(writeTarget.nextMessageBlocking() instanceof VersionMessage); checkState(writeTarget.nextMessageBlocking() instanceof VersionAck); peer.getVersionHandshakeFuture().get(); synchronized (doneConnecting) { doneConnecting.set(true); } Thread.interrupted(); // Clear interrupted bit in case it was set before we got into the CS } catch (InterruptedException e) { // We were disconnected before we got back version/verack } return writeTarget; } protected void closePeer(Peer peer) throws Exception { peer.close(); } protected void inbound(InboundMessageQueuer peerChannel, Message message) { peerChannel.sendMessage(message); } private void outboundPingAndWait(final InboundMessageQueuer p, long nonce) throws Exception { // Send a ping and wait for it to get to the other side CompletableFuture<Void> pingReceivedFuture = new CompletableFuture<>(); p.mapPingFutures.put(nonce, pingReceivedFuture); p.peer.sendMessage(Ping.of(nonce)); pingReceivedFuture.get(); p.mapPingFutures.remove(nonce); } private void inboundPongAndWait(final InboundMessageQueuer p, final long nonce) throws Exception { // Receive a ping (that the Peer doesn't see) and wait for it to get through the socket final CompletableFuture<Void> pongReceivedFuture = new CompletableFuture<>(); PreMessageReceivedEventListener listener = (p1, m) -> { if (m instanceof Pong && ((Pong) m).nonce() == nonce) { pongReceivedFuture.complete(null); return null; } return m; }; p.peer.addPreMessageReceivedEventListener(Threading.SAME_THREAD, listener); inbound(p, Pong.of(nonce)); pongReceivedFuture.get(); p.peer.removePreMessageReceivedEventListener(listener); } protected void pingAndWait(final InboundMessageQueuer p) throws Exception { final long nonce = (long) (Math.random() * Long.MAX_VALUE); // Start with an inbound Pong as pingAndWait often happens immediately after an inbound() call, and then wants // to wait on an outbound message, so we do it in the same order or we see race conditions inboundPongAndWait(p, nonce); outboundPingAndWait(p, nonce); } protected Message outbound(InboundMessageQueuer p1) throws Exception { pingAndWait(p1); return p1.nextMessage(); } protected Message waitForOutbound(InboundMessageQueuer ch) throws InterruptedException { return ch.nextMessageBlocking(); } protected Peer peerOf(InboundMessageQueuer ch) { return ch.peer; } }
10,796
39.897727
158
java
bitcoinj
bitcoinj-master/integration-test/src/test/java/org/bitcoinj/testing/TestWithPeerGroup.java
/* * Copyright 2012 Matt Corallo. * * 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. */ package org.bitcoinj.testing; import com.google.common.util.concurrent.ListeningScheduledExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.core.BloomFilter; import org.bitcoinj.core.MemoryPoolMessage; import org.bitcoinj.core.Peer; import org.bitcoinj.core.PeerGroup; import org.bitcoinj.core.ProtocolVersion; import org.bitcoinj.core.SendAddrV2Message; import org.bitcoinj.core.Services; import org.bitcoinj.core.VersionAck; import org.bitcoinj.core.VersionMessage; import org.bitcoinj.net.BlockingClientManager; import org.bitcoinj.net.ClientConnectionManager; import org.bitcoinj.net.NioClientManager; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.MemoryBlockStore; import org.bitcoinj.utils.ContextPropagatingThreadFactory; import org.junit.Rule; import org.junit.rules.Timeout; import java.net.InetAddress; import java.net.InetSocketAddress; import java.time.Duration; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * You can derive from this class and call peerGroup.start() in your tests to get a functional PeerGroup that can be * used with loopback peers created using connectPeer. This involves real TCP connections so is a pretty accurate * mock, but means unit tests cannot be run simultaneously. */ public class TestWithPeerGroup extends TestWithNetworkConnections { protected PeerGroup peerGroup; protected VersionMessage remoteVersionMessage; private final ClientType clientType; public TestWithPeerGroup(ClientType clientType) { super(clientType); if (clientType != ClientType.NIO_CLIENT_MANAGER && clientType != ClientType.BLOCKING_CLIENT_MANAGER) throw new RuntimeException(); this.clientType = clientType; } @Rule public Timeout globalTimeout = Timeout.seconds(15); @Override public void setUp() throws Exception { setUp(new MemoryBlockStore(UNITTEST.getGenesisBlock())); } @Override public void setUp(BlockStore blockStore) throws Exception { super.setUp(blockStore); remoteVersionMessage = new VersionMessage(UNITTEST, 1); remoteVersionMessage.localServices = Services.of(Services.NODE_NETWORK | Services.NODE_BLOOM | Services.NODE_WITNESS); remoteVersionMessage.clientVersion = ProtocolVersion.WITNESS_VERSION.intValue(); blockJobs = false; initPeerGroup(); } @Override public void tearDown() { try { super.tearDown(); blockJobs = false; if (peerGroup.isRunning()) peerGroup.stopAsync(); } catch (Exception e) { throw new RuntimeException(e); } } protected void initPeerGroup() { if (clientType == ClientType.NIO_CLIENT_MANAGER) peerGroup = createPeerGroup(new NioClientManager()); else peerGroup = createPeerGroup(new BlockingClientManager()); peerGroup.setPingIntervalMsec(0); // Disable the pings as they just get in the way of most tests. peerGroup.addWallet(wallet); peerGroup.setUseLocalhostPeerWhenPossible(false); // Prevents from connecting to bitcoin nodes on localhost. } protected boolean blockJobs = false; protected final Semaphore jobBlocks = new Semaphore(0); private PeerGroup createPeerGroup(final ClientConnectionManager manager) { return new PeerGroup(UNITTEST, blockChain, manager) { @Override protected ListeningScheduledExecutorService createPrivateExecutor() { return MoreExecutors.listeningDecorator(new ScheduledThreadPoolExecutor(1, new ContextPropagatingThreadFactory("PeerGroup test thread")) { @Override public ScheduledFuture<?> schedule(final Runnable command, final long delay, final TimeUnit unit) { if (!blockJobs) return super.schedule(command, delay, unit); return super.schedule(() -> { TimeUtils.rollMockClock(Duration.ofMillis(unit.toMillis(delay))); command.run(); jobBlocks.acquireUninterruptibly(); }, 0 /* immediate */, unit); } }); } }; } protected InboundMessageQueuer connectPeerWithoutVersionExchange(int id) throws Exception { checkArgument(id < PEER_SERVERS); InetSocketAddress remoteAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), TCP_PORT_BASE + id); Peer peer = peerGroup.connectTo(remoteAddress).getConnectionOpenFuture().get(); InboundMessageQueuer writeTarget = newPeerWriteTargetQueue.take(); writeTarget.peer = peer; return writeTarget; } protected InboundMessageQueuer connectPeer(int id) throws Exception { return connectPeer(id, remoteVersionMessage); } protected InboundMessageQueuer connectPeer(int id, VersionMessage versionMessage) throws Exception { checkArgument(versionMessage.services().has(Services.NODE_NETWORK)); InboundMessageQueuer writeTarget = connectPeerWithoutVersionExchange(id); // Complete handshake with the peer - send/receive version(ack)s, receive bloom filter writeTarget.sendMessage(versionMessage); writeTarget.sendMessage(new VersionAck()); stepThroughInit(versionMessage, writeTarget); return writeTarget; } // handle peer discovered by PeerGroup protected InboundMessageQueuer handleConnectToPeer(int id) throws Exception { return handleConnectToPeer(id, remoteVersionMessage); } // handle peer discovered by PeerGroup protected InboundMessageQueuer handleConnectToPeer(int id, VersionMessage versionMessage) throws Exception { InboundMessageQueuer writeTarget = newPeerWriteTargetQueue.take(); checkArgument(versionMessage.services().has(Services.NODE_NETWORK)); // Complete handshake with the peer - send/receive version(ack)s, receive bloom filter writeTarget.sendMessage(versionMessage); writeTarget.sendMessage(new VersionAck()); stepThroughInit(versionMessage, writeTarget); return writeTarget; } private void stepThroughInit(VersionMessage versionMessage, InboundMessageQueuer writeTarget) throws InterruptedException { checkState(writeTarget.nextMessageBlocking() instanceof VersionMessage); checkState(writeTarget.nextMessageBlocking() instanceof SendAddrV2Message); checkState(writeTarget.nextMessageBlocking() instanceof VersionAck); checkState(writeTarget.nextMessageBlocking() instanceof BloomFilter); checkState(writeTarget.nextMessageBlocking() instanceof MemoryPoolMessage); } }
7,795
41.835165
154
java
bitcoinj
bitcoinj-master/integration-test/src/test/java/org/bitcoinj/testing/InboundMessageQueuer.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.testing; import org.bitcoinj.core.BloomFilter; import org.bitcoinj.core.Message; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Peer; import org.bitcoinj.core.PeerSocketHandler; import org.bitcoinj.core.Ping; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; /** * An extension of {@link PeerSocketHandler} that keeps inbound messages in a queue for later processing */ public abstract class InboundMessageQueuer extends PeerSocketHandler { public final BlockingQueue<Message> inboundMessages = new ArrayBlockingQueue<>(1000); public final Map<Long, CompletableFuture<Void>> mapPingFutures = new HashMap<>(); public Peer peer; public BloomFilter lastReceivedFilter; protected InboundMessageQueuer(NetworkParameters params) { super(params, new InetSocketAddress(InetAddress.getLoopbackAddress(), 2000)); } public Message nextMessage() { return inboundMessages.poll(); } public Message nextMessageBlocking() throws InterruptedException { return inboundMessages.take(); } @Override protected void processMessage(Message m) throws Exception { if (m instanceof Ping) { CompletableFuture<Void> future = mapPingFutures.get(((Ping) m).nonce()); if (future != null) { future.complete(null); return; } } if (m instanceof BloomFilter) { lastReceivedFilter = (BloomFilter) m; } inboundMessages.offer(m); } }
2,359
32.239437
104
java
bitcoinj
bitcoinj-master/integration-test/src/test/java/org/bitcoinj/examples/ForwardingServiceTest.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.examples; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Address; import org.bitcoinj.core.Context; import org.bitcoinj.crypto.ECKey; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import java.io.File; /** * Forwarding Service Functional/Integration test. Uses {@link BitcoinNetwork#TESTNET} so is {@code @Disabled}. * To run this test comment-out the {@code @Disabled} annotation. */ @Disabled public class ForwardingServiceTest { static final BitcoinNetwork network = BitcoinNetwork.TESTNET; static final Address forwardingAddress = new ECKey().toAddress(ScriptType.P2WPKH, network); static final String[] args = new String[] { forwardingAddress.toString(), network.toString() }; @BeforeEach void setupTest() { Context.propagate(new Context()); } @Test public void startAndImmediatelyInterrupt(@TempDir File tempDir) { // Start the service and immediately interrupt Thread thread = new Thread( () -> new ForwardingService(args).run() ); thread.start(); thread.interrupt(); } @Test public void startAndImmediatelyClose(@TempDir File tempDir) { // Instantiate the service, start it, and immediately close it try (ForwardingService service = new ForwardingService(args) ) { service.run(); } } }
2,150
32.609375
111
java
bitcoinj
bitcoinj-master/integration-test/src/test/java/org/bitcoinj/kits/WalletAppKitTest.java
/* * Copyright by the original author or authors. * * 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. */ package org.bitcoinj.kits; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.ScriptType; import org.bitcoinj.core.Context; import org.bitcoinj.wallet.KeyChainGroupStructure; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import java.io.File; /** * WalletAppKit Functional/Integration test. Uses {@link BitcoinNetwork#TESTNET} so is {@code @Ignore}d. * To run this test comment-out the {@code @Disabled} annotation. */ @Disabled public class WalletAppKitTest { static final BitcoinNetwork network = BitcoinNetwork.TESTNET; static final int MAX_CONNECTIONS = 3; WalletAppKit kit; @BeforeEach void setupTest(@TempDir File tempDir) { Context.propagate(new Context()); kit = new WalletAppKit(network, ScriptType.P2WPKH, KeyChainGroupStructure.BIP43, tempDir, "prefix") { @Override protected void onSetupCompleted() { peerGroup().setMaxConnections(MAX_CONNECTIONS); } }; } // Construct the kit and immediately stop it @Test public void constructAndStop() { kit.stopAsync(); kit.awaitTerminated(); } // Construct the kit, start it, and immediately stop it @Test public void constructStartAndStop() { kit.setBlockingStartup(false); kit.startAsync(); kit.awaitRunning(); kit.stopAsync(); kit.awaitTerminated(); } // Construct the kit, start it, wait for it to sync, and then stop it @Test public void constructStartSyncAndStop() { // blockStartup is true by default, so this will sync the blockchain before awaitRunning completes kit.startAsync(); kit.awaitRunning(); kit.stopAsync(); kit.awaitTerminated(); } }
2,560
29.855422
106
java