3
0
mirror of https://github.com/Qortal/altcoinj.git synced 2025-02-12 10:15:52 +00:00

Clean up toString and other string-related code.

This commit is contained in:
Amichai Rothman 2015-06-28 15:10:22 +03:00 committed by Mike Hearn
parent fd52c86bf9
commit 820765753c
32 changed files with 78 additions and 131 deletions

View File

@ -142,13 +142,7 @@ public class AddressMessage extends Message {
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("addr: ");
for (PeerAddress a : addresses) {
builder.append(a.toString());
builder.append(" ");
}
return builder.toString();
return "addr: " + Utils.join(addresses);
}
}

View File

@ -585,27 +585,15 @@ public class Block extends Message {
StringBuilder s = new StringBuilder("v");
s.append(version);
s.append(" block: \n");
s.append(" previous block: ");
s.append(getPrevBlockHash());
s.append("\n");
s.append(" merkle root: ");
s.append(getMerkleRoot());
s.append("\n");
s.append(" time: [");
s.append(time);
s.append("] ");
s.append(Utils.dateTimeFormat(time * 1000));
s.append("\n");
s.append(" difficulty target (nBits): ");
s.append(difficultyTarget);
s.append("\n");
s.append(" nonce: ");
s.append(nonce);
s.append("\n");
s.append(" previous block: ").append(getPrevBlockHash()).append("\n");
s.append(" merkle root: ").append(getMerkleRoot()).append("\n");
s.append(" time: [").append(time).append("] ").append(Utils.dateTimeFormat(time * 1000)).append("\n");
s.append(" difficulty target (nBits): ").append(difficultyTarget).append("\n");
s.append(" nonce: ").append(nonce).append("\n");
if (transactions != null && transactions.size() > 0) {
s.append(" with ").append(transactions.size()).append(" transaction(s):\n");
for (Transaction tx : transactions) {
s.append(tx.toString());
s.append(tx);
}
}
return s.toString();

View File

@ -76,13 +76,7 @@ public class GetBlocksMessage extends Message {
@Override
public String toString() {
StringBuffer b = new StringBuffer();
b.append("getblocks: ");
for (Sha256Hash hash : locator) {
b.append(hash.toString());
b.append(" ");
}
return b.toString();
return "getblocks: " + Utils.join(locator);
}
@Override

View File

@ -35,13 +35,7 @@ public class GetHeadersMessage extends GetBlocksMessage {
@Override
public String toString() {
StringBuffer b = new StringBuffer();
b.append("getheaders: ");
for (Sha256Hash hash : locator) {
b.append(hash.toString());
b.append(" ");
}
return b.toString();
return "getheaders: " + Utils.join(locator);
}
/**

View File

@ -40,7 +40,7 @@ public class InventoryItem {
@Override
public String toString() {
return type.toString() + ": " + hash;
return type + ": " + hash;
}
@Override

View File

@ -273,12 +273,8 @@ public class Peer extends PeerSocketHandler {
@Override
public String toString() {
PeerAddress addr = getAddress();
if (addr == null) {
// User-provided NetworkConnection object.
return "Peer()";
} else {
return addr.toString();
}
// if null, it's a user-provided NetworkConnection object
return addr == null ? "Peer()" : addr.toString();
}
@Override
@ -501,9 +497,9 @@ public class Peer extends PeerSocketHandler {
private void processAlert(AlertMessage m) {
try {
if (m.isSignatureValid()) {
log.info("Received alert from peer {}: {}", toString(), m.getStatusBar());
log.info("Received alert from peer {}: {}", this, m.getStatusBar());
} else {
log.warn("Received alert with invalid signature from peer {}: {}", toString(), m.getStatusBar());
log.warn("Received alert with invalid signature from peer {}: {}", this, m.getStatusBar());
}
} catch (Throwable t) {
// Signature checking can FAIL on Android platforms before Gingerbread apparently due to bugs in their
@ -1306,7 +1302,7 @@ public class Peer extends PeerSocketHandler {
}
if (log.isDebugEnabled())
log.debug("{}: blockChainDownloadLocked({}) current head = {}",
toString(), toHash.toString(), chainHead.getHeader().getHashAsString());
this, toHash, chainHead.getHeader().getHashAsString());
StoredBlock cursor = chainHead;
for (int i = 100; cursor != null && i > 0; i--) {
blockLocator.add(cursor.getHeader().getHash());

View File

@ -152,12 +152,8 @@ public class RejectMessage extends Message {
@Override
public String toString() {
Sha256Hash hash = getRejectedObjectHash();
if (hash != null)
return String.format("Reject: %s %s for reason '%s' (%d)", getRejectedMessage(), getRejectedObjectHash(),
getReasonString(), getReasonCode().code);
else
return String.format("Reject: %s for reason '%s' (%d)", getRejectedMessage(),
getReasonString(), getReasonCode().code);
return String.format("Reject: %s %s for reason '%s' (%d)", getRejectedMessage(),
hash != null ? hash : "", getReasonString(), getReasonCode().code);
}
@Override

View File

@ -86,6 +86,6 @@ public class StoredUndoableBlock implements Serializable {
@Override
public String toString() {
return "Undoable Block " + blockHash.toString();
return "Undoable Block " + blockHash;
}
}

View File

@ -47,7 +47,7 @@ import static com.google.common.base.Preconditions.checkState;
*
* <p>All Bitcoin transactions are at risk of being reversed, though the risk is much less than with traditional payment
* systems. Transactions have <i>confidence levels</i>, which help you decide whether to trust a transaction or not.
* Whether to trust a transaction is something that needs to be decided on a case by case basis - a rule that makes
* Whether to trust a transaction is something that needs to be decided on a case by case basis - a rule that makes
* sense for selling MP3s might not make sense for selling cars, or accepting payments from a family member. If you
* are building a wallet, how to present confidence to your users is something to consider carefully.</p>
*/
@ -74,7 +74,7 @@ public class Transaction extends ChildMessage implements Serializable {
final int height2 = tx2.getConfidence().getAppearedAtChainHeight();
final int heightComparison = -(Ints.compare(height1, height2));
//If height1==height2, compare by tx hash to make comparator consistent with equals
return heightComparison != 0 ? heightComparison : tx1.getHash().compareTo(tx2.getHash());
return heightComparison != 0 ? heightComparison : tx1.getHash().compareTo(tx2.getHash());
}
};
private static final Logger log = LoggerFactory.getLogger(Transaction.class);
@ -115,7 +115,7 @@ public class Transaction extends ChildMessage implements Serializable {
// This is an in memory helper only.
private transient Sha256Hash hash;
// Data about how confirmed this tx is. Serialized, may be null.
// Data about how confirmed this tx is. Serialized, may be null.
@Nullable private TransactionConfidence confidence;
// Records a map of which blocks the transaction has appeared in (keys) to an index within that block (values).
@ -199,8 +199,8 @@ public class Transaction extends ChildMessage implements Serializable {
* @param payload Bitcoin protocol formatted byte array containing message content.
* @param offset The location of the first payload byte within the array.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization.
* If true and the backing byte array is invalidated due to modification of a field then
* @param parseRetain Whether to retain the backing byte array for quick reserialization.
* If true and the backing byte array is invalidated due to modification of a field then
* the cached bytes may be repopulated and retained if the message is serialized again in the future.
* @param length The length of message if known. Usually this is provided when deserializing of the wire
* as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH
@ -318,7 +318,7 @@ public class Transaction extends ChildMessage implements Serializable {
* is the best chain. The best chain block is guaranteed to be called last. So this must be idempotent.</p>
*
* <p>Sets updatedAt to be the earliest valid block time where this tx was seen.</p>
*
*
* @param block The {@link StoredBlock} in which the transaction has appeared.
* @param bestChain whether to set the updatedAt timestamp from the block header (only if not already set)
* @param relativityOffset A number that disambiguates the order of transactions within a block.
@ -398,7 +398,7 @@ public class Transaction extends ChildMessage implements Serializable {
/**
* The transaction fee is the difference of the value of all inputs and the value of all outputs. Currently, the fee
* can only be determined for transactions created by us.
*
*
* @return fee, or null if it cannot be determined
*/
public Coin getFee() {
@ -647,7 +647,8 @@ public class Transaction extends ChildMessage implements Serializable {
script = "???";
script2 = "???";
}
s.append(" == COINBASE TXN (scriptSig " + script + ") (scriptPubKey " + script2 + ")\n");
s.append(" == COINBASE TXN (scriptSig ").append(script)
.append(") (scriptPubKey ").append(script2).append(")\n");
return s.toString();
}
for (TransactionInput in : inputs) {

View File

@ -322,12 +322,7 @@ public class TransactionConfidence implements Serializable {
StringBuilder builder = new StringBuilder();
int peers = numBroadcastPeers();
if (peers > 0) {
builder.append("Seen by ");
builder.append(peers);
if (peers > 1)
builder.append(" peers. ");
else
builder.append(" peer. ");
builder.append("Seen by ").append(peers).append(peers > 1 ? " peers. " : " peer. ");
}
switch (getConfidenceType()) {
case UNKNOWN:

View File

@ -279,10 +279,8 @@ public class TransactionInput extends ChildMessage implements Serializable {
*/
@Override
public String toString() {
if (isCoinBase())
return "TxIn: COINBASE";
try {
return "TxIn for [" + outpoint + "]: " + getScriptSig();
return isCoinBase() ? "TxIn: COINBASE" : "TxIn for [" + outpoint + "]: " + getScriptSig();
} catch (ScriptException e) {
throw new RuntimeException(e);
}

View File

@ -193,10 +193,9 @@ public class TransactionOutPoint extends ChildMessage implements Serializable {
@Override
public String toString() {
return hash.toString() + ":" + index;
return hash + ":" + index;
}
/**
* Returns the hash of the transaction this outpoint references/spends/is connected to.
*/

View File

@ -354,8 +354,7 @@ public class TransactionOutput extends ChildMessage implements Serializable {
buf.append(" to multisig");
else
buf.append(" (unknown type)");
buf.append(" script:");
buf.append(script);
buf.append(" script:").append(script);
return buf.toString();
} catch (ScriptException e) {
throw new RuntimeException(e);

View File

@ -156,7 +156,7 @@ public class UTXO implements Serializable {
@Override
public String toString() {
return String.format("Stored TxOut of %s (%s:%d)", value.toFriendlyString(), hash.toString(), index);
return String.format("Stored TxOut of %s (%s:%d)", value.toFriendlyString(), hash, index);
}
@Override

View File

@ -54,6 +54,8 @@ public class Utils {
public static final String BITCOIN_SIGNED_MESSAGE_HEADER = "Bitcoin Signed Message:\n";
public static final byte[] BITCOIN_SIGNED_MESSAGE_HEADER_BYTES = BITCOIN_SIGNED_MESSAGE_HEADER.getBytes(Charsets.UTF_8);
private static final Joiner SPACE_JOINER = Joiner.on(" ");
private static BlockingQueue<Boolean> mockSleepQueue;
/**
@ -407,6 +409,18 @@ public class Utils {
return iso8601.format(dateTime);
}
/**
* Returns a string containing the string representation of the given items,
* delimited by a single space character.
*
* @param items the items to join
* @param <T> the item type
* @return the joined space-delimited string
*/
public static <T> String join(Iterable<T> items) {
return SPACE_JOINER.join(items);
}
public static byte[] copyOf(byte[] in, int length) {
byte[] out = new byte[length];
System.arraycopy(in, 0, out, 0, Math.min(length, in.length));

View File

@ -2768,9 +2768,7 @@ public class Wallet extends BaseTaggableObject implements Serializable, BlockCha
if (!watchedScripts.isEmpty()) {
builder.append("\nWatched scripts:\n");
for (Script script : watchedScripts) {
builder.append(" ");
builder.append(script.toString());
builder.append("\n");
builder.append(" ").append(script).append("\n");
}
}

View File

@ -617,18 +617,11 @@ public class DeterministicKey extends ECKey {
@Override
public void formatKeyWithAddress(boolean includePrivateKeys, StringBuilder builder, NetworkParameters params) {
final Address address = toAddress(params);
builder.append(" addr:");
builder.append(address.toString());
builder.append(" hash160:");
builder.append(Utils.HEX.encode(getPubKeyHash()));
builder.append(" (");
builder.append(getPathAsString());
builder.append(")");
builder.append("\n");
builder.append(" addr:").append(address);
builder.append(" hash160:").append(Utils.HEX.encode(getPubKeyHash()));
builder.append(" (").append(getPathAsString()).append(")\n");
if (includePrivateKeys) {
builder.append(" ");
builder.append(toStringWithPrivate(params));
builder.append("\n");
builder.append(" ").append(toStringWithPrivate(params)).append("\n");
}
}
}

View File

@ -51,6 +51,7 @@ public final class EncryptedData {
@Override
public String toString() {
return "EncryptedData [initialisationVector=" + Arrays.toString(initialisationVector) + ", encryptedPrivateKey=" + Arrays.toString(encryptedBytes) + "]";
return "EncryptedData [initialisationVector=" + Arrays.toString(initialisationVector)
+ ", encryptedPrivateKey=" + Arrays.toString(encryptedBytes) + "]";
}
}

View File

@ -19,7 +19,6 @@ package org.bitcoinj.crypto;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.Utils;
import com.google.common.base.Joiner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -126,7 +125,7 @@ public class MnemonicCode {
// used as a pseudo-random function. Desired length of the
// derived key is 512 bits (= 64 bytes).
//
String pass = Joiner.on(' ').join(words);
String pass = Utils.join(words);
String salt = "mnemonic" + passphrase;
long start = System.currentTimeMillis();

View File

@ -79,6 +79,6 @@ public class PaymentChannelCloseException extends Exception {
@Override
public String toString() {
return "PaymentChannelCloseException for reason " + getCloseReason().toString();
return "PaymentChannelCloseException for reason " + getCloseReason();
}
}

View File

@ -110,7 +110,7 @@ public class StoredServerChannel {
" Client output: %s%n" +
" Refund unlock: %s (%d unix time)%n" +
" Contract: %s%n",
connectedHandler != null ? "connected" : "disconnected", myKey, bestValueToMe.toString(),
connectedHandler != null ? "connected" : "disconnected", myKey, bestValueToMe,
clientOutput, new Date(refundTransactionUnlockTimeSecs * 1000), refundTransactionUnlockTimeSecs,
contract.toString().replaceAll(newline, newline + " "));
}

View File

@ -125,12 +125,7 @@ public class Script {
*/
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
for (ScriptChunk chunk : chunks)
buf.append(chunk).append(' ');
if (buf.length() > 0)
buf.setLength(buf.length() - 1);
return buf.toString();
return Utils.join(chunks);
}
/** Returns the serialized program as a newly created byte array. */
@ -297,7 +292,7 @@ public class Script {
// A large constant followed by an OP_CHECKSIG is the key.
return chunk0data;
} else {
throw new ScriptException("Script did not match expected form: " + toString());
throw new ScriptException("Script did not match expected form: " + this);
}
}

View File

@ -139,10 +139,7 @@ public class ScriptChunk {
buf.append(getOpCodeName(opcode));
} else if (data != null) {
// Data chunk
buf.append(getPushDataName(opcode));
buf.append("[");
buf.append(Utils.HEX.encode(data));
buf.append("]");
buf.append(getPushDataName(opcode)).append("[").append(Utils.HEX.encode(data)).append("]");
} else {
// Small num
buf.append(Script.decodeFromOpN(opcode));

View File

@ -68,7 +68,7 @@ class StoredTransactionOutPoint implements Serializable {
@Override
public String toString() {
return "Stored transaction out point: " + hash.toString() + ":" + index;
return "Stored transaction out point: " + hash + ":" + index;
}
@Override

View File

@ -337,7 +337,7 @@ public class BitcoinURI {
} else {
builder.append(",");
}
builder.append("'").append(entry.getKey()).append("'=").append("'").append(entry.getValue().toString()).append("'");
builder.append("'").append(entry.getKey()).append("'=").append("'").append(entry.getValue()).append("'");
}
builder.append("]");
return builder.toString();

View File

@ -1157,8 +1157,7 @@ public abstract class BtcFormat extends Format {
* @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();
return format(qty, new StringBuffer(), new FieldPosition(0), minDecimals, boxAsList(fractionGroups)).toString();
}
/**
@ -1542,9 +1541,9 @@ public abstract class BtcFormat extends Format {
* 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) {
StringBuffer groups = new StringBuffer();
StringBuilder groups = new StringBuilder();
for (int group : decimalGroups) {
groups.append("(" + Strings.repeat("#",group) + ")");
groups.append("(").append(Strings.repeat("#", group)).append(")");
}
DecimalFormatSymbols s = numberFormat.getDecimalFormatSymbols();
String digit = String.valueOf(s.getDigit());

View File

@ -25,7 +25,6 @@ import org.bitcoinj.script.Script;
import org.bitcoinj.store.UnreadableWalletException;
import org.bitcoinj.utils.Threading;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import com.google.common.collect.PeekingIterator;
@ -1333,7 +1332,7 @@ public class DeterministicKeyChain implements EncryptableKeyChain {
} else if (includePrivateKeys) {
final List<String> words = seed.getMnemonicCode();
builder2.append(
String.format("Seed as words: %s%nSeed as hex: %s%n", Joiner.on(' ').join(words),
String.format("Seed as words: %s%nSeed as hex: %s%n", Utils.join(words),
seed.toHexString())
);
}

View File

@ -21,7 +21,6 @@ import org.bitcoinj.core.Utils;
import org.bitcoinj.crypto.*;
import org.bitcoinj.store.UnreadableWalletException;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.spongycastle.crypto.params.KeyParameter;
@ -132,10 +131,9 @@ public class DeterministicSeed implements EncryptableItem {
@Override
public String toString() {
if (isEncrypted())
return "DeterministicSeed [encrypted]";
else
return "DeterministicSeed " + toHexString() + " " + Joiner.on(" ").join(mnemonicCode);
return isEncrypted()
? "DeterministicSeed [encrypted]"
: "DeterministicSeed " + toHexString() + " " + Utils.join(mnemonicCode);
}
/** Returns the seed as hex or null if encrypted. */
@ -185,7 +183,7 @@ public class DeterministicSeed implements EncryptableItem {
}
private byte[] getMnemonicAsBytes() {
return Joiner.on(" ").join(mnemonicCode).getBytes(Charsets.UTF_8);
return Utils.join(mnemonicCode).getBytes(Charsets.UTF_8);
}
public DeterministicSeed decrypt(KeyCrypter crypter, String passphrase, KeyParameter aesKey) {

View File

@ -104,12 +104,12 @@ public class KeyCrypterScryptTest {
KeyCrypterScrypt keyCrypter = new KeyCrypterScrypt(scryptParameters);
// create a longer encryption string
StringBuilder stringBuffer = new StringBuilder();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 100; i++) {
stringBuffer.append(i).append(" ").append("The quick brown fox");
builder.append(i).append(" The quick brown fox");
}
EncryptedData data = keyCrypter.encrypt(stringBuffer.toString().getBytes(), keyCrypter.deriveKey(PASSWORD2));
EncryptedData data = keyCrypter.encrypt(builder.toString().getBytes(), keyCrypter.deriveKey(PASSWORD2));
assertNotNull(data);
try {

View File

@ -17,7 +17,7 @@
package org.bitcoinj.crypto;
import com.google.common.base.Joiner;
import org.bitcoinj.core.Utils;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
@ -171,7 +171,7 @@ public class MnemonicCodeTest {
byte[] entropy = mc.toEntropy(split(vecCode));
assertEquals(vecData, HEX.encode(entropy));
assertEquals(vecCode, Joiner.on(' ').join(code));
assertEquals(vecCode, Utils.join(code));
assertEquals(vecSeed, HEX.encode(seed));
}
}

View File

@ -1,10 +1,10 @@
package org.bitcoinj.examples;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Utils;
import org.bitcoinj.core.Wallet;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.wallet.DeterministicSeed;
import com.google.common.base.Joiner;
/**
* The following example shows you how to create a deterministic seed from a hierarchical deterministic wallet represented as a mnemonic code.
@ -25,6 +25,6 @@ public class BackupToMnemonicSeed {
System.out.println("seed: " + seed.toString());
System.out.println("creation time: " + seed.getCreationTimeSeconds());
System.out.println("mnemonicCode: " + Joiner.on(" ").join(seed.getMnemonicCode()));
System.out.println("mnemonicCode: " + Utils.join(seed.getMnemonicCode()));
}
}

View File

@ -1,8 +1,8 @@
package wallettemplate;
import org.bitcoinj.core.Utils;
import org.bitcoinj.crypto.MnemonicCode;
import org.bitcoinj.wallet.DeterministicSeed;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.util.concurrent.Service;
import javafx.application.Platform;
@ -68,7 +68,7 @@ public class WalletSettingsController {
// Set the mnemonic seed words.
final List<String> mnemonicCode = seed.getMnemonicCode();
checkNotNull(mnemonicCode); // Already checked for encryption.
String origWords = Joiner.on(" ").join(mnemonicCode);
String origWords = Utils.join(mnemonicCode);
wordsArea.setText(origWords);
// Validate words as they are being typed.