diff --git a/pom.xml b/pom.xml index e9f753ed7..841f427cb 100644 --- a/pom.xml +++ b/pom.xml @@ -11,44 +11,46 @@ UTF-8 UTF-8 - 1.7.22 + 1.8.21 17 17 package ${project.basedir}/dist - 4.1.107.Final - 2.3.1 - 2.14.2 - 5.4.0 - 1.18.26 - 3.1.5 - 3.25.0 + 4.1.108.Final + 2.4.2 + 2.17.1 + 5.5.0 + 1.18.32 + 3.1.8 + 3.25.1 4.13.2 - 5.2.0 + 5.11.0 1.2.1 - 2.20.0 - 3.13.0 - 4.4 - 1.16.0 - 2.13.0 - 1.5.0 - 32.1.2-jre - 8.0.0 + 2.23.1 + 3.14.0 + 1.5 + 4.5.0-M1 + 1.17.0 + 2.16.1 + 1.7.0 + 33.2.0-jre + 9.1.1 4.12.0 - 3.24.2 + 3.25.3 23.1.3 - 1.76 - 1.76 - 4.4.0 + 1.78 + 1.78 + 4.5.7 1.6 - 4.0.1 - 1.4.2 - 1.17.1 + 4.0.2 + 1.4.3 + 1.21.1 1.1.10.4 - 1.2.18 - 8.0.33 - 2.2.220 + 1.2.22 + 8.4.0 + 2.2.224 + 2.10 **/*RandomXSyncTest.java,**/*SyncTest.java,**/*SnapshotJTest.java @@ -66,26 +68,6 @@ - - bintray - https://jcenter.bintray.com - - - jitpack.io - https://jitpack.io - - - consensys-maven - https://artifacts.consensys.net/public/maven/maven/ - - true - always - - - true - always - - hyperledger.jfrog.io https://hyperledger.jfrog.io/artifactory/besu-maven/ @@ -432,6 +414,12 @@ ${commons-collections4.version} + + org.apache.commons + commons-rng-simple + ${commons-rng.version} + + commons-codec commons-codec @@ -619,7 +607,7 @@ - org.apache.tuweni + io.tmio tuweni-bytes ${tuweni.version} @@ -635,7 +623,7 @@ - org.apache.tuweni + io.tmio tuweni-units ${tuweni.version} @@ -647,7 +635,7 @@ - org.apache.tuweni + io.tmio tuweni-io ${tuweni.version} @@ -793,19 +781,19 @@ com.fasterxml.jackson.core jackson-databind - ${json.version} + ${jackson.version} com.fasterxml.jackson.core jackson-core - ${json.version} + ${jackson.version} com.fasterxml.jackson.core jackson-annotations - ${json.version} + ${jackson.version} @@ -901,16 +889,11 @@ druid ${druid.version} + com.google.code.gson gson - 2.9.0 - test - - - com.google.code.gson - gson - 2.9.0 + ${gson.version} compile diff --git a/src/main/java/io/xdag/Kernel.java b/src/main/java/io/xdag/Kernel.java index 2f50923b5..05f45d925 100644 --- a/src/main/java/io/xdag/Kernel.java +++ b/src/main/java/io/xdag/Kernel.java @@ -335,7 +335,7 @@ private JsonRpcWeb3ServerHandler getJsonRpcWeb3ServerHandler() { config.getRPCSpec().getRpcModules() ); } catch (Exception e) { - log.error("catch an error " + e.getMessage()); + log.error("catch an error {}", e.getMessage()); } } diff --git a/src/main/java/io/xdag/Launcher.java b/src/main/java/io/xdag/Launcher.java index 34ef91557..a50baf20e 100644 --- a/src/main/java/io/xdag/Launcher.java +++ b/src/main/java/io/xdag/Launcher.java @@ -109,7 +109,6 @@ protected void addOption(Option option) { /** * Parses options from the given arguments. - * * Priority: arguments => system property => console input */ protected CommandLine parseOptions(String[] args) throws ParseException { diff --git a/src/main/java/io/xdag/Wallet.java b/src/main/java/io/xdag/Wallet.java index c32bb552e..48de36b36 100644 --- a/src/main/java/io/xdag/Wallet.java +++ b/src/main/java/io/xdag/Wallet.java @@ -85,6 +85,11 @@ public class Wallet { private static final int SALT_LENGTH = 16; private static final int BCRYPT_COST = 12; private static final String MNEMONIC_PASS_PHRASE = ""; + /** + * -- GETTER -- + * Returns the file where the wallet is persisted. + */ + @Getter private final File file; private final Config config; @@ -123,13 +128,6 @@ public void delete() throws IOException { Files.delete(file.toPath()); } - /** - * Returns the file where the wallet is persisted. - */ - public File getFile() { - return file; - } - /** * Locks the wallet. */ @@ -502,7 +500,7 @@ public List createTransactionBlock(Map ourKeys, int base = 1 + 1 + 2 + hasRemark; XAmount amount = XAmount.ZERO; - while (stack.size() > 0) { + while (!stack.isEmpty()) { Map.Entry key = stack.peek(); base += 1; int originSize = keysPerBlock.size(); @@ -527,7 +525,7 @@ public List createTransactionBlock(Map ourKeys, amount = XAmount.ZERO; } } - if (keys.size() != 0) { + if (!keys.isEmpty()) { res.add(createTransaction(to, amount, keys, remark)); } @@ -571,12 +569,12 @@ private Block createNewBlock(Map pairs, List
to, int defKeyIndex = -1; // if no input, return null - if (pairs == null || pairs.size() == 0) { + if (pairs == null || pairs.isEmpty()) { return null; } // if no output, return null - if (to == null || to.size() == 0) { + if (to == null || to.isEmpty()) { return null; } diff --git a/src/main/java/io/xdag/cli/Commands.java b/src/main/java/io/xdag/cli/Commands.java index c8e4a1579..e0d0f7db7 100644 --- a/src/main/java/io/xdag/cli/Commands.java +++ b/src/main/java/io/xdag/cli/Commands.java @@ -61,10 +61,10 @@ import static io.xdag.utils.BasicUtils.*; import static io.xdag.utils.WalletUtils.*; +@Getter @Slf4j public class Commands { - @Getter private final Kernel kernel; public Commands(Kernel kernel) { @@ -273,7 +273,7 @@ private List createTransactionBlock(Map ourKeys, int base = 1 + 1 + 2 + hasRemark; XAmount amount = XAmount.ZERO; - while (stack.size() > 0) { + while (!stack.isEmpty()) { Map.Entry key = stack.peek(); base += 1; int originSize = keysPerBlock.size(); @@ -298,7 +298,7 @@ private List createTransactionBlock(Map ourKeys, amount = XAmount.ZERO; } } - if (keys.size() != 0) { + if (!keys.isEmpty()) { res.add(createTransaction(to, amount, keys, remark)); } return res; @@ -432,7 +432,7 @@ public String printBlockInfo(Block block, boolean raw) { StringBuilder inputs = null; StringBuilder outputs = null; if (raw) { - if (block.getInputs().size() != 0) { + if (!block.getInputs().isEmpty()) { inputs = new StringBuilder(); for (Address input : block.getInputs()) { inputs.append(String.format(" input: %s %s%n", @@ -441,7 +441,7 @@ public String printBlockInfo(Block block, boolean raw) { )); } } - if (block.getOutputs().size() != 0) { + if (!block.getOutputs().isEmpty()) { outputs = new StringBuilder(); for (Address output : block.getOutputs()) { if (output.getType().equals(XDAG_FIELD_COINBASE)) continue; @@ -461,7 +461,7 @@ public String printBlockInfo(Block block, boolean raw) { ----------------------------------------------------------------------------------------------------------------------------- block as address: details direction address amount time - """; + """; StringBuilder tx = new StringBuilder(); if (getStateByFlags(block.getInfo().getFlags()).equals(MAIN.getDesc()) && block.getInfo().getHeight() > kernel.getConfig().getSnapshotSpec().getSnapshotHeight()) { tx.append(String.format(" earn: %s %s %s%n", hash2Address(block.getHashLow()), @@ -573,7 +573,7 @@ public String listConnect() { StringBuilder stringBuilder = new StringBuilder(); for (Channel channel : channelList) { stringBuilder.append(channel).append(" ") - .append(System.getProperty("line.separator")); + .append(System.lineSeparator()); } return stringBuilder.toString(); @@ -627,7 +627,7 @@ public String address(Bytes32 wrap, int page) { ----------------------------------------------------------------------------------------------------------------------------- histories of address: details direction address amount time - """; + """; StringBuilder tx = new StringBuilder(); for (TxHistory txHistory : kernel.getBlockchain().getBlockTxHistoryByAddress(wrap, page)) { diff --git a/src/main/java/io/xdag/cli/Shell.java b/src/main/java/io/xdag/cli/Shell.java index 4966dc5b5..25969f610 100644 --- a/src/main/java/io/xdag/cli/Shell.java +++ b/src/main/java/io/xdag/cli/Shell.java @@ -65,6 +65,7 @@ public class Shell extends JlineCommandRegistry implements CommandRegistry, Teln @Setter private Kernel kernel; private Commands commands; + @Setter private LineReader reader; public Shell() { @@ -162,10 +163,6 @@ private void processOldBalance(CommandInput input) { } } - public void setReader(LineReader reader) { - this.reader = reader; - } - private void println(final String msg) { reader.getTerminal().writer().println(msg); reader.getTerminal().writer().flush(); diff --git a/src/main/java/io/xdag/config/AbstractConfig.java b/src/main/java/io/xdag/config/AbstractConfig.java index 5e636b8f3..d6a6b599a 100644 --- a/src/main/java/io/xdag/config/AbstractConfig.java +++ b/src/main/java/io/xdag/config/AbstractConfig.java @@ -61,7 +61,7 @@ public class AbstractConfig implements Config, AdminSpec, NodeSpec, WalletSpec, // Pool websocket spec // ========================= - protected int WebsocketServerPort; + protected int websocketServerPort; protected int maxShareCountPerChannel = 20; protected int awardEpoch = 0xf; @@ -253,7 +253,7 @@ public void getSetting() { poolWhiteIPList = config.hasPath("pool.whiteIPs") ? config.getStringList("pool.whiteIPs") : Collections.singletonList("127.0.0.1"); log.info("Pool whitelist {}. Any IP allowed? {}", poolWhiteIPList, poolWhiteIPList.contains("0.0.0.0")); - WebsocketServerPort = config.hasPath("pool.ws.port") ? config.getInt("pool.ws.port") : 7001; + websocketServerPort = config.hasPath("pool.ws.port") ? config.getInt("pool.ws.port") : 7001; nodeIp = config.hasPath("node.ip") ? config.getString("node.ip") : "127.0.0.1"; nodePort = config.hasPath("node.port") ? config.getInt("node.port") : 8001; nodeTag = config.hasPath("node.tag") ? config.getString("node.tag") : "xdagj"; @@ -393,7 +393,7 @@ public List getPoolWhiteIPList() { @Override public int getWebsocketServerPort() { - return WebsocketServerPort; + return websocketServerPort; } diff --git a/src/main/java/io/xdag/config/Constants.java b/src/main/java/io/xdag/config/Constants.java index 94d91edba..44afc1349 100644 --- a/src/main/java/io/xdag/config/Constants.java +++ b/src/main/java/io/xdag/config/Constants.java @@ -62,7 +62,6 @@ public class Constants { public static final byte BI_EXTRA = 0x40; public static final byte BI_REMARK = (byte) 0x80; public static final Long SEND_PERIOD = 10L; - public static final int DNET_PKT_XDAG = 0x8B; public static final long REQUEST_BLOCKS_MAX_TIME = UInt64.valueOf(1L << 20).toLong(); public static final long REQUEST_WAIT = 64; diff --git a/src/main/java/io/xdag/config/spec/FundSpec.java b/src/main/java/io/xdag/config/spec/FundSpec.java index f15254ae3..5a74e5078 100644 --- a/src/main/java/io/xdag/config/spec/FundSpec.java +++ b/src/main/java/io/xdag/config/spec/FundSpec.java @@ -1,3 +1,26 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020-2030 The XdagJ Developers + * + * 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 io.xdag.config.spec; public interface FundSpec { diff --git a/src/main/java/io/xdag/consensus/SyncManager.java b/src/main/java/io/xdag/consensus/SyncManager.java index 5db884e04..7f9f6bc0d 100644 --- a/src/main/java/io/xdag/consensus/SyncManager.java +++ b/src/main/java/io/xdag/consensus/SyncManager.java @@ -172,7 +172,7 @@ public ImportResult importBlock(BlockWrapper blockWrapper) { .tryToConnect(new Block(new XdagBlock(blockWrapper.getBlock().getXdagBlock().getData().toArray()))); if (importResult == EXIST) { - log.debug("Block have exist:" + blockWrapper.getBlock().getHashLow()); + log.debug("Block have exist:{}", blockWrapper.getBlock().getHashLow()); } if (!blockWrapper.isOld() && (importResult == IMPORTED_BEST || importResult == IMPORTED_NOT_BEST)) { @@ -327,7 +327,8 @@ public void makeSyncDone() { } if (config.getEnableGenerateBlock()) { - log.info("start pow at:" + FastDateFormat.getInstance("yyyy-MM-dd 'at' HH:mm:ss z").format(new Date())); + log.info("start pow at:{}", + FastDateFormat.getInstance("yyyy-MM-dd 'at' HH:mm:ss z").format(new Date())); // check main chain // kernel.getMinerServer().start(); kernel.getPow().start(); diff --git a/src/main/java/io/xdag/consensus/XdagPow.java b/src/main/java/io/xdag/consensus/XdagPow.java index 42cb9e2a0..167b5b962 100644 --- a/src/main/java/io/xdag/consensus/XdagPow.java +++ b/src/main/java/io/xdag/consensus/XdagPow.java @@ -37,11 +37,11 @@ import io.xdag.net.websocket.ChannelSupervise; import io.xdag.pool.PoolAwardManager; import io.xdag.utils.BytesUtils; +import io.xdag.utils.XdagRandomUtils; import io.xdag.utils.XdagSha256Digest; import io.xdag.utils.XdagTime; import lombok.Getter; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes32; @@ -59,7 +59,6 @@ import static io.xdag.utils.BasicUtils.keyPair2Hash; import static io.xdag.utils.BytesUtils.compareTo; import static io.xdag.utils.BytesUtils.equalBytes; -@SuppressWarnings({"deprecation"}) @Slf4j public class XdagPow implements PoW, Listener, Runnable { @@ -189,7 +188,7 @@ public Block generateRandomXBlock(long sendTime) { block.signOut(wallet.getDefKey()); // The first 20 bytes of the initial nonce are the node wallet address. minShare.set(Bytes32.wrap(BytesUtils.merge(hash2byte(keyPair2Hash(wallet.getDefKey())), - RandomUtils.nextBytes(12)))); + XdagRandomUtils.nextNewBytes(12)))); block.setNonce(minShare.get()); minHash.set(Bytes32.fromHexString("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")); @@ -204,7 +203,7 @@ public Block generateBlock(long sendTime) { Block block = blockchain.createNewBlock(null, null, true, null, XAmount.ZERO); block.signOut(wallet.getDefKey()); minShare.set(Bytes32.wrap(BytesUtils.merge(hash2byte(keyPair2Hash(wallet.getDefKey())), - RandomUtils.nextBytes(12)))); + XdagRandomUtils.nextNewBytes(12)))); block.setNonce(minShare.get()); // initial nonce minHash.set(block.recalcHash()); @@ -236,12 +235,10 @@ public void receiveNewShare(String share, String hash, long taskIndex) { log.info("Current task is empty"); } else if (currentTask.get().getTaskIndex() == taskIndex && Objects.equals(hash, currentTask.get().getTask()[0].getData().toUnprefixedHexString())) { - // log.debug("Receive Share-info From Pool, Share: {},preHash: {}, task index: {}", share, preHash, - // taskIndex); onNewShare(Bytes32.wrap(Bytes.fromHexString(share))); } else { - log.debug("Task index error or preHash error. " + "Current task is " + currentTask.get().getTaskIndex() + - " ,but pool sends task index is " + taskIndex); + log.debug("Task index error or preHash error. Current task is {} ,but pool sends task index is {}", + currentTask.get().getTaskIndex(), taskIndex); } } @@ -285,8 +282,8 @@ protected void onNewShare(Bytes32 share) { // put minShare into nonce Block b = generateBlock.get(); b.setNonce(minShare.get()); - log.debug("New MinShare :" + share.toHexString()); - log.debug("New MinHash :" + hash.toHexString()); + log.debug("New MinShare :{}", share.toHexString()); + log.debug("New MinHash :{}", hash.toHexString()); } } } catch (Exception e) { @@ -555,11 +552,11 @@ public void run() { shareJson.getJSONObject("msgContent").getString("hash"), shareJson.getJSONObject("msgContent").getLong("taskIndex")); } else { - log.error("Share format error! Current share: " + shareInfo); + log.error("Share format error! Current share: {}", shareInfo); } } catch (JSONException e) { - log.error("Share format error, current share: " + shareInfo); + log.error("Share format error, current share: {}", shareInfo); } } } diff --git a/src/main/java/io/xdag/consensus/XdagSync.java b/src/main/java/io/xdag/consensus/XdagSync.java index a32bb6a91..c48611397 100644 --- a/src/main/java/io/xdag/consensus/XdagSync.java +++ b/src/main/java/io/xdag/consensus/XdagSync.java @@ -35,10 +35,10 @@ import io.xdag.db.BlockStore; import io.xdag.net.Channel; import io.xdag.net.ChannelManager; +import io.xdag.utils.XdagRandomUtils; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.MutableBytes; @@ -69,7 +69,8 @@ public class XdagSync { private final LinkedList syncWindow = new LinkedList<>(); - @Getter@Setter + @Getter + @Setter private Status status; private final Kernel kernel; @@ -119,11 +120,11 @@ private void syncLoop() { */ private void getBlocks() { List any = getAnyNode(); - if (any == null || any.size() == 0) { + if (any == null || any.isEmpty()) { return; } SettableFuture sf = SettableFuture.create(); - int index = RandomUtils.nextInt() % any.size(); + int index = XdagRandomUtils.nextInt() % any.size(); Channel xc = any.get(index); long lastTime = getLastTime(); @@ -167,12 +168,12 @@ private void requestBlocks(long t, long dt) { } List any = getAnyNode(); - if (any == null || any.size() == 0) { + if (any == null || any.isEmpty()) { return; } SettableFuture sf = SettableFuture.create(); - int index = RandomUtils.nextInt() % any.size(); + int index = XdagRandomUtils.nextInt() % any.size(); Channel xc = any.get(index); if (dt > REQUEST_BLOCKS_MAX_TIME) { findGetBlocks(xc, t, dt, sf); diff --git a/src/main/java/io/xdag/core/Address.java b/src/main/java/io/xdag/core/Address.java index 13fb3d19e..5156e59e4 100644 --- a/src/main/java/io/xdag/core/Address.java +++ b/src/main/java/io/xdag/core/Address.java @@ -54,7 +54,7 @@ public class Address { */ protected MutableBytes32 addressHash; - protected boolean isAddress = false; + protected boolean isAddress; protected boolean parsed = false; diff --git a/src/main/java/io/xdag/core/BlockchainImpl.java b/src/main/java/io/xdag/core/BlockchainImpl.java index efff211c7..4e300dcfc 100644 --- a/src/main/java/io/xdag/core/BlockchainImpl.java +++ b/src/main/java/io/xdag/core/BlockchainImpl.java @@ -43,11 +43,11 @@ import io.xdag.utils.BasicUtils; import io.xdag.utils.BytesUtils; import io.xdag.utils.WalletUtils; +import io.xdag.utils.XdagRandomUtils; import io.xdag.utils.XdagTime; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes32; @@ -296,7 +296,7 @@ public synchronized ImportResult tryToConnect(Block block) { result = ImportResult.NO_PARENT; result.setHashlow(ref.getAddress()); result.setErrorInfo("Block have no parent for " + result.getHashlow().toHexString()); - log.debug("Block have no parent for " + result.getHashlow().toHexString()); + log.debug("Block have no parent for {}", result.getHashlow().toHexString()); return result; } else { // ensure ref block's time is earlier than block's time @@ -320,7 +320,8 @@ public synchronized ImportResult tryToConnect(Block block) { if (ref != null && ref.type == XDAG_FIELD_INPUT && !addressStore.addressIsExist(BytesUtils.byte32ToArray(ref.getAddress()))) { result = ImportResult.INVALID_BLOCK; result.setErrorInfo("Address isn't exist " + WalletUtils.toBase58(BytesUtils.byte32ToArray(ref.getAddress()))); - log.debug("Address isn't exist " + WalletUtils.toBase58(BytesUtils.byte32ToArray(ref.getAddress()))); + log.debug("Address isn't exist {}", + WalletUtils.toBase58(BytesUtils.byte32ToArray(ref.getAddress()))); return result; } // ensure TX block's input's & output's amount is enough to subtract minGas, Amount must >= 0.1; @@ -376,7 +377,7 @@ public synchronized ImportResult tryToConnect(Block block) { // 如果是自己的区块 if (checkMineAndAdd(block)) { - log.debug("A block hash:" + block.getHashLow().toHexString() + " become mine"); + log.debug("A block hash:{} become mine", block.getHashLow().toHexString()); updateBlockFlag(block, BI_OURS, true); } @@ -1353,10 +1354,6 @@ public boolean isExtraBlock(Block block) { return (block.getTimestamp() & 0xffff) == 0xffff && block.getNonce() != null && !block.isSaved(); } - public boolean isMainBlock(Block block) { - return ((block.getTimestamp() & 0xffff) == 0xffff && block.getNonce() != null); - } - @Override public XdagStats getXdagStats() { return this.xdagStats; @@ -1550,7 +1547,7 @@ public void checkState() { public void checkOrphan() { long nblk = xdagStats.nnoref / 11; if (nblk > 0) { - boolean b = (nblk % 61) > (RandomUtils.nextLong() % 61); + boolean b = (nblk % 61) > (XdagRandomUtils.nextLong() % 61); nblk = nblk / 61 + (b ? 1 : 0); } while (nblk-- > 0) { @@ -1573,23 +1570,6 @@ public void checkMain() { } } - public SECPPublicKey getBlockPubKey(Block block) { - List keys = block.verifiedKeys(); - MutableBytes subData = block.getSubRawData(block.getOutsigIndex() - 2); -// log.debug("verify encoded:{}", Hex.toHexString(subdata)); - SECPSignature sig = block.getOutsig(); - for (SECPPublicKey publicKey : keys) { - byte[] publicKeyBytes = publicKey.asEcPoint(Sign.CURVE).getEncoded(true); - Bytes digest = Bytes.wrap(subData, Bytes.wrap(publicKeyBytes)); -// log.debug("verify encoded:{}", Hex.toHexString(digest)); - Bytes32 hash = Hash.hashTwice(digest); - if (Sign.SECP256K1.verify(hash, sig, publicKey)) { - return publicKey; - } - } - return null; - } - @Override public void stopCheckMain() { try { diff --git a/src/main/java/io/xdag/core/Filter.java b/src/main/java/io/xdag/core/Filter.java deleted file mode 100644 index 95e86bc18..000000000 --- a/src/main/java/io/xdag/core/Filter.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.xdag.core; - -import io.xdag.db.BlockStore; -import org.apache.tuweni.bytes.Bytes32; - -import java.util.List; - -public class Filter { - - private BlockStore blockStore; - - public Filter(BlockStore blockStore) { - this.blockStore = blockStore; - } - - public boolean filterLinkBlock(Block block){ - List
links = block.getLinks(); - for (Address link:links) { - if(link.getType() != XdagField.FieldType. XDAG_FIELD_OUT){ - return true; - } - } - return false; - } - - public boolean filterTxBlock(Block block){ - List
links = block.getLinks(); - for (Address link:links) { - if(link.getType() == XdagField.FieldType.XDAG_FIELD_IN || link.getType() == XdagField.FieldType.XDAG_FIELD_INPUT){ - return true; - } - } - return false; - } - - public boolean filterOurLinkBlock(Bytes32 blockHashLow){ - Block block = blockStore.getBlockByHash(blockHashLow,true); - if(!filterLinkBlock(block)){ - return block.isOurs(); - }else { - return true; - } - } - -} diff --git a/src/main/java/io/xdag/core/ImportResult.java b/src/main/java/io/xdag/core/ImportResult.java index 3f816be85..3ec1470ed 100644 --- a/src/main/java/io/xdag/core/ImportResult.java +++ b/src/main/java/io/xdag/core/ImportResult.java @@ -27,6 +27,7 @@ import org.apache.tuweni.bytes.MutableBytes32; import lombok.Getter; +import lombok.Setter; public enum ImportResult { ERROR, @@ -41,6 +42,7 @@ public enum ImportResult { MutableBytes32 hashLow; + @Setter @Getter String errorInfo; @@ -52,8 +54,4 @@ public void setHashlow(MutableBytes32 hashLow) { this.hashLow = hashLow; } - public void setErrorInfo(String errorInfo) { - this.errorInfo = errorInfo; - } - } diff --git a/src/main/java/io/xdag/core/PreBlockInfo.java b/src/main/java/io/xdag/core/PreBlockInfo.java index e58c3914b..3c6fc935a 100644 --- a/src/main/java/io/xdag/core/PreBlockInfo.java +++ b/src/main/java/io/xdag/core/PreBlockInfo.java @@ -26,7 +26,6 @@ import java.math.BigInteger; import lombok.Getter; import lombok.Setter; -import org.apache.tuweni.units.bigints.UInt64; @Getter @Setter diff --git a/src/main/java/io/xdag/crypto/RandomX.java b/src/main/java/io/xdag/crypto/RandomX.java index 98e106289..d2ade8200 100644 --- a/src/main/java/io/xdag/crypto/RandomX.java +++ b/src/main/java/io/xdag/crypto/RandomX.java @@ -56,6 +56,7 @@ import io.xdag.crypto.randomx.RandomXUtils; import io.xdag.utils.XdagTime; import lombok.Data; +import lombok.Setter; import lombok.extern.slf4j.Slf4j; @@ -78,6 +79,7 @@ public class RandomX { protected long randomXPoolMemIndex; protected long randomXHashEpochIndex; + @Setter protected Blockchain blockchain; protected boolean is_full_mem; @@ -98,10 +100,6 @@ public RandomX(Config config) { } } - public void setBlockchain(Blockchain blockchain) { - this.blockchain = blockchain; - } - // 外部使用 public boolean isRandomxFork(long epoch) { return mineType == XDAG_RANDOMX && epoch > randomXForkTime; diff --git a/src/main/java/io/xdag/db/OrphanBlockStore.java b/src/main/java/io/xdag/db/OrphanBlockStore.java index fd8f6f9ad..8d0152bdf 100644 --- a/src/main/java/io/xdag/db/OrphanBlockStore.java +++ b/src/main/java/io/xdag/db/OrphanBlockStore.java @@ -27,7 +27,6 @@ import io.xdag.core.Block; import java.util.List; -import io.xdag.core.Filter; import org.bouncycastle.util.encoders.Hex; public interface OrphanBlockStore { diff --git a/src/main/java/io/xdag/db/mysql/TransactionHistoryStoreImpl.java b/src/main/java/io/xdag/db/mysql/TransactionHistoryStoreImpl.java index 230e275bc..1778c369a 100644 --- a/src/main/java/io/xdag/db/mysql/TransactionHistoryStoreImpl.java +++ b/src/main/java/io/xdag/db/mysql/TransactionHistoryStoreImpl.java @@ -175,12 +175,10 @@ public List listTxHistoryByAddress(String address, int page, Object.. long start = new Date(0).getTime(); long end = System.currentTimeMillis(); switch (parameters.length) { - case 0 -> { - } case 1 -> { - int pageSize = Integer.parseInt(parameters[0].toString()); - PAGE_SIZE = (pageSize > 0 && pageSize <= TX_PAGE_SIZE_LIMIT) ? pageSize : PAGE_SIZE; - } + int pageSize = Integer.parseInt(parameters[0].toString()); + PAGE_SIZE = (pageSize > 0 && pageSize <= TX_PAGE_SIZE_LIMIT) ? pageSize : PAGE_SIZE; + } case 2 -> { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); diff --git a/src/main/java/io/xdag/db/rocksdb/BlockStoreImpl.java b/src/main/java/io/xdag/db/rocksdb/BlockStoreImpl.java index 1de8b56e6..39babb909 100644 --- a/src/main/java/io/xdag/db/rocksdb/BlockStoreImpl.java +++ b/src/main/java/io/xdag/db/rocksdb/BlockStoreImpl.java @@ -179,7 +179,7 @@ public void saveTxHistoryToRocksdb(TxHistory txHistory, int id) { remark)); // value: type + isWalletAddress +address hash +txHashLow+ amount + timestamp + remark_length + remark txHistorySource.put(key, value); - log.info("MySQL write exception, transaction history stored in Rocksdb. " + txHistory); + log.info("MySQL write exception, transaction history stored in Rocksdb. {}", txHistory); } public List getAllTxHistoryFromRocksdb() { @@ -550,7 +550,7 @@ public Block getBlockInfoByHash(Bytes32 hashlow) { try { blockInfo = (BlockInfo) deserialize(value, BlockInfo.class); } catch (DeserializationException e) { - log.error("hash low:" + hashlow.toHexString()); + log.error("hash low:{}", hashlow.toHexString()); log.error("can't deserialize data:{}", Hex.toHexString(value)); log.error(e.getMessage(), e); } diff --git a/src/main/java/io/xdag/db/rocksdb/OrphanBlockStoreImpl.java b/src/main/java/io/xdag/db/rocksdb/OrphanBlockStoreImpl.java index f1fb1bbc9..68a2bfcb4 100644 --- a/src/main/java/io/xdag/db/rocksdb/OrphanBlockStoreImpl.java +++ b/src/main/java/io/xdag/db/rocksdb/OrphanBlockStoreImpl.java @@ -109,15 +109,15 @@ public void addOrphan(Block block) { orphanSource.put(BytesUtils.merge(ORPHAN_PREFEX, block.getHashLow().toArray()), BytesUtils.longToBytes(block.getTimestamp(), true)); long currentsize = BytesUtils.bytesToLong(orphanSource.get(ORPHAN_SIZE), 0, false); - log.debug("orphan current size:" + currentsize); + log.debug("orphan current size:{}", currentsize); // log.debug(":" + Hex.toHexString(orphanSource.get(ORPHAN_SIZE))); orphanSource.put(ORPHAN_SIZE, BytesUtils.longToBytes(currentsize + 1, false)); } public long getOrphanSize() { long currentsize = BytesUtils.bytesToLong(orphanSource.get(ORPHAN_SIZE), 0, false); - log.debug("current orphan size:" + currentsize); - log.debug("Hex:" + Hex.toHexString(orphanSource.get(ORPHAN_SIZE))); + log.debug("current orphan size:{}", currentsize); + log.debug("Hex:{}", Hex.toHexString(orphanSource.get(ORPHAN_SIZE))); return currentsize; } diff --git a/src/main/java/io/xdag/db/rocksdb/RocksdbKVSource.java b/src/main/java/io/xdag/db/rocksdb/RocksdbKVSource.java index efab6ad37..e4e7128fc 100644 --- a/src/main/java/io/xdag/db/rocksdb/RocksdbKVSource.java +++ b/src/main/java/io/xdag/db/rocksdb/RocksdbKVSource.java @@ -83,20 +83,20 @@ public class RocksdbKVSource implements KVSource { public RocksdbKVSource(String name) { this.name = name; - log.debug("New RocksdbKVSource: " + name); + log.debug("New RocksdbKVSource: {}", name); } public RocksdbKVSource(String name, int prefixSeekLength) { this.name = name; this.prefixSeekLength = prefixSeekLength; - log.debug("New RocksdbKVSource: " + name); + log.debug("New RocksdbKVSource: {}", name); } @Override public void init() { resetDbLock.writeLock().lock(); try { - log.debug("~> RocksdbKVSource.init(): " + name); + log.debug("~> RocksdbKVSource.init(): {}", name); if (isAlive()) { return; @@ -171,7 +171,7 @@ public void init() { throw new RuntimeException("Failed to initialize database", ioe); } - log.debug("<~ RocksdbKVSource.init(): " + name); + log.debug("<~ RocksdbKVSource.init(): {}", name); } } finally { resetDbLock.writeLock().unlock(); @@ -181,7 +181,7 @@ public void init() { public void backup() { resetDbLock.readLock().lock(); if (log.isTraceEnabled()) { - log.trace("~> RocksdbKVSource.backup(): " + name); + log.trace("~> RocksdbKVSource.backup(): {}", name); } Path path = backupPath(); path.toFile().mkdirs(); @@ -191,7 +191,7 @@ public void backup() { backups.createNewBackup(db, true); if (log.isTraceEnabled()) { - log.trace("<~ RocksdbKVSource.backup(): " + name + " done"); + log.trace("<~ RocksdbKVSource.backup(): {} done", name); } } catch (RocksDBException e) { log.error("Failed to backup database '{}'", name, e); @@ -207,13 +207,8 @@ public void put(byte[] key, byte[] val) { resetDbLock.readLock().lock(); try { if (log.isTraceEnabled()) { - log.trace( - "~> RocksdbKVSource.put(): " - + name - + ", key: " - + Hex.encodeHexString(key) - + ", " - + (val == null ? "null" : val.length)); + log.trace("~> RocksdbKVSource.put(): {}, key: {}, {}", name, Hex.encodeHexString(key), + val == null ? "null" : val.length); } if (val != null) { if (db == null) { @@ -225,13 +220,8 @@ public void put(byte[] key, byte[] val) { db.delete(key); } if (log.isTraceEnabled()) { - log.trace( - "<~ RocksdbKVSource.put(): " - + name - + ", key: " - + Hex.encodeHexString(key) - + ", " - + (val == null ? "null" : val.length)); + log.trace("<~ RocksdbKVSource.put(): {}, key: {}, {}", name, Hex.encodeHexString(key), + val == null ? "null" : val.length); } } catch (RocksDBException e) { log.error("Failed to put into db '{}'", name, e); @@ -247,17 +237,12 @@ public byte[] get(byte[] key) { resetDbLock.readLock().lock(); try { if (log.isTraceEnabled()) { - log.trace("~> RocksdbKVSource.get(): " + name + ", key: " + Hex.encodeHexString(key)); + log.trace("~> RocksdbKVSource.get(): {}, key: {}", name, Hex.encodeHexString(key)); } byte[] ret = db.get(readOpts, key); if (log.isTraceEnabled()) { - log.trace( - "<~ RocksdbKVSource.get(): " - + name - + ", key: " - + Hex.encodeHexString(key) - + ", " - + (ret == null ? "null" : ret.length)); + log.trace("<~ RocksdbKVSource.get(): {}, key: {}, {}", name, Hex.encodeHexString(key), + ret == null ? "null" : ret.length); } return ret; } catch (RocksDBException e) { @@ -274,11 +259,11 @@ public void delete(byte[] key) { resetDbLock.readLock().lock(); try { if (log.isTraceEnabled()) { - log.trace("~> RocksdbKVSource.delete(): " + name + ", key: " + Hex.encodeHexString(key)); + log.trace("~> RocksdbKVSource.delete(): {}, key: {}", name, Hex.encodeHexString(key)); } db.delete(key); if (log.isTraceEnabled()) { - log.trace("<~ RocksdbKVSource.delete(): " + name + ", key: " + Hex.encodeHexString(key)); + log.trace("<~ RocksdbKVSource.delete(): {}, key: {}", name, Hex.encodeHexString(key)); } } catch (RocksDBException e) { log.error("Failed to delete from db '{}'", name, e); @@ -293,7 +278,7 @@ public Set keys() throws RuntimeException { resetDbLock.readLock().lock(); try { if (log.isTraceEnabled()) { - log.trace("~> RocksdbKVSource.keys(): " + name); + log.trace("~> RocksdbKVSource.keys(): {}", name); } try (RocksIterator iterator = db.newIterator()) { Set result = new HashSet<>(); @@ -301,7 +286,7 @@ public Set keys() throws RuntimeException { result.add(iterator.key()); } if (log.isTraceEnabled()) { - log.trace("<~ RocksdbKVSource.keys(): " + name + ", " + result.size()); + log.trace("<~ RocksdbKVSource.keys(): {}, {}", name, result.size()); } return result; } catch (Exception e) { diff --git a/src/main/java/io/xdag/db/rocksdb/SnapshotStoreImpl.java b/src/main/java/io/xdag/db/rocksdb/SnapshotStoreImpl.java index 2abc638d7..4e4006d59 100644 --- a/src/main/java/io/xdag/db/rocksdb/SnapshotStoreImpl.java +++ b/src/main/java/io/xdag/db/rocksdb/SnapshotStoreImpl.java @@ -171,7 +171,7 @@ public void saveSnapshotToIndex(BlockStore blockStore, TransactionHistoryStore t try { blockInfo = (BlockInfo) deserialize(iter.value(), BlockInfo.class); } catch (DeserializationException e) { - log.error("hash low:" + Hex.toHexString(blockInfo.getHashlow())); + log.error("hash low:{}", Hex.toHexString(blockInfo.getHashlow())); log.error("can't deserialize data:{}", Hex.toHexString(iter.value())); log.error(e.getMessage(), e); } diff --git a/src/main/java/io/xdag/net/Channel.java b/src/main/java/io/xdag/net/Channel.java index 378607216..e969b1103 100644 --- a/src/main/java/io/xdag/net/Channel.java +++ b/src/main/java/io/xdag/net/Channel.java @@ -29,7 +29,7 @@ import io.netty.handler.timeout.ReadTimeoutHandler; import io.xdag.Kernel; import io.xdag.net.message.MessageQueue; -import io.xdag.net.node.Node; + import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; diff --git a/src/main/java/io/xdag/net/ChannelManager.java b/src/main/java/io/xdag/net/ChannelManager.java index dfa2ab2b5..f2be1eca0 100644 --- a/src/main/java/io/xdag/net/ChannelManager.java +++ b/src/main/java/io/xdag/net/ChannelManager.java @@ -38,9 +38,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; -import org.apache.commons.lang3.StringUtils; - -import io.xdag.net.node.Node; import lombok.Getter; import lombok.extern.slf4j.Slf4j; @@ -134,7 +131,7 @@ public void closeBlacklistedChannels() { public void onChannelActive(Channel channel, Peer peer) { channel.setActive(peer); activeChannels.put(peer.getPeerId(), channel); - log.debug("activeChannel size:" + activeChannels.size()); + log.debug("activeChannel size:{}", activeChannels.size()); } public List getActivePeers() { diff --git a/src/main/java/io/xdag/net/NetDB.java b/src/main/java/io/xdag/net/NetDB.java index bd8f5999f..acbf8959e 100644 --- a/src/main/java/io/xdag/net/NetDB.java +++ b/src/main/java/io/xdag/net/NetDB.java @@ -38,6 +38,7 @@ import java.util.Set; import lombok.Getter; +import lombok.Setter; import lombok.extern.slf4j.Slf4j; @Getter @@ -166,7 +167,7 @@ public String toString() { } public void appendNetDB(NetDB netDB) { - if (netDB.ipList.size() == 0) { + if (netDB.ipList.isEmpty()) { log.debug("size 0"); return; } @@ -183,6 +184,8 @@ public boolean contains(InetSocketAddress address) { return this.ipList.contains(ip); } + @Setter + @Getter static class IP { InetAddress ip; @@ -202,22 +205,6 @@ public IP(String ip, int port) { } } - public InetAddress getIp() { - return ip; - } - - public void setIp(InetAddress ip) { - this.ip = ip; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - public byte[] getData() { return BytesUtils.merge(ip.getAddress(), BytesUtils.shortToBytes((short) port, true)); } diff --git a/src/main/java/io/xdag/net/Peer.java b/src/main/java/io/xdag/net/Peer.java index 3c8901d32..a625257d2 100644 --- a/src/main/java/io/xdag/net/Peer.java +++ b/src/main/java/io/xdag/net/Peer.java @@ -25,6 +25,7 @@ import io.xdag.Network; import lombok.Getter; +import lombok.Setter; @Getter public class Peer { @@ -36,7 +37,9 @@ public class Peer { private final int port; private final String clientId; private final String[] capabilities; + @Setter private long latestBlockNumber; + @Setter private long latency; public Peer(Network network, short networkVersion, String peerId, String ip, int port, String clientId, @@ -51,14 +54,6 @@ public Peer(Network network, short networkVersion, String peerId, String ip, int this.latestBlockNumber = latestBlockNumber; } - public void setLatestBlockNumber(long number) { - this.latestBlockNumber = number; - } - - public void setLatency(long latency) { - this.latency = latency; - } - @Override public String toString() { return getPeerId() + "@" + ip + ":" + port; diff --git a/src/main/java/io/xdag/net/XdagP2pHandler.java b/src/main/java/io/xdag/net/XdagP2pHandler.java index 07a9398d4..ed972566d 100644 --- a/src/main/java/io/xdag/net/XdagP2pHandler.java +++ b/src/main/java/io/xdag/net/XdagP2pHandler.java @@ -45,7 +45,6 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.xdag.Kernel; -import io.xdag.Network; import io.xdag.config.Config; import io.xdag.config.spec.NodeSpec; import io.xdag.consensus.SyncManager; @@ -446,7 +445,7 @@ protected void processBlockRequest(BlockRequestMessage msg) { Block block = chain.getBlockByHash(Bytes32.wrap(hash), true); int ttl = config.getNodeSpec().getTTL(); if (block != null) { - log.debug("processBlockRequest: findBlock" + Bytes32.wrap(hash).toHexString()); + log.debug("processBlockRequest: findBlock{}", Bytes32.wrap(hash).toHexString()); NewBlockMessage message = new NewBlockMessage(block, ttl); msgQueue.sendMessage(message); } diff --git a/src/main/java/io/xdag/net/message/Message.java b/src/main/java/io/xdag/net/message/Message.java index 49b6a2b3c..cd58befe6 100644 --- a/src/main/java/io/xdag/net/message/Message.java +++ b/src/main/java/io/xdag/net/message/Message.java @@ -25,7 +25,6 @@ package io.xdag.net.message; import org.apache.tuweni.bytes.Bytes; -import org.apache.tuweni.bytes.MutableBytes; import lombok.Getter; diff --git a/src/main/java/io/xdag/net/message/MessageCode.java b/src/main/java/io/xdag/net/message/MessageCode.java index b9a34fd5e..c8f9c2694 100644 --- a/src/main/java/io/xdag/net/message/MessageCode.java +++ b/src/main/java/io/xdag/net/message/MessageCode.java @@ -104,7 +104,7 @@ public static MessageCode of(int code) { return map[0xff & code]; } - private int code; + private final int code; MessageCode(int code) { this.code = code; diff --git a/src/main/java/io/xdag/net/message/MessageFactory.java b/src/main/java/io/xdag/net/message/MessageFactory.java index 998c56786..71fdc8ae4 100644 --- a/src/main/java/io/xdag/net/message/MessageFactory.java +++ b/src/main/java/io/xdag/net/message/MessageFactory.java @@ -31,7 +31,6 @@ import io.xdag.net.message.p2p.PingMessage; import io.xdag.net.message.p2p.PongMessage; import io.xdag.net.message.p2p.WorldMessage; -import io.xdag.utils.exception.UnreachableException; import lombok.extern.slf4j.Slf4j; @Slf4j @@ -56,43 +55,24 @@ public Message create(byte code, byte[] body) throws MessageException { } try { - switch (c) { - case HANDSHAKE_INIT: - return new InitMessage(body); - case HANDSHAKE_HELLO: - return new HelloMessage(body); - case HANDSHAKE_WORLD: - return new WorldMessage(body); - case DISCONNECT: - return new DisconnectMessage(body); - case PING: - return new PingMessage(body); - case PONG: - return new PongMessage(body); - case BLOCKS_REQUEST: - return new BlocksRequestMessage(body); - case BLOCKS_REPLY: - return new BlocksReplyMessage(body); - case SUMS_REQUEST: - return new SumRequestMessage(body); - case SUMS_REPLY: - return new SumReplyMessage(body); - case BLOCKEXT_REQUEST: - return new BlockExtRequestMessage(body); - case BLOCKEXT_REPLY: - return new BlockExtReplyMessage(body); - case BLOCK_REQUEST: - return new BlockRequestMessage(body); - case NEW_BLOCK: - return new NewBlockMessage(body); - case SYNC_BLOCK: - return new SyncBlockMessage(body); - case SYNCBLOCK_REQUEST: - return new SyncBlockRequestMessage(body); - - default: - throw new UnreachableException(); - } + return switch (c) { + case HANDSHAKE_INIT -> new InitMessage(body); + case HANDSHAKE_HELLO -> new HelloMessage(body); + case HANDSHAKE_WORLD -> new WorldMessage(body); + case DISCONNECT -> new DisconnectMessage(body); + case PING -> new PingMessage(body); + case PONG -> new PongMessage(body); + case BLOCKS_REQUEST -> new BlocksRequestMessage(body); + case BLOCKS_REPLY -> new BlocksReplyMessage(body); + case SUMS_REQUEST -> new SumRequestMessage(body); + case SUMS_REPLY -> new SumReplyMessage(body); + case BLOCKEXT_REQUEST -> new BlockExtRequestMessage(body); + case BLOCKEXT_REPLY -> new BlockExtReplyMessage(body); + case BLOCK_REQUEST -> new BlockRequestMessage(body); + case NEW_BLOCK -> new NewBlockMessage(body); + case SYNC_BLOCK -> new SyncBlockMessage(body); + case SYNCBLOCK_REQUEST -> new SyncBlockRequestMessage(body); + }; } catch (Exception e) { throw new MessageException("Failed to decode message", e); } diff --git a/src/main/java/io/xdag/net/message/consensus/BlocksRequestMessage.java b/src/main/java/io/xdag/net/message/consensus/BlocksRequestMessage.java index 64ba3fa42..29616efb6 100644 --- a/src/main/java/io/xdag/net/message/consensus/BlocksRequestMessage.java +++ b/src/main/java/io/xdag/net/message/consensus/BlocksRequestMessage.java @@ -23,15 +23,14 @@ */ package io.xdag.net.message.consensus; -import org.apache.commons.lang3.RandomUtils; - import io.xdag.core.XdagStats; import io.xdag.net.NetDB; import io.xdag.net.message.MessageCode; +import io.xdag.utils.XdagRandomUtils; public class BlocksRequestMessage extends XdagMessage { public BlocksRequestMessage(long starttime, long endtime, XdagStats xdagStats, NetDB localNetdb) { - super(MessageCode.BLOCKS_REQUEST, null, starttime, endtime, RandomUtils.nextLong(), xdagStats, localNetdb); + super(MessageCode.BLOCKS_REQUEST, null, starttime, endtime, XdagRandomUtils.nextLong(), xdagStats, localNetdb); } public BlocksRequestMessage(byte[] body) { diff --git a/src/main/java/io/xdag/net/message/consensus/SumReplyMessage.java b/src/main/java/io/xdag/net/message/consensus/SumReplyMessage.java index 98ad16434..805e52550 100644 --- a/src/main/java/io/xdag/net/message/consensus/SumReplyMessage.java +++ b/src/main/java/io/xdag/net/message/consensus/SumReplyMessage.java @@ -54,11 +54,4 @@ public SumReplyMessage(byte[] body) { this.sum = MutableBytes.wrap(dec.readBytes()); } -// @Override -// protected SimpleEncoder encode() { -// SimpleEncoder enc = super.encode(); -// // add sum -// enc.writeBytes(sum.toArray()); -// return enc; -// } } diff --git a/src/main/java/io/xdag/net/message/consensus/SumRequestMessage.java b/src/main/java/io/xdag/net/message/consensus/SumRequestMessage.java index 1b42fda10..f6dbd1a96 100644 --- a/src/main/java/io/xdag/net/message/consensus/SumRequestMessage.java +++ b/src/main/java/io/xdag/net/message/consensus/SumRequestMessage.java @@ -23,15 +23,14 @@ */ package io.xdag.net.message.consensus; -import org.apache.commons.lang3.RandomUtils; - import io.xdag.core.XdagStats; import io.xdag.net.NetDB; import io.xdag.net.message.MessageCode; +import io.xdag.utils.XdagRandomUtils; public class SumRequestMessage extends XdagMessage { public SumRequestMessage(long starttime, long endtime, XdagStats xdagStats, NetDB localNetdb) { - super(MessageCode.SUMS_REQUEST, SumReplyMessage.class, starttime, endtime, RandomUtils.nextLong(), xdagStats, localNetdb); + super(MessageCode.SUMS_REQUEST, SumReplyMessage.class, starttime, endtime, XdagRandomUtils.nextLong(), xdagStats, localNetdb); } public SumRequestMessage(byte[] body) { diff --git a/src/main/java/io/xdag/net/message/p2p/HandshakeMessage.java b/src/main/java/io/xdag/net/message/p2p/HandshakeMessage.java index bc437047a..8d8afa176 100644 --- a/src/main/java/io/xdag/net/message/p2p/HandshakeMessage.java +++ b/src/main/java/io/xdag/net/message/p2p/HandshakeMessage.java @@ -159,9 +159,6 @@ public boolean validate(Config config) { /** * Constructs a Peer object from the handshake info. - * - * @param ip - * @return */ public Peer getPeer(String ip) { return new Peer(network, networkVersion, peerId, ip, port, clientId, capabilities, latestBlockNumber); diff --git a/src/main/java/io/xdag/net/websocket/ChannelSupervise.java b/src/main/java/io/xdag/net/websocket/ChannelSupervise.java index c47a32215..694844851 100644 --- a/src/main/java/io/xdag/net/websocket/ChannelSupervise.java +++ b/src/main/java/io/xdag/net/websocket/ChannelSupervise.java @@ -1,3 +1,26 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020-2030 The XdagJ Developers + * + * 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 io.xdag.net.websocket; import io.netty.channel.Channel; @@ -45,9 +68,9 @@ public static String findChannel(ChannelId id) { public static void send2Pools(String info) { if (!ChannelMap.isEmpty()) { - log.debug("There are active mining pools: " + showChannel()); + log.debug("There are active mining pools: {}", showChannel()); GlobalGroup.writeAndFlush(new TextWebSocketFrame(info)); - log.debug("Send info to pools successfully. Info: " + info); + log.debug("Send info to pools successfully. Info: {}", info); } else { log.debug("No active pools."); } diff --git a/src/main/java/io/xdag/net/websocket/PoolHandShakeHandler.java b/src/main/java/io/xdag/net/websocket/PoolHandShakeHandler.java index 993fde435..4bab39e34 100644 --- a/src/main/java/io/xdag/net/websocket/PoolHandShakeHandler.java +++ b/src/main/java/io/xdag/net/websocket/PoolHandShakeHandler.java @@ -1,3 +1,26 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020-2030 The XdagJ Developers + * + * 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 io.xdag.net.websocket; import io.netty.buffer.ByteBuf; diff --git a/src/main/java/io/xdag/net/websocket/WebSocketServer.java b/src/main/java/io/xdag/net/websocket/WebSocketServer.java index 96aad1275..f72807196 100644 --- a/src/main/java/io/xdag/net/websocket/WebSocketServer.java +++ b/src/main/java/io/xdag/net/websocket/WebSocketServer.java @@ -1,3 +1,26 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020-2030 The XdagJ Developers + * + * 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 io.xdag.net.websocket; import io.netty.bootstrap.ServerBootstrap; diff --git a/src/main/java/io/xdag/pool/PoolAwardManager.java b/src/main/java/io/xdag/pool/PoolAwardManager.java index 9b244db93..410b5ffd8 100644 --- a/src/main/java/io/xdag/pool/PoolAwardManager.java +++ b/src/main/java/io/xdag/pool/PoolAwardManager.java @@ -1,3 +1,26 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020-2030 The XdagJ Developers + * + * 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 io.xdag.pool; import org.apache.tuweni.bytes.Bytes32; diff --git a/src/main/java/io/xdag/pool/PoolAwardManagerImpl.java b/src/main/java/io/xdag/pool/PoolAwardManagerImpl.java index 1602a81cd..1f779e9fe 100644 --- a/src/main/java/io/xdag/pool/PoolAwardManagerImpl.java +++ b/src/main/java/io/xdag/pool/PoolAwardManagerImpl.java @@ -1,3 +1,26 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020-2030 The XdagJ Developers + * + * 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 io.xdag.pool; import io.xdag.Kernel; @@ -101,7 +124,7 @@ public void run() { payAndAddNewAwardBlock(awardBlock); } } catch (InterruptedException e) { - log.error(" Can not take the awardBlock from awardBlockQueue" + e.getMessage(), e); + log.error(" Can not take the awardBlock from awardBlockQueue{}", e.getMessage(), e); } } } @@ -118,7 +141,7 @@ public void init() { public void payAndAddNewAwardBlock(AwardBlock awardBlock) { int awardBlockIndex = (int) ((awardBlock.generateTime >> 16) & config.getNodeSpec().getAwardEpoch()); - log.debug("Add reward block to index: " + awardBlockIndex); + log.debug("Add reward block to index: {}", awardBlockIndex); if (payPools(awardBlock.generateTime) == 0) { log.debug("Start distributing block rewards..."); } diff --git a/src/main/java/io/xdag/utils/BasicUtils.java b/src/main/java/io/xdag/utils/BasicUtils.java index 95ed7d374..5b4b86cff 100644 --- a/src/main/java/io/xdag/utils/BasicUtils.java +++ b/src/main/java/io/xdag/utils/BasicUtils.java @@ -126,8 +126,7 @@ public static UInt64 xdag2amount(double input) { input -= amount; // 小数部分 input = input * Math.pow(2, 32); long tmp = (long) Math.ceil(input); - UInt64 result = res.add(tmp); - return result; + return res.add(tmp); } /** diff --git a/src/main/java/io/xdag/utils/BytesUtils.java b/src/main/java/io/xdag/utils/BytesUtils.java index 0d012d689..d10695ede 100644 --- a/src/main/java/io/xdag/utils/BytesUtils.java +++ b/src/main/java/io/xdag/utils/BytesUtils.java @@ -28,7 +28,7 @@ import com.google.common.primitives.UnsignedLong; import com.sun.jna.Memory; import com.sun.jna.Pointer; -import org.apache.commons.lang3.ArrayUtils; + import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.MutableBytes32; import org.apache.tuweni.units.bigints.UInt64; @@ -135,14 +135,6 @@ public static byte[] bigIntegerToBytes(UInt64 b, int numBytes) { System.arraycopy(biBytes, start, bytes, numBytes - length, length); return bytes; } - public static byte[] longToBytes(long b, int numBytes) { - byte[] bytes = new byte[numBytes]; - byte[] biBytes = long2UnsignedLong(b).bigIntegerValue().toByteArray(); - int start = (biBytes.length == numBytes + 1) ? 1 : 0; - int length = Math.min(biBytes.length, numBytes); - System.arraycopy(biBytes, start, bytes, numBytes - length, length); - return bytes; - } public static byte[] bigIntegerToBytes(BigInteger b, int numBytes, boolean littleEndian) { byte[] bytes = bigIntegerToBytes(b, numBytes); @@ -269,22 +261,6 @@ public static boolean isFullZero(byte[] input) { return true; } - /** - * 直接将十六进制的byte[]数组转换为都变了的数据 - * - * @param input byte[]类型的hash 这里的hash 是正向排序了的 - * @param offset 偏移位置 - * @param littleEndian 是否为大小端 - */ - public static double hexBytesToDouble(byte[] input, int offset, boolean littleEndian) { - byte[] data = new byte[8]; - System.arraycopy(input, offset, data, 0, 8); - if (littleEndian) { - ArrayUtils.reverse(data); - } - return Numeric.toBigInt(data).doubleValue(); - } - public static boolean equalBytes(byte[] b1, byte[] b2) { return b1.length == b2.length && compareTo(b1, 0, b1.length, b2, 0, b2.length) == 0; } diff --git a/src/main/java/io/xdag/utils/DruidUtils.java b/src/main/java/io/xdag/utils/DruidUtils.java index c10ff4e89..b3e087418 100644 --- a/src/main/java/io/xdag/utils/DruidUtils.java +++ b/src/main/java/io/xdag/utils/DruidUtils.java @@ -24,6 +24,8 @@ package io.xdag.utils; import com.alibaba.druid.pool.DruidDataSourceFactory; + +import lombok.Getter; import lombok.extern.slf4j.Slf4j; import javax.sql.DataSource; @@ -33,6 +35,7 @@ @Slf4j public final class DruidUtils { + @Getter private static DataSource dataSource; static { @@ -46,9 +49,6 @@ public final class DruidUtils { } } - public static DataSource getDataSource() { - return dataSource; - } public static Connection getConnection(){ try { return dataSource.getConnection(); diff --git a/src/main/java/io/xdag/utils/Numeric.java b/src/main/java/io/xdag/utils/Numeric.java index 5c1090eea..d2c662cbc 100644 --- a/src/main/java/io/xdag/utils/Numeric.java +++ b/src/main/java/io/xdag/utils/Numeric.java @@ -141,8 +141,4 @@ public static String toHexString(byte[] input) { return toHexString(input, 0, input.length, true); } - public static byte asByte(int m, int n) { - return (byte) ((m << 4) | n); - } - } diff --git a/src/main/java/io/xdag/net/node/NodeStat.java b/src/main/java/io/xdag/utils/XdagRandomUtils.java similarity index 56% rename from src/main/java/io/xdag/net/node/NodeStat.java rename to src/main/java/io/xdag/utils/XdagRandomUtils.java index 367cd3ecc..b911de06c 100644 --- a/src/main/java/io/xdag/net/node/NodeStat.java +++ b/src/main/java/io/xdag/utils/XdagRandomUtils.java @@ -21,35 +21,42 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +package io.xdag.utils; -package io.xdag.net.node; +import org.apache.commons.rng.UniformRandomProvider; +import org.apache.commons.rng.simple.RandomSource; -import java.util.concurrent.atomic.AtomicLong; +public class XdagRandomUtils { -public class NodeStat { + private final static UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create(); - public final StatHandler Inbound = new StatHandler(); - public final StatHandler Outbound = new StatHandler(); + public static int nextInt() { + return rng.nextInt(); + } - public static class StatHandler { + public static int nextInt(int n) { + return rng.nextInt(n); + } - AtomicLong count = new AtomicLong(0); + public static long nextLong() { + return rng.nextLong(); + } - public void add() { - count.incrementAndGet(); - } + public static long nextLong(long n) { + return rng.nextLong(n); + } - public void add(long delta) { - count.addAndGet(delta); - } + public static void nextBytes(byte[] bytes) { + rng.nextBytes(bytes); + } - public long get() { - return count.get(); - } + public static void nextBytes(byte[] bytes, int start, int len) { + rng.nextBytes(bytes, start, len); + } - @Override - public String toString() { - return count.toString(); - } + public static byte[] nextNewBytes(int count) { + final byte[] result = new byte[count]; + rng.nextBytes(result); + return result; } } diff --git a/src/test/java/io/xdag/consensus/TaskTest.java b/src/test/java/io/xdag/consensus/TaskTest.java index 6078faf4c..2b46c0918 100644 --- a/src/test/java/io/xdag/consensus/TaskTest.java +++ b/src/test/java/io/xdag/consensus/TaskTest.java @@ -35,14 +35,13 @@ import io.xdag.crypto.Sign; import io.xdag.pool.PoolAwardManagerImpl; import io.xdag.utils.BytesUtils; +import io.xdag.utils.XdagRandomUtils; import io.xdag.utils.XdagSha256Digest; import io.xdag.utils.XdagTime; -import org.apache.commons.lang3.RandomUtils; import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes32; import org.apache.tuweni.bytes.MutableBytes; import org.hyperledger.besu.crypto.KeyPair; -import org.jline.utils.Log; import org.json.JSONObject; import org.junit.After; import org.junit.Before; @@ -119,8 +118,8 @@ public void testTaskConvertToJsonFormatTask() { // send to pool Task newTask = new Task(); XdagField[] task = new XdagField[2]; - MutableBytes preHash = MutableBytes.wrap(RandomUtils.nextBytes(32)); - MutableBytes taskSeed = MutableBytes.wrap(RandomUtils.nextBytes(32)); + MutableBytes preHash = MutableBytes.wrap(XdagRandomUtils.nextNewBytes(32)); + MutableBytes taskSeed = MutableBytes.wrap(XdagRandomUtils.nextNewBytes(32)); task[0] = new XdagField(preHash); task[0].setSum(1); task[0].setType(XdagField.FieldType.XDAG_FIELD_HEAD); @@ -161,8 +160,8 @@ public void testSend2PoolsTxInfoConvertToJsonFormat() { double fundRation = 5; PoolAwardManagerImpl.TransactionInfoSender transactionInfoSender = new PoolAwardManagerImpl.TransactionInfoSender(); - Bytes32 preHash = Bytes32.wrap(RandomUtils.nextBytes(32)); - Bytes32 txHash = Bytes32.wrap(RandomUtils.nextBytes(32)); + Bytes32 preHash = Bytes32.wrap(Bytes.random(32)); + Bytes32 txHash = Bytes32.wrap(Bytes.random(32)); transactionInfoSender.setPreHash(preHash); transactionInfoSender.setTxBlock(txHash); transactionInfoSender.setDonateBlock(txHash); @@ -175,7 +174,6 @@ public void testSend2PoolsTxInfoConvertToJsonFormat() { transactionInfoSender.setFee(MIN_GAS.toDecimal(9, XDAG).toPlainString()); XAmount amount = XAmount.of(64, XDAG); XAmount fundAmount = amount.multiply(div(fundRation, 100, 6)); - Log.info(fundAmount.toDecimal(9,XDAG).toPlainString()); transactionInfoSender.setAmount(amount.subtract(MIN_GAS).subtract(fundAmount).toDecimal(9, XDAG).toPlainString()); transactionInfoSender.setDonate(fundAmount.toDecimal(9, XDAG).toPlainString()); @@ -219,9 +217,9 @@ public void testSaveRewardDistributionMessageHistory() throws Exception { transactionInfoSender.setAmount(amount.subtract(MIN_GAS).subtract(fundAmount).toDecimal(9, XDAG).toPlainString()); transactionInfoSender.setDonate(fundAmount.toDecimal(9, XDAG).toPlainString()); for (int i = 0; i < 16; i++) { - Bytes32 preHash = Bytes32.wrap(RandomUtils.nextBytes(32)); - Bytes32 txBlock = Bytes32.wrap(RandomUtils.nextBytes(32)); - Bytes32 share = Bytes32.wrap(RandomUtils.nextBytes(32)); + Bytes32 preHash = Bytes32.wrap(XdagRandomUtils.nextNewBytes(32)); + Bytes32 txBlock = Bytes32.wrap(XdagRandomUtils.nextNewBytes(32)); + Bytes32 share = Bytes32.wrap(XdagRandomUtils.nextNewBytes(32)); transactionInfoSender.setShare(share); transactionInfoSender.setTxBlock(txBlock); transactionInfoSender.setPreHash(preHash); diff --git a/src/test/java/io/xdag/core/BlockTest.java b/src/test/java/io/xdag/core/BlockTest.java index e419bd7cb..861cea6bb 100644 --- a/src/test/java/io/xdag/core/BlockTest.java +++ b/src/test/java/io/xdag/core/BlockTest.java @@ -24,17 +24,13 @@ package io.xdag.core; -//import static io.xdag.db.BlockStore.BLOCK_AMOUNT; - import io.xdag.utils.BytesUtils; import io.xdag.utils.SimpleEncoder; import org.apache.tuweni.bytes.Bytes32; -import org.apache.tuweni.bytes.MutableBytes32; import org.bouncycastle.util.encoders.Hex; import org.junit.Test; import java.nio.ByteOrder; -import java.util.Arrays; import static org.junit.Assert.assertEquals; diff --git a/src/test/java/io/xdag/core/BlockchainTest.java b/src/test/java/io/xdag/core/BlockchainTest.java index ca2ecf357..4b51a4ad2 100644 --- a/src/test/java/io/xdag/core/BlockchainTest.java +++ b/src/test/java/io/xdag/core/BlockchainTest.java @@ -191,7 +191,7 @@ public void testExtraBlock() { Bytes32 ref = addressBlock.getHashLow(); // 2. create 10 mainblocks for (int i = 1; i <= 10; i++) { - log.debug("create No." + i + " extra block"); + log.debug("create No.{} extra block", i); generateTime += 64000L; pending.clear(); pending.add(new Address(ref, XDAG_FIELD_OUT,false)); @@ -1147,7 +1147,6 @@ public void startCheckMain(long period) { @Override public void addOurBlock(int keyIndex, Block block) { - return; } } diff --git a/src/test/java/io/xdag/core/PoWTest.java b/src/test/java/io/xdag/core/PoWTest.java index e5464b161..1c46790a9 100644 --- a/src/test/java/io/xdag/core/PoWTest.java +++ b/src/test/java/io/xdag/core/PoWTest.java @@ -32,10 +32,9 @@ import io.xdag.crypto.Sign; import io.xdag.utils.BytesUtils; import io.xdag.utils.WalletUtils; -import org.apache.commons.lang3.RandomUtils; +import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes32; import org.hyperledger.besu.crypto.KeyPair; -import org.jline.utils.Log; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -180,7 +179,6 @@ public class PoWTest { @Before public void setUp() { - String pwd = "password"; Config config = new DevnetConfig(); wallet = new Wallet(config); @@ -201,14 +199,14 @@ public void tearDown() throws IOException { public void createInitialShare() { wallet.unlock("password"); minShare.set(Bytes32.wrap(BytesUtils.merge(hash2byte(keyPair2Hash(wallet.getDefKey())), - RandomUtils.nextBytes(12)))); + Bytes.random(12).toArray()))); assertEquals(minShare.get().slice(0, 20), Bytes32.wrap(keyPair2Hash(wallet.getDefKey())).slice(8, 20)); assertEquals(minShare.get().slice(0, 20), Bytes32.wrap(keyPair2Hash(wallet.getDefKey())).slice(8, 20)); assertEquals(0, compareTo(minShare.get().slice(0, 20).reverse().toArray(), 0, 20, Bytes32.wrap(keyPair2Hash(wallet.getDefKey())).slice(8, 20).reverse().toArray(), 0, 20)); assertNotSame(minShare.get().slice(0, 20), Bytes32.wrap(keyPair2Hash(wallet.getDefKey())).slice(8, 20)); - minShare.set(Bytes32.wrap(RandomUtils.nextBytes(32))); + minShare.set(Bytes32.wrap(Bytes.random(32))); assertNotEquals(minShare.get().slice(0, 20), Bytes32.wrap(keyPair2Hash(wallet.getDefKey())).slice(8, 20)); assertNotEquals(0, compareTo(minShare.get().slice(0, 20).reverse().toArray(), 0, 20, Bytes32.wrap(keyPair2Hash(wallet.getDefKey())).slice(8, 20).reverse().toArray(), 0, 20)); @@ -224,13 +222,7 @@ public void testGetTask() { assertNull(currentTask.get().getTask()); assertNull(currentTask.get().getDigest()); assertEquals(currentTask.get().getTaskIndex(), 0); - Log.info(hash2PubAddress(hexPubAddress2Hashlow( - "46a2a0fe035c413d92be9c79a11cfc3695780f65"))); - Log.info(hash2PubAddress(hexPubAddress2Hashlow( - "46a2a0fe035c413d92be9c79a11cfc3695780f66"))); assertTrue(WalletUtils.checkAddress(hash2PubAddress(hexPubAddress2Hashlow( "46a2a0fe035c413d92be9c79a11cfc3695780f66")))); - - } } diff --git a/src/test/java/io/xdag/core/RandomXSyncTest.java b/src/test/java/io/xdag/core/RandomXSyncTest.java index c42bca425..d828f9914 100644 --- a/src/test/java/io/xdag/core/RandomXSyncTest.java +++ b/src/test/java/io/xdag/core/RandomXSyncTest.java @@ -141,7 +141,7 @@ public long addBlocks(Kernel kernel, int number) { long forkDate = 0; for (int i = 1; i <= number; i++) { - log.debug("create No." + i + " extra block"); + log.debug("create No.{} extra block", i); generateTime += 64000L; pending.clear(); pending.add(new Address(ref, XDAG_FIELD_OUT,false)); diff --git a/src/test/java/io/xdag/crypto/SignTest.java b/src/test/java/io/xdag/crypto/SignTest.java index 7cceaecb7..b69818b40 100644 --- a/src/test/java/io/xdag/crypto/SignTest.java +++ b/src/test/java/io/xdag/crypto/SignTest.java @@ -25,7 +25,6 @@ package io.xdag.crypto; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import io.xdag.core.Block; diff --git a/src/test/java/io/xdag/db/SnapshotStoreTest.java b/src/test/java/io/xdag/db/SnapshotStoreTest.java index f108061fe..8e2ac1a91 100644 --- a/src/test/java/io/xdag/db/SnapshotStoreTest.java +++ b/src/test/java/io/xdag/db/SnapshotStoreTest.java @@ -36,7 +36,6 @@ import io.xdag.db.rocksdb.*; import io.xdag.crypto.RandomX; import io.xdag.utils.BasicUtils; -import io.xdag.utils.BytesUtils; import io.xdag.utils.XdagTime; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; @@ -63,7 +62,6 @@ import static io.xdag.core.ImportResult.IMPORTED_NOT_BEST; import static io.xdag.core.XdagField.FieldType.XDAG_FIELD_IN; import static io.xdag.core.XdagField.FieldType.XDAG_FIELD_OUT; -import static io.xdag.db.rocksdb.BlockStoreImpl.HASH_BLOCK_INFO; import static org.junit.Assert.*; @Slf4j diff --git a/src/test/java/io/xdag/db/mysql/TransactionHistoryStoreImplTest.java b/src/test/java/io/xdag/db/mysql/TransactionHistoryStoreImplTest.java index e4355d89f..a97ab10a6 100644 --- a/src/test/java/io/xdag/db/mysql/TransactionHistoryStoreImplTest.java +++ b/src/test/java/io/xdag/db/mysql/TransactionHistoryStoreImplTest.java @@ -44,7 +44,6 @@ import java.sql.SQLException; import java.sql.Statement; import java.util.List; -import java.util.Random; import static io.xdag.utils.BasicUtils.hash2Address; import static io.xdag.utils.BasicUtils.hash2byte; diff --git a/src/test/java/io/xdag/rpc/Web3XdagModuleTest.java b/src/test/java/io/xdag/rpc/Web3XdagModuleTest.java index 114503b2c..2f2ee83a0 100644 --- a/src/test/java/io/xdag/rpc/Web3XdagModuleTest.java +++ b/src/test/java/io/xdag/rpc/Web3XdagModuleTest.java @@ -44,7 +44,6 @@ import org.junit.rules.TemporaryFolder; import java.io.IOException; -import java.math.BigInteger; import java.util.Collections; public class Web3XdagModuleTest { diff --git a/src/test/java/io/xdag/wallet/WalletUtilsTest.java b/src/test/java/io/xdag/wallet/WalletUtilsTest.java index 6f16fb926..9d17931c2 100644 --- a/src/test/java/io/xdag/wallet/WalletUtilsTest.java +++ b/src/test/java/io/xdag/wallet/WalletUtilsTest.java @@ -31,14 +31,12 @@ import io.xdag.crypto.Keys; import io.xdag.crypto.SampleKeys; import io.xdag.crypto.Sign; -import io.xdag.utils.BasicUtils; import io.xdag.utils.BytesUtils; import io.xdag.utils.MnemonicUtils; import io.xdag.utils.WalletUtils; import org.apache.tuweni.bytes.Bytes32; import org.apache.tuweni.io.Base58; import org.hyperledger.besu.crypto.KeyPair; -import org.jline.utils.Log; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -142,8 +140,8 @@ public void generateBip44KeyPairTestNet() { public void testCheckIsAddress() { String walletAddress="KD77RGFihFaqrJQrKK8MJ21hocJeq32Pf"; assertTrue(io.xdag.crypto.Base58.checkAddress(walletAddress)); - Log.info(BasicUtils.pubAddress2Hash(walletAddress)); } + @Test public void testHashlowIsAddress(){ Bytes32 addressHashlow1 = Bytes32.fromHexString( @@ -154,10 +152,6 @@ public void testHashlowIsAddress(){ assertEquals(0,addressHashlow2.slice(28,4).toInt()); assertFalse(checkAddress(addressHashlow1)); assertTrue(checkAddress(addressHashlow2)); - Log.info(BasicUtils.hexPubAddress2Hashlow("0x46a2a0fe035c413d92be9c79a11cfc3695780f65")); - Log.info(BasicUtils.hash2PubAddress(BasicUtils.hexPubAddress2Hashlow( - "46a2a0fe035c413d92be9c79a11cfc3695780f65"))); - } @After @@ -165,6 +159,5 @@ public void tearDown() throws IOException { wallet.delete(); } - }