From 98402852cd9691b5457ebd9fe970fb1f4d1f8435 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Fri, 5 Jul 2024 19:51:19 -0700 Subject: [PATCH] style: clean up and simply code for several classes (#253) * FinalCommitment, GetQuorumRotationInfo, InstantSend8, LLMQ*, MasternodeConfig, Report --- .../masternode/owner/MasternodeConfig.java | 11 ++- .../org/bitcoinj/quorums/FinalCommitment.java | 27 +++--- .../quorums/GetQuorumRotationInfo.java | 4 +- .../org/bitcoinj/quorums/InstantSendLock.java | 1 + .../bitcoinj/quorums/InstantSendManager.java | 87 +++++++++---------- .../quorums/LLMQBackgroundThread.java | 2 +- .../java/org/bitcoinj/quorums/LLMQUtils.java | 6 +- .../org/bitcoinj/examples/debug/Report.java | 28 +++--- 8 files changed, 77 insertions(+), 89 deletions(-) diff --git a/core/src/main/java/org/bitcoinj/masternode/owner/MasternodeConfig.java b/core/src/main/java/org/bitcoinj/masternode/owner/MasternodeConfig.java index 379d033b1b..016ab0a5c6 100644 --- a/core/src/main/java/org/bitcoinj/masternode/owner/MasternodeConfig.java +++ b/core/src/main/java/org/bitcoinj/masternode/owner/MasternodeConfig.java @@ -9,13 +9,13 @@ import java.io.*; import java.util.ArrayList; +import java.util.List; /** * Created by Hash Engineering on 7/8/2018. */ public class MasternodeConfig { - public static class MasternodeEntry { private String alias; @@ -76,7 +76,7 @@ public void setIp(String ip) { protected File masternodeConfigFile; public MasternodeConfig(File configFile) { - entries = new ArrayList(); + entries = new ArrayList<>(); masternodeConfigFile = configFile; } @@ -94,7 +94,7 @@ public void add(String alias, String ip, String privKey, String txHash, String o entries.add(cme); } - public ArrayList getEntries() { + public List getEntries() { return entries; } @@ -102,7 +102,7 @@ public int getCount() { return entries.size(); } - private ArrayList entries; + private final ArrayList entries; public boolean importFromFile(String fileToImport, StringBuilder strError) { try { @@ -190,8 +190,7 @@ public boolean read(StringBuilder strError) { } catch (FileNotFoundException x) { strError.append(x.getMessage()); - try { - FileOutputStream configFile = new FileOutputStream(masternodeConfigFile, true); + try (FileOutputStream configFile = new FileOutputStream(masternodeConfigFile, true)) { String strHeader = "# Masternode config file\n" + "# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n" + "# Example: mn1 127.0.0.2:19999 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n"; configFile.write(strHeader.getBytes()); return true; // Nothing to read, so just return diff --git a/core/src/main/java/org/bitcoinj/quorums/FinalCommitment.java b/core/src/main/java/org/bitcoinj/quorums/FinalCommitment.java index 0690d5fd55..f7c6c98f77 100644 --- a/core/src/main/java/org/bitcoinj/quorums/FinalCommitment.java +++ b/core/src/main/java/org/bitcoinj/quorums/FinalCommitment.java @@ -33,6 +33,7 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; +import java.util.List; public class FinalCommitment extends SpecialTxPayload { @Deprecated @@ -128,6 +129,7 @@ protected void parse() throws ProtocolException { length = cursor - offset; } + @Override protected void bitcoinSerializeToStream(OutputStream stream) throws IOException{ bitcoinSerializeToStream(stream, isLegacy()); } @@ -189,6 +191,7 @@ public String getName() { * } */ + @Override public JSONObject toJson() { JSONObject result = new JSONObject(); result.put("version", getVersion()); @@ -245,7 +248,7 @@ public boolean verify(StoredBlock block, ArrayList members, boolean return false; if(!params.getLlmqs().containsKey(LLMQParameters.LLMQType.fromValue(llmqType))) { - log.error("invalid llmqType " + llmqType); + log.error("invalid llmqType: {}", llmqType); return false; } @@ -325,13 +328,10 @@ public boolean isNull() { countValidMembers() > 0) { return false; } - if (quorumPublicKey.isValid() || - !quorumVvecHash.isZero() || - membersSignature.isValid() || - quorumSignature.isValid()) { - return false; - } - return true; + return !quorumPublicKey.isValid() && + quorumVvecHash.isZero() && + !membersSignature.isValid() && + !quorumSignature.isValid(); } public boolean verifyNull() @@ -342,11 +342,7 @@ public boolean verifyNull() } LLMQParameters llmqParameters = params.getLlmqs().get(LLMQParameters.LLMQType.fromValue(llmqType)); - if (!isNull() || !verifySizes(llmqParameters)) { - return false; - } - - return true; + return isNull() && verifySizes(llmqParameters); } public boolean verifySizes(LLMQParameters llmqParameters) { @@ -361,6 +357,7 @@ public boolean verifySizes(LLMQParameters llmqParameters) { return true; } + @Override public Sha256Hash getHash() { try { UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(getMessageSize()); @@ -407,11 +404,11 @@ public BLSSignature getQuorumSignature() { return quorumSignature.getSignature(); } - public ArrayList getSigners() { + public List getSigners() { return signers; } - public ArrayList getValidMembers() { + public List getValidMembers() { return validMembers; } diff --git a/core/src/main/java/org/bitcoinj/quorums/GetQuorumRotationInfo.java b/core/src/main/java/org/bitcoinj/quorums/GetQuorumRotationInfo.java index 11e4f4f737..deab45ac4e 100644 --- a/core/src/main/java/org/bitcoinj/quorums/GetQuorumRotationInfo.java +++ b/core/src/main/java/org/bitcoinj/quorums/GetQuorumRotationInfo.java @@ -40,7 +40,7 @@ public GetQuorumRotationInfo(NetworkParameters params, byte [] payload) { } public GetQuorumRotationInfo(NetworkParameters params, - ArrayList baseBlockHashes, Sha256Hash blockRequestHash, boolean extraShare) { + List baseBlockHashes, Sha256Hash blockRequestHash, boolean extraShare) { super(params); this.baseBlockHashes = new ArrayList<>(baseBlockHashes.size()); this.baseBlockHashes.addAll(baseBlockHashes); @@ -73,7 +73,7 @@ public Sha256Hash getBlockRequestHash() { return blockRequestHash; } - public ArrayList getBaseBlockHashes() { + public List getBaseBlockHashes() { return baseBlockHashes; } diff --git a/core/src/main/java/org/bitcoinj/quorums/InstantSendLock.java b/core/src/main/java/org/bitcoinj/quorums/InstantSendLock.java index 920cfa8805..377d362121 100644 --- a/core/src/main/java/org/bitcoinj/quorums/InstantSendLock.java +++ b/core/src/main/java/org/bitcoinj/quorums/InstantSendLock.java @@ -118,6 +118,7 @@ public Sha256Hash getRequestId() { } } + @Override public Sha256Hash getHash() { try { UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(getMessageSize()); diff --git a/core/src/main/java/org/bitcoinj/quorums/InstantSendManager.java b/core/src/main/java/org/bitcoinj/quorums/InstantSendManager.java index 58586c4a26..d1e4d314e1 100644 --- a/core/src/main/java/org/bitcoinj/quorums/InstantSendManager.java +++ b/core/src/main/java/org/bitcoinj/quorums/InstantSendManager.java @@ -165,9 +165,9 @@ public void processInstantSendLock(Peer peer, InstantSendLock isLock) { } log.info("received islock: txid={}, islock={} , peer={}", - isLock.txid.toString(), hash.toString(), peer.hashCode()); + isLock.txid, hash, peer.hashCode()); - pendingInstantSendLocks.put(hash, new Pair((long)peer.hashCode(), isLock)); + pendingInstantSendLocks.put(hash, new Pair<>((long)peer.hashCode(), isLock)); if(runWithoutThread) { try { @@ -208,9 +208,8 @@ public boolean alreadyHave(InventoryItem inv) try { boolean haslock = db.getInstantSendLockByHash(inv.hash) != null || pendingInstantSendLocks.containsKey(inv.hash); TransactionConfidence confidence = context.getConfidenceTable().get(inv.hash); - if(confidence != null) { - if(confidence.getIXType() != TransactionConfidence.IXType.IX_NONE) - return true; + if (confidence != null && confidence.getIXType() != TransactionConfidence.IXType.IX_NONE) { + return true; } if(!invalidInstantSendLocks.isEmpty()) { for(InstantSendLock islock : invalidInstantSendLocks.keySet()) { @@ -238,7 +237,7 @@ public void run() { } catch (InterruptedException x) { //let the thread stop } catch (BlockStoreException x) { - + throw new RuntimeException(x); } } }; @@ -294,7 +293,7 @@ public boolean checkCanLock(Transaction tx, boolean printDebug) BlockStore blockStore = blockChain.getBlockStore(); Coin value = Coin.valueOf(0); for (TransactionInput in : tx.getInputs()) { - if (!checkCanLock(in.getOutpoint(), printDebug, tx.getHash())) { + if (!checkCanLock(in.getOutpoint(), printDebug, tx.getTxId())) { return false; } @@ -317,8 +316,7 @@ public boolean checkCanLock(Transaction tx, boolean printDebug) return true; } - boolean checkCanLock(TransactionOutPoint outpoint, boolean printDebug, Sha256Hash txHash) - { + boolean checkCanLock(TransactionOutPoint outpoint, boolean printDebug, Sha256Hash txHash) { int nInstantSendConfirmationsRequired = context.getParams().getInstantSendConfirmationsRequired(); if (isLocked(outpoint.getHash())) { @@ -330,8 +328,7 @@ boolean checkCanLock(TransactionOutPoint outpoint, boolean printDebug, Sha256Has TransactionConfidence mempoolTx = mempool.get(outpoint.getHash()); if (mempoolTx != null) { if (printDebug) { - log.info("txid={}: parent mempool TX {} is not locked", - txHash.toString(), outpoint.getHash().toString()); + log.info("txid={}: parent mempool TX {} is not locked", txHash, outpoint.getHash()); } return false; } @@ -349,12 +346,12 @@ boolean checkCanLock(TransactionOutPoint outpoint, boolean printDebug, Sha256Has hashBlock = block.getHeader().getHash(); if (printDebug) { log.info("txid={}: failed to find parent TX {}", - txHash.toString(), outpoint.getHash().toString()); + txHash, outpoint.getHash()); return false; } } catch (BlockStoreException x) { - log.error("BlockStoreException: "+ x.getMessage()); + log.error("BlockStoreException: {}", x.getMessage()); return false; } @@ -369,7 +366,7 @@ boolean checkCanLock(TransactionOutPoint outpoint, boolean printDebug, Sha256Has if (context.chainLockHandler.hasChainLock(utxo.getHeight(), block.getHash())) { if (printDebug) { log.info("txid={}: outpoint {} too new and not ChainLocked. nTxAge={}, nInstantSendConfirmationsRequired={}", - txHash.toString(), outpoint.toStringShort(), txAge, nInstantSendConfirmationsRequired); + txHash, outpoint.toStringShort(), txAge, nInstantSendConfirmationsRequired); } return false; } @@ -391,7 +388,7 @@ boolean checkCanLock(TransactionOutPoint outpoint, boolean printDebug, Sha256Has { if (printDebug) { log.info("txid={}: outpoint {} too new and not ChainLocked. nTxAge={}, nInstantSendConfirmationsRequired={}", - txHash.toString(), outpoint.toStringShort(), confidence.getDepthInBlocks(), nInstantSendConfirmationsRequired); + txHash, outpoint.toStringShort(), confidence.getDepthInBlocks(), nInstantSendConfirmationsRequired); } return false; } @@ -413,7 +410,7 @@ boolean processPendingInstantSendLocks() throws BlockStoreException { return processPendingInstantSendLocks(true); } else { // Don't short circuit. Try to process deterministic and not deterministic islocks - return processPendingInstantSendLocks(false) & processPendingInstantSendLocks(true); + return processPendingInstantSendLocks(false) && processPendingInstantSendLocks(true); } } return false; @@ -517,12 +514,12 @@ HashSet processPendingInstantSendLocks(LLMQParameters.LLMQType llmqT InstantSendLock islock = p.getValue().getSecond(); if (batchVerifier.getBadSources().contains(nodeId)) { - log.info("islock: bad sources contains this node: " + nodeId); + log.info("islock: bad sources contains this node: {}", nodeId); continue; } if (!islock.signature.getSignature().isValid()) { - log.info("islock: signature is not valid: " + islock.signature); + log.info("islock: signature is not valid: {}", islock.signature); batchVerifier.getBadSources().add(nodeId); continue; } @@ -531,7 +528,7 @@ HashSet processPendingInstantSendLocks(LLMQParameters.LLMQType llmqT // no need to verify an ISLOCK if we already have verified the recovered sig that belongs to it if (quorumSigningManager.hasRecoveredSig(llmqType, id, islock.txid)) { - log.info("islock: signature has already been verified: " + islock.txid); + log.info("islock: signature has already been verified: {}", islock.txid); continue; } @@ -565,7 +562,8 @@ HashSet processPendingInstantSendLocks(LLMQParameters.LLMQType llmqT quorum = quorumSigningManager.selectQuorumForSigning(llmqType, signHeight, id, signOffset); if (quorum == null) { // should not happen, but if one fails to select, all others will also fail to select - log.info("islock: quorum not found to verify signature [tipHeight: " + tipHeight + " vs " + context.masternodeListManager.getQuorumListAtTip(llmqType).getHeight() + "]"); + log.info("islock: quorum not found to verify signature [tipHeight: {} vs {}]", tipHeight, + context.masternodeListManager.getQuorumListAtTip(llmqType).getHeight()); log.info("islock: signHeight: {}, id: {}", signHeight, id); log.info("islock: dash-cli quorum selectquorum {} {}", llmqType.getValue(), Sha256Hash.wrap(id.getReversedBytes())); invalidInstantSendLocks.put(islock, Utils.currentTimeSeconds()); @@ -616,7 +614,7 @@ HashSet processPendingInstantSendLocks(LLMQParameters.LLMQType llmqT if (batchVerifier.getBadMessages().contains(hash)) { log.info("islock: -- txid={}, islock={}: invalid sig in islock, peer={}", - islock.txid.toString(), hash.toString(), nodeId); + islock.txid, hash, nodeId); badISLocks.add(hash); // report invalid signature to the logs @@ -651,7 +649,7 @@ HashSet processPendingInstantSendLocks(LLMQParameters.LLMQType llmqT if (!quorumSigningManager.hasRecoveredSigForId(llmqType, recSig.id)) { recSig.updateHash(); log.info("passing reconstructed recSig to signing mgr -- txid={}, islock={}: peer={}", - islock.txid.toString(), hash.toString(), nodeId); + islock.txid, hash, nodeId); quorumSigningManager.pushReconstructedRecoveredSig(recSig, quorum); } } @@ -665,25 +663,22 @@ void processInstantSendLock(long from, Sha256Hash hash, InstantSendLock islock) StoredBlock minedBlock = null; TransactionConfidence confidence = context.getConfidenceTable().get(hash); - if(confidence != null) { - if(confidence.getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) - { - long height = confidence.getAppearedAtChainHeight(); + if(confidence != null && confidence.getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) { + long height = confidence.getAppearedAtChainHeight(); - try { - StoredBlock block = blockChain.getBlockStore().get((int)height); - if(block != null) { - // Let's see if the TX that was locked by this islock is already mined in a ChainLocked block. If yes, - // we can simply ignore the islock, as the ChainLock implies locking of all TXs in that chain - if (context.chainLockHandler.hasChainLock(height, block.getHeader().getHash())) { - log.info("txlock={}, islock={}: dropping islock as it already got a ChainLock in block {}, peer={}", - islock.txid.toString(), hash.toString(), block.getHeader().getHash().toString(), from); - return; - } + try { + StoredBlock block = blockChain.getBlockStore().get((int)height); + if(block != null) { + // Let's see if the TX that was locked by this islock is already mined in a ChainLocked block. If yes, + // we can simply ignore the islock, as the ChainLock implies locking of all TXs in that chain + if (context.chainLockHandler.hasChainLock(height, block.getHeader().getHash())) { + log.info("txlock={}, islock={}: dropping islock as it already got a ChainLock in block {}, peer={}", + islock.txid, hash, block.getHeader().getHash(), from); + return; } - } catch (BlockStoreException x) { - //swallow } + } catch (BlockStoreException x) { + //swallow } } @@ -691,7 +686,7 @@ void processInstantSendLock(long from, Sha256Hash hash, InstantSendLock islock) try { log.info("processing islock txid={}, islock={}: peer={}", - islock.txid.toString(), hash.toString(), from); + islock.txid, hash, from); InstantSendLock otherIsLock; if (db.getInstantSendLockByHash(hash) != null) { @@ -700,13 +695,13 @@ void processInstantSendLock(long from, Sha256Hash hash, InstantSendLock islock) otherIsLock = db.getInstantSendLockByTxid(islock.txid); if (otherIsLock != null) { log.info("duplicate islock: txid={}, islock={}: other islock={}, peer={}", - islock.txid.toString(), hash, otherIsLock.getHash().toString(), from); + islock.txid, hash, otherIsLock, from); } for (TransactionOutPoint in : islock.inputs) { otherIsLock = db.getInstantSendLockByInput(in); if (otherIsLock != null) { log.info("processInstantSendLock -- txid={}, islock={}: conflicting input in islock. input={}, other islock={}, peer={}", - islock.txid.toString(), hash, in.toStringShort(), otherIsLock.getHash(), from); + islock.txid, hash, in.toStringShort(), otherIsLock.getHash(), from); } } @@ -782,11 +777,7 @@ public void syncTransaction(Transaction tx, StoredBlock block, int posInBlock) } } - ChainLockListener chainLockListener = new ChainLockListener() { - public void onNewChainLock(StoredBlock block) { - handleFullyConfirmedBlock(block.getHeight()); - } - }; + ChainLockListener chainLockListener = block -> handleFullyConfirmedBlock(block.getHeight()); NewBestBlockListener newBestBlockListener = new NewBestBlockListener() { @Override @@ -817,7 +808,7 @@ void handleFullyConfirmedBlock(int height) Sha256Hash islockHash = p.getKey(); InstantSendLock islock = p.getValue(); log.info("removed islock as it got fully confirmed -- txid={}, islock={}", - islock.txid.toString(), islockHash.toString()); + islock.txid, islockHash); } // Keep invalid ISLocks for 1 hour @@ -945,7 +936,7 @@ public Sha256Hash getConflictingTx(Transaction tx) continue; } - if (otherIsLock.txid.equals(tx.getHash())) { + if (otherIsLock.txid.equals(tx.getTxId())) { return otherIsLock.txid; } } diff --git a/core/src/main/java/org/bitcoinj/quorums/LLMQBackgroundThread.java b/core/src/main/java/org/bitcoinj/quorums/LLMQBackgroundThread.java index e6161023d8..8c6410e3f6 100644 --- a/core/src/main/java/org/bitcoinj/quorums/LLMQBackgroundThread.java +++ b/core/src/main/java/org/bitcoinj/quorums/LLMQBackgroundThread.java @@ -56,7 +56,7 @@ public void run() { debugTimer++; if(debugTimer % 400 == 0) { - log.info(context.instantSendManager.toString()); + log.info("{}", context.instantSendManager); if(debugTimer == 2000) debugTimer = 0; } diff --git a/core/src/main/java/org/bitcoinj/quorums/LLMQUtils.java b/core/src/main/java/org/bitcoinj/quorums/LLMQUtils.java index 7cf89bd77b..ddf3386e54 100644 --- a/core/src/main/java/org/bitcoinj/quorums/LLMQUtils.java +++ b/core/src/main/java/org/bitcoinj/quorums/LLMQUtils.java @@ -21,7 +21,7 @@ import static org.bitcoinj.quorums.LLMQParameters.LLMQType.LLMQ_400_85; public class LLMQUtils { - static public Sha256Hash buildCommitmentHash(LLMQParameters.LLMQType llmqType, Sha256Hash blockHash, ArrayList validMembers, BLSPublicKey pubKey, Sha256Hash vvecHash) + public static Sha256Hash buildCommitmentHash(LLMQParameters.LLMQType llmqType, Sha256Hash blockHash, ArrayList validMembers, BLSPublicKey pubKey, Sha256Hash vvecHash) { try { UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(); @@ -37,7 +37,7 @@ static public Sha256Hash buildCommitmentHash(LLMQParameters.LLMQType llmqType, S } - static public Sha256Hash buildSignHash(int llmqType, Sha256Hash quorumHash, Sha256Hash id, Sha256Hash msgHash) + public static Sha256Hash buildSignHash(int llmqType, Sha256Hash quorumHash, Sha256Hash id, Sha256Hash msgHash) { try { UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(); @@ -51,7 +51,7 @@ static public Sha256Hash buildSignHash(int llmqType, Sha256Hash quorumHash, Sha2 } } - static public Sha256Hash buildSignHash(LLMQParameters.LLMQType llmqType, Sha256Hash quorumHash, Sha256Hash id, Sha256Hash msgHash) + public static Sha256Hash buildSignHash(LLMQParameters.LLMQType llmqType, Sha256Hash quorumHash, Sha256Hash id, Sha256Hash msgHash) { return buildSignHash(llmqType.getValue(), quorumHash, id, msgHash); } diff --git a/examples/src/main/java/org/bitcoinj/examples/debug/Report.java b/examples/src/main/java/org/bitcoinj/examples/debug/Report.java index 3066de8b8a..b5aaa66bd8 100644 --- a/examples/src/main/java/org/bitcoinj/examples/debug/Report.java +++ b/examples/src/main/java/org/bitcoinj/examples/debug/Report.java @@ -8,20 +8,20 @@ import java.io.File; import java.io.IOException; import java.io.InputStreamReader; +import java.nio.charset.Charset; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; -abstract public class Report { +public abstract class Report { File outputFile; String dashClientPath; String confPath; - private static final DateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH_mm"); - - public Report(String prefix, String dashClientPath, String confPath, NetworkParameters params) { + protected Report(String prefix, String dashClientPath, String confPath, NetworkParameters params) { this.dashClientPath = dashClientPath; this.confPath = confPath; + DateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH_mm"); outputFile = new File(prefix + params.getId() + "-" + format.format(new Date()) + ".csv"); } @@ -34,19 +34,19 @@ JSONObject runRPCCommand(String command) { config = String.format("-conf=%s", confPath); } Process process = Runtime.getRuntime().exec(String.format("%s %s %s", dashClientPath, config, command)); - int result = process.waitFor(); - - BufferedReader stdInput = new BufferedReader(new - InputStreamReader(process.getInputStream())); + process.waitFor(); - String s; - StringBuilder output = new StringBuilder(); - while ((s = stdInput.readLine()) != null) { - output.append(s); - } + try (BufferedReader stdInput = new BufferedReader(new + InputStreamReader(process.getInputStream(), Charset.defaultCharset()))) { - return new JSONObject(output.toString()); + String s; + StringBuilder output = new StringBuilder(); + while ((s = stdInput.readLine()) != null) { + output.append(s); + } + return new JSONObject(output.toString()); + } } catch (IOException e) { return null; } catch (JSONException e) {