From 448997e882c9887361ebef19294768b69fef0973 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 25 Sep 2023 18:43:29 +0000 Subject: [PATCH 01/19] Bump org.xerial.snappy:snappy-java from 1.1.10.1 to 1.1.10.4 Bumps [org.xerial.snappy:snappy-java](https://github.com/xerial/snappy-java) from 1.1.10.1 to 1.1.10.4. - [Release notes](https://github.com/xerial/snappy-java/releases) - [Commits](https://github.com/xerial/snappy-java/compare/v1.1.10.1...v1.1.10.4) --- updated-dependencies: - dependency-name: org.xerial.snappy:snappy-java dependency-type: direct:production ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 3d2e8df8..e574b2f7 100644 --- a/pom.xml +++ b/pom.xml @@ -47,7 +47,7 @@ 4.0.1 1.4.2 1.17.1 - 1.1.10.1 + 1.1.10.4 1.2.18 8.0.33 2.2.220 From 2148ba830deeb36abfe32a7009217e15239e9c12 Mon Sep 17 00:00:00 2001 From: xdager <55344427+xdager@users.noreply.github.com> Date: Fri, 22 Mar 2024 15:33:55 +0800 Subject: [PATCH 02/19] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index aa11d056..313e942e 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ Four stages: - [x] Introduce the Stratum protocol for miners -- [ ] Lightweight wallet application: connect to MetaMask, join the browser wallet +- [x] Lightweight wallet application: connect to MetaMask, join the browser wallet - [x] Standardize the format of public and private keys, follow the BIPXX specification, and add mnemonic words to generate public and private key pairs @@ -85,7 +85,7 @@ Four stages: - [x] Improve the address block structure -- [ ] Increase the handling fee +- [x] Increase the handling fee - [x] Optimize wallets to improve the user experience From c7c7e93951766c1edc40442ae5718137ebb2ccea Mon Sep 17 00:00:00 2001 From: xdager <55344427+xdager@users.noreply.github.com> Date: Fri, 22 Mar 2024 15:50:29 +0800 Subject: [PATCH 03/19] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 313e942e..63f4bce5 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ Four stages: - [x] Optimize wallets to improve the user experience -- [ ] Support smart contracts, implement EVM that supports Solidity, and be compatible with Ethereum smart contracts +- [ ] Support XRC standards - [x] Decrease the threshold of mining pool users From 64d7f4ff1798280ff808300a34eb165a77f11f11 Mon Sep 17 00:00:00 2001 From: xdager <55344427+xdager@users.noreply.github.com> Date: Fri, 22 Mar 2024 16:08:24 +0800 Subject: [PATCH 04/19] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 63f4bce5..298454d5 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ Four stages: - [x] Standardize the format of public and private keys, follow the BIPXX specification, and add mnemonic words to generate public and private key pairs -#### Expansion phase: XDAGJ & EVM +#### Expansion phase: XDAGJ & XRC - [x] Improve the address block structure From 85ef87a052a2c40c61b8d4d9d88cf387c6f69e9b Mon Sep 17 00:00:00 2001 From: xdager <55344427+xdager@users.noreply.github.com> Date: Thu, 11 Apr 2024 11:10:09 +0800 Subject: [PATCH 05/19] Update README_zh.md --- docs/README_zh.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/README_zh.md b/docs/README_zh.md index c0c9b611..e2a04e81 100644 --- a/docs/README_zh.md +++ b/docs/README_zh.md @@ -75,17 +75,17 @@ XDAGJ教程可以让您快速加入并体验XDAGJ的钱包及挖矿功能,私 - [x] 挖矿协议改进:引入较成熟的Stratum协议,方便矿机的接入与使用 -- [ ] 轻量级钱包应用:接入MateMask,加入浏览器钱包 +- [x] 轻量级钱包应用:加入浏览器钱包 - [x] 规范公私钥格式,遵循BIPXX规范,加入助记词方式生成公私钥对 #### 拓展阶段:XDAGJ & EVM 拓展 -- [ ] 修改地址块结构,增加手续费 +- [x] 修改地址块结构,增加手续费 - [x] 优化改善移动端钱包,提高用户体验 -- [ ] 开放智能合约,实现支持Solidity的EVM,兼容以太坊智能合约 +- [ ] 支持XRC协议 - [ ] 降低矿池门槛,逐步开放白名单从而实现完全去中心化 From eb27f117eaa8ae52d121b9327a026d534af332ef Mon Sep 17 00:00:00 2001 From: xdager <55344427+xdager@users.noreply.github.com> Date: Thu, 11 Apr 2024 11:42:09 +0800 Subject: [PATCH 06/19] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 298454d5..3920c802 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ Four stages: - [x] Introduce the Stratum protocol for miners -- [x] Lightweight wallet application: connect to MetaMask, join the browser wallet +- [x] Lightweight wallet application: join the browser wallet - [x] Standardize the format of public and private keys, follow the BIPXX specification, and add mnemonic words to generate public and private key pairs From 49083ad565683dfd4e86a82b2e9aa070461482a9 Mon Sep 17 00:00:00 2001 From: LucasMLK Date: Sat, 27 Apr 2024 21:11:28 +0800 Subject: [PATCH 07/19] update version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 47091d57..e9f753ed 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ io.xdag xdagj - 0.7.0 + 0.7.1 UTF-8 From 1d92e4b96fe095ca53ae613e3878e52a74193cbf Mon Sep 17 00:00:00 2001 From: LucasMLK Date: Thu, 9 May 2024 10:50:00 +0800 Subject: [PATCH 08/19] upgrade maven dependency and refactor XdagRandomUtils use commons-rng --- pom.xml | 71 ++++++++++--------- src/main/java/io/xdag/Kernel.java | 2 +- src/main/java/io/xdag/Launcher.java | 1 - src/main/java/io/xdag/Wallet.java | 20 +++--- src/main/java/io/xdag/cli/Commands.java | 16 ++--- src/main/java/io/xdag/cli/Shell.java | 5 +- .../java/io/xdag/config/AbstractConfig.java | 6 +- src/main/java/io/xdag/config/Constants.java | 1 - .../java/io/xdag/consensus/SyncManager.java | 5 +- src/main/java/io/xdag/consensus/XdagPow.java | 21 +++--- src/main/java/io/xdag/consensus/XdagSync.java | 13 ++-- src/main/java/io/xdag/core/Address.java | 2 +- .../java/io/xdag/core/BlockchainImpl.java | 32 ++------- src/main/java/io/xdag/core/Filter.java | 45 ------------ src/main/java/io/xdag/core/ImportResult.java | 6 +- src/main/java/io/xdag/core/PreBlockInfo.java | 1 - src/main/java/io/xdag/crypto/RandomX.java | 6 +- .../java/io/xdag/db/OrphanBlockStore.java | 1 - .../db/mysql/TransactionHistoryStoreImpl.java | 8 +-- .../io/xdag/db/rocksdb/BlockStoreImpl.java | 4 +- .../xdag/db/rocksdb/OrphanBlockStoreImpl.java | 6 +- .../io/xdag/db/rocksdb/RocksdbKVSource.java | 49 +++++-------- .../io/xdag/db/rocksdb/SnapshotStoreImpl.java | 2 +- src/main/java/io/xdag/net/Channel.java | 2 +- src/main/java/io/xdag/net/ChannelManager.java | 5 +- src/main/java/io/xdag/net/NetDB.java | 21 ++---- src/main/java/io/xdag/net/Peer.java | 11 +-- src/main/java/io/xdag/net/XdagP2pHandler.java | 3 +- .../java/io/xdag/net/message/Message.java | 1 - .../java/io/xdag/net/message/MessageCode.java | 2 +- .../io/xdag/net/message/MessageFactory.java | 56 +++++---------- .../consensus/BlocksRequestMessage.java | 5 +- .../message/consensus/SumReplyMessage.java | 7 -- .../message/consensus/SumRequestMessage.java | 5 +- .../net/message/p2p/HandshakeMessage.java | 3 - src/main/java/io/xdag/net/node/NodeStat.java | 55 -------------- .../xdag/net/websocket/ChannelSupervise.java | 4 +- .../io/xdag/pool/PoolAwardManagerImpl.java | 4 +- src/main/java/io/xdag/utils/BasicUtils.java | 3 +- src/main/java/io/xdag/utils/BytesUtils.java | 26 +------ src/main/java/io/xdag/utils/DruidUtils.java | 6 +- src/main/java/io/xdag/utils/Numeric.java | 4 -- .../java/io/xdag/utils/XdagRandomUtils.java | 39 ++++++++++ src/test/java/io/xdag/consensus/TaskTest.java | 18 +++-- src/test/java/io/xdag/core/BlockTest.java | 4 -- .../java/io/xdag/core/BlockchainTest.java | 3 +- src/test/java/io/xdag/core/PoWTest.java | 14 +--- .../java/io/xdag/core/RandomXSyncTest.java | 2 +- src/test/java/io/xdag/crypto/SignTest.java | 1 - .../java/io/xdag/db/SnapshotStoreTest.java | 2 - .../TransactionHistoryStoreImplTest.java | 1 - .../java/io/xdag/rpc/Web3XdagModuleTest.java | 1 - .../java/io/xdag/wallet/WalletUtilsTest.java | 9 +-- 53 files changed, 212 insertions(+), 428 deletions(-) delete mode 100644 src/main/java/io/xdag/core/Filter.java delete mode 100644 src/main/java/io/xdag/net/node/NodeStat.java create mode 100644 src/main/java/io/xdag/utils/XdagRandomUtils.java diff --git a/pom.xml b/pom.xml index e9f753ed..6649d97a 100644 --- a/pom.xml +++ b/pom.xml @@ -17,38 +17,39 @@ package ${project.basedir}/dist - 4.1.107.Final + 4.1.108.Final 2.3.1 - 2.14.2 - 5.4.0 - 1.18.26 - 3.1.5 - 3.25.0 + 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 **/*RandomXSyncTest.java,**/*SyncTest.java,**/*SnapshotJTest.java @@ -90,6 +91,11 @@ hyperledger.jfrog.io https://hyperledger.jfrog.io/artifactory/besu-maven/ + + maven_central + Maven Central + https://repo.maven.apache.org/maven2/ + @@ -432,6 +438,12 @@ ${commons-collections4.version} + + org.apache.commons + commons-rng-simple + ${commons-rng.version} + + commons-codec commons-codec @@ -901,16 +913,11 @@ druid ${druid.version} + com.google.code.gson gson - 2.9.0 - test - - - com.google.code.gson - gson - 2.9.0 + 2.10 compile diff --git a/src/main/java/io/xdag/Kernel.java b/src/main/java/io/xdag/Kernel.java index 2f50923b..05f45d92 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 34ef9155..a50baf20 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 c32bb552..48de36b3 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 c8e4a157..e0d0f7db 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 4966dc5b..25969f61 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 5e636b8f..d6a6b599 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 94d91edb..44afc134 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/consensus/SyncManager.java b/src/main/java/io/xdag/consensus/SyncManager.java index 5db884e0..7f9f6bc0 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 42cb9e2a..167b5b96 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 a32bb6a9..c4861139 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 13fb3d19..5156e59e 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 efff211c..4e300dcf 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 95e86bc1..00000000 --- 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 3f816be8..3ec1470e 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 e58c3914..3c6fc935 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 98e10628..d2ade820 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 fd8f6f9a..8d0152bd 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 230e275b..1778c369 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 1de8b56e..39babb90 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 f1fb1bbc..68a2bfcb 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 efab6ad3..e4e7128f 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 2abc638d..4e4006d5 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 37860721..e969b110 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 dfa2ab2b..f2be1eca 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 bd8f5999..acbf8959 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 3c8901d3..a625257d 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 07a9398d..ed972566 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 49b6a2b3..cd58befe 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 b9a34fd5..c8f9c269 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 998c5678..71fdc8ae 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 64ba3fa4..29616efb 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 98ad1643..805e5255 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 1b42fda1..f6dbd1a9 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 bc437047..8d8afa17 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/node/NodeStat.java b/src/main/java/io/xdag/net/node/NodeStat.java deleted file mode 100644 index 367cd3ec..00000000 --- a/src/main/java/io/xdag/net/node/NodeStat.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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.node; - -import java.util.concurrent.atomic.AtomicLong; - -public class NodeStat { - - public final StatHandler Inbound = new StatHandler(); - public final StatHandler Outbound = new StatHandler(); - - public static class StatHandler { - - AtomicLong count = new AtomicLong(0); - - public void add() { - count.incrementAndGet(); - } - - public void add(long delta) { - count.addAndGet(delta); - } - - public long get() { - return count.get(); - } - - @Override - public String toString() { - return count.toString(); - } - } -} diff --git a/src/main/java/io/xdag/net/websocket/ChannelSupervise.java b/src/main/java/io/xdag/net/websocket/ChannelSupervise.java index c47a3221..876f15d1 100644 --- a/src/main/java/io/xdag/net/websocket/ChannelSupervise.java +++ b/src/main/java/io/xdag/net/websocket/ChannelSupervise.java @@ -45,9 +45,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/pool/PoolAwardManagerImpl.java b/src/main/java/io/xdag/pool/PoolAwardManagerImpl.java index 1602a81c..92af6643 100644 --- a/src/main/java/io/xdag/pool/PoolAwardManagerImpl.java +++ b/src/main/java/io/xdag/pool/PoolAwardManagerImpl.java @@ -101,7 +101,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 +118,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 95ed7d37..5b4b86cf 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 0d012d68..d10695ed 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 c10ff4e8..b3e08741 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 5c1090ee..d2c662cb 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/utils/XdagRandomUtils.java b/src/main/java/io/xdag/utils/XdagRandomUtils.java new file mode 100644 index 00000000..0612872a --- /dev/null +++ b/src/main/java/io/xdag/utils/XdagRandomUtils.java @@ -0,0 +1,39 @@ +package io.xdag.utils; + +import org.apache.commons.rng.UniformRandomProvider; +import org.apache.commons.rng.simple.RandomSource; + +public class XdagRandomUtils { + + private final static UniformRandomProvider rng = RandomSource.XO_RO_SHI_RO_128_PP.create(); + + public static int nextInt() { + return rng.nextInt(); + } + + public static int nextInt(int n) { + return rng.nextInt(n); + } + + public static long nextLong() { + return rng.nextLong(); + } + + public static long nextLong(long n) { + return rng.nextLong(n); + } + + public static void nextBytes(byte[] bytes) { + rng.nextBytes(bytes); + } + + public static void nextBytes(byte[] bytes, int start, int len) { + rng.nextBytes(bytes, start, len); + } + + 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 6078faf4..2b46c091 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 e419bd7c..861cea6b 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 ca2ecf35..4b51a4ad 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 e5464b16..1c46790a 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 c42bca42..d828f991 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 7cceaecb..b69818b4 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 f108061f..8e2ac1a9 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 e4355d89..a97ab10a 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 114503b2..2f2ee83a 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 6f16fb92..9d17931c 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(); } - } From 4f55a445d669db1fd4bedda848f4b93a74518cb2 Mon Sep 17 00:00:00 2001 From: LucasMLK Date: Thu, 9 May 2024 11:28:06 +0800 Subject: [PATCH 09/19] upgrade maven dependency --- pom.xml | 46 +++++++++++----------------------------------- 1 file changed, 11 insertions(+), 35 deletions(-) diff --git a/pom.xml b/pom.xml index 6649d97a..841f427c 100644 --- a/pom.xml +++ b/pom.xml @@ -11,15 +11,15 @@ UTF-8 UTF-8 - 1.7.22 + 1.8.21 17 17 package ${project.basedir}/dist 4.1.108.Final - 2.3.1 - 2.17.1 + 2.4.2 + 2.17.1 5.5.0 1.18.32 3.1.8 @@ -50,6 +50,7 @@ 1.2.22 8.4.0 2.2.224 + 2.10 **/*RandomXSyncTest.java,**/*SyncTest.java,**/*SnapshotJTest.java @@ -67,35 +68,10 @@ - - 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/ - - maven_central - Maven Central - https://repo.maven.apache.org/maven2/ - @@ -631,7 +607,7 @@ - org.apache.tuweni + io.tmio tuweni-bytes ${tuweni.version} @@ -647,7 +623,7 @@ - org.apache.tuweni + io.tmio tuweni-units ${tuweni.version} @@ -659,7 +635,7 @@ - org.apache.tuweni + io.tmio tuweni-io ${tuweni.version} @@ -805,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} @@ -917,7 +893,7 @@ com.google.code.gson gson - 2.10 + ${gson.version} compile From 0bb7c29b2e6350e18d939e93532a95354ec93aa3 Mon Sep 17 00:00:00 2001 From: LucasMLK Date: Thu, 9 May 2024 11:29:10 +0800 Subject: [PATCH 10/19] license format --- .../java/io/xdag/config/spec/FundSpec.java | 23 +++++++++++++++++++ .../xdag/net/websocket/ChannelSupervise.java | 23 +++++++++++++++++++ .../net/websocket/PoolHandShakeHandler.java | 23 +++++++++++++++++++ .../xdag/net/websocket/WebSocketServer.java | 23 +++++++++++++++++++ .../java/io/xdag/pool/PoolAwardManager.java | 23 +++++++++++++++++++ .../io/xdag/pool/PoolAwardManagerImpl.java | 23 +++++++++++++++++++ .../java/io/xdag/utils/XdagRandomUtils.java | 23 +++++++++++++++++++ 7 files changed, 161 insertions(+) diff --git a/src/main/java/io/xdag/config/spec/FundSpec.java b/src/main/java/io/xdag/config/spec/FundSpec.java index f15254ae..5a74e507 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/net/websocket/ChannelSupervise.java b/src/main/java/io/xdag/net/websocket/ChannelSupervise.java index 876f15d1..69484485 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; diff --git a/src/main/java/io/xdag/net/websocket/PoolHandShakeHandler.java b/src/main/java/io/xdag/net/websocket/PoolHandShakeHandler.java index 993fde43..4bab39e3 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 96aad127..f7280719 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 9b244db9..410b5ffd 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 92af6643..1f779e9f 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; diff --git a/src/main/java/io/xdag/utils/XdagRandomUtils.java b/src/main/java/io/xdag/utils/XdagRandomUtils.java index 0612872a..b911de06 100644 --- a/src/main/java/io/xdag/utils/XdagRandomUtils.java +++ b/src/main/java/io/xdag/utils/XdagRandomUtils.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.utils; import org.apache.commons.rng.UniformRandomProvider; From 6a355af1afb8a45cbac146e78ea69d0d59089108 Mon Sep 17 00:00:00 2001 From: LucasMLK Date: Fri, 10 May 2024 16:36:59 +0800 Subject: [PATCH 11/19] remove websocket and add jws-api dependency --- pom.xml | 12 +- src/main/java/io/xdag/Kernel.java | 46 +---- .../java/io/xdag/config/AbstractConfig.java | 20 -- src/main/java/io/xdag/config/Config.java | 2 - .../java/io/xdag/config/spec/RPCSpec.java | 1 - .../Web3ResultWebSocketResponseHandler.java | 42 ---- .../xdag/rpc/netty/Web3WebSocketServer.java | 102 ---------- .../io/xdag/rpc/netty/XdagJsonRpcHandler.java | 75 ------- .../rpc/netty/Web3WebSocketServerTest.java | 188 ------------------ 9 files changed, 8 insertions(+), 480 deletions(-) delete mode 100644 src/main/java/io/xdag/rpc/netty/Web3ResultWebSocketResponseHandler.java delete mode 100644 src/main/java/io/xdag/rpc/netty/Web3WebSocketServer.java delete mode 100644 src/main/java/io/xdag/rpc/netty/XdagJsonRpcHandler.java delete mode 100644 src/test/java/io/xdag/rpc/netty/Web3WebSocketServerTest.java diff --git a/pom.xml b/pom.xml index 841f427c..29ccbea6 100644 --- a/pom.xml +++ b/pom.xml @@ -51,6 +51,7 @@ 8.4.0 2.2.224 2.10 + 2.1.0 **/*RandomXSyncTest.java,**/*SyncTest.java,**/*SnapshotJTest.java @@ -370,7 +371,6 @@ - io.xdag xdagj-native-randomx @@ -796,7 +796,6 @@ ${jackson.version} - com.github.briandilley.jsonrpc4j jsonrpc4j @@ -850,22 +849,25 @@ + + jakarta.jws + jakarta.jws-api + ${jws-api.version} + + - com.typesafe config ${config.version} - org.agrona agrona ${agrona.version} - org.xerial.snappy snappy-java diff --git a/src/main/java/io/xdag/Kernel.java b/src/main/java/io/xdag/Kernel.java index 05f45d92..c2aa5eb0 100644 --- a/src/main/java/io/xdag/Kernel.java +++ b/src/main/java/io/xdag/Kernel.java @@ -41,15 +41,12 @@ import io.xdag.net.*; import io.xdag.net.message.MessageQueue; import io.xdag.net.node.NodeManager; -import io.xdag.net.websocket.WebSocketServer; import io.xdag.pool.PoolAwardManagerImpl; import io.xdag.rpc.Web3; import io.xdag.rpc.Web3Impl; import io.xdag.rpc.cors.CorsConfiguration; import io.xdag.rpc.modules.xdag.*; import io.xdag.rpc.netty.*; -import io.xdag.rpc.serialize.JacksonBasedRpcSerializer; -import io.xdag.rpc.serialize.JsonRpcSerializer; import io.xdag.utils.XdagTime; import lombok.Getter; import lombok.Setter; @@ -92,7 +89,6 @@ public class Kernel { protected byte[] firstAccount; protected Block firstBlock; - protected WebSocketServer webSocketServer; protected PoolAwardManagerImpl poolAwardManager; protected XdagState xdagState; @@ -112,10 +108,8 @@ public class Kernel { // rpc private JsonRpcWeb3ServerHandler jsonRpcWeb3ServerHandler; private Web3 web3; - private Web3WebSocketServer web3WebSocketServer; private Web3HttpServer web3HttpServer; private JsonRpcWeb3FilterHandler jsonRpcWeb3FilterHandler; - private JacksonBasedRpcSerializer jacksonBasedRpcSerializer; public Kernel(Config config, Wallet wallet) { this.config = config; @@ -283,7 +277,7 @@ public synchronized void testStart() throws Exception { // pow // ==================================== pow = new XdagPow(this); - getWsServer().start(); + log.info("Node to pool websocket start..."); // register pow blockchain.registerListener(pow); @@ -300,7 +294,6 @@ public synchronized void testStart() throws Exception { // ==================================== if (config.getRPCSpec().isRPCEnabled()) { getWeb3HttpServer().start(); - getWeb3WebSocketServer().start(); } // ==================================== @@ -342,29 +335,6 @@ private JsonRpcWeb3ServerHandler getJsonRpcWeb3ServerHandler() { return jsonRpcWeb3ServerHandler; } - public WebSocketServer getWsServer() { - if (webSocketServer == null) { - webSocketServer = new WebSocketServer(this, config.getPoolWhiteIPList(), - config.getWebsocketServerPort()); - } - return webSocketServer; - } - - private Web3WebSocketServer getWeb3WebSocketServer() throws UnknownHostException { - if (web3WebSocketServer == null) { - JsonRpcSerializer jsonRpcSerializer = getJsonRpcSerializer(); - XdagJsonRpcHandler jsonRpcHandler = new XdagJsonRpcHandler(jsonRpcSerializer); - web3WebSocketServer = new Web3WebSocketServer( - InetAddress.getByName(config.getRPCSpec().getRPCHost()), - config.getRPCSpec().getRPCPortByWebSocket(), - jsonRpcHandler, - getJsonRpcWeb3ServerHandler() - ); - } - - return web3WebSocketServer; - } - private Web3HttpServer getWeb3HttpServer() throws UnknownHostException { if (web3HttpServer == null) { web3HttpServer = new Web3HttpServer( @@ -393,14 +363,6 @@ private JsonRpcWeb3FilterHandler getJsonRpcWeb3FilterHandler() throws UnknownHos return jsonRpcWeb3FilterHandler; } - private JsonRpcSerializer getJsonRpcSerializer() { - if (jacksonBasedRpcSerializer == null) { - jacksonBasedRpcSerializer = new JacksonBasedRpcSerializer(); - } - - return jacksonBasedRpcSerializer; - } - /** * Stops the kernel. */ @@ -416,9 +378,6 @@ public synchronized void testStop() { if (web3HttpServer != null) { web3HttpServer.stop(); } - if (web3WebSocketServer != null) { - web3WebSocketServer.stop(); - } // 1. 工作层关闭 // stop consensus @@ -459,13 +418,10 @@ public synchronized void testStop() { // release randomx.randomXPoolReleaseMem(); log.info("Release randomx"); - webSocketServer.stop(); - log.info("WebSocket server stop."); poolAwardManager.stop(); log.info("Pool award manager stop."); } - public enum Status { STOPPED, SYNCING, BLOCK_PRODUCTION_ON, SYNCDONE } diff --git a/src/main/java/io/xdag/config/AbstractConfig.java b/src/main/java/io/xdag/config/AbstractConfig.java index d6a6b599..e736581c 100644 --- a/src/main/java/io/xdag/config/AbstractConfig.java +++ b/src/main/java/io/xdag/config/AbstractConfig.java @@ -57,12 +57,6 @@ public class AbstractConfig implements Config, AdminSpec, NodeSpec, WalletSpec, protected int telnetPort = 7001; protected String telnetPassword; - // ========================= - // Pool websocket spec - // ========================= - - protected int websocketServerPort; - protected int maxShareCountPerChannel = 20; protected int awardEpoch = 0xf; protected int waitEpoch = 32; @@ -144,7 +138,6 @@ public class AbstractConfig implements Config, AdminSpec, NodeSpec, WalletSpec, protected boolean rpcEnabled = false; protected String rpcHost; protected int rpcPortHttp; - protected int rpcPortWs; // ========================= // Xdag Snapshot @@ -253,7 +246,6 @@ 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; 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"; @@ -277,7 +269,6 @@ public void getSetting() { if (rpcEnabled) { rpcHost = config.hasPath("rpc.http.host") ? config.getString("rpc.http.host") : "127.0.0.1"; rpcPortHttp = config.hasPath("rpc.http.port") ? config.getInt("rpc.http.port") : 10001; - rpcPortWs = config.hasPath("rpc.ws.port") ? config.getInt("rpc.ws.port") : 10002; } flag = config.hasPath("randomx.flags.fullmem") && config.getBoolean("randomx.flags.fullmem"); @@ -391,12 +382,6 @@ public List getPoolWhiteIPList() { return poolWhiteIPList; } - @Override - public int getWebsocketServerPort() { - return websocketServerPort; - } - - @Override public boolean isRPCEnabled() { return rpcEnabled; @@ -412,11 +397,6 @@ public int getRPCPortByHttp() { return rpcPortHttp; } - @Override - public int getRPCPortByWebSocket() { - return rpcPortWs; - } - @Override public boolean isSnapshotEnabled() { return snapshotEnabled; diff --git a/src/main/java/io/xdag/config/Config.java b/src/main/java/io/xdag/config/Config.java index a2c0744a..e7384521 100644 --- a/src/main/java/io/xdag/config/Config.java +++ b/src/main/java/io/xdag/config/Config.java @@ -96,8 +96,6 @@ public interface Config { //websocket List getPoolWhiteIPList(); - int getWebsocketServerPort(); - FundSpec getFundSpec(); } diff --git a/src/main/java/io/xdag/config/spec/RPCSpec.java b/src/main/java/io/xdag/config/spec/RPCSpec.java index c2c25c28..58248e9e 100644 --- a/src/main/java/io/xdag/config/spec/RPCSpec.java +++ b/src/main/java/io/xdag/config/spec/RPCSpec.java @@ -37,5 +37,4 @@ public interface RPCSpec { int getRPCPortByHttp(); - int getRPCPortByWebSocket(); } diff --git a/src/main/java/io/xdag/rpc/netty/Web3ResultWebSocketResponseHandler.java b/src/main/java/io/xdag/rpc/netty/Web3ResultWebSocketResponseHandler.java deleted file mode 100644 index 165c853c..00000000 --- a/src/main/java/io/xdag/rpc/netty/Web3ResultWebSocketResponseHandler.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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.rpc.netty; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; - -public class Web3ResultWebSocketResponseHandler extends SimpleChannelInboundHandler { - - @Override - protected void channelRead0(ChannelHandlerContext ctx, Web3Result msg) { - ctx.write(new TextWebSocketFrame(msg.getContent())); - } - - @Override - public void channelReadComplete(ChannelHandlerContext ctx) { - ctx.flush(); - } -} diff --git a/src/main/java/io/xdag/rpc/netty/Web3WebSocketServer.java b/src/main/java/io/xdag/rpc/netty/Web3WebSocketServer.java deleted file mode 100644 index cef0b5f2..00000000 --- a/src/main/java/io/xdag/rpc/netty/Web3WebSocketServer.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * 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.rpc.netty; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.SocketChannel; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import io.netty.handler.codec.http.HttpObjectAggregator; -import io.netty.handler.codec.http.HttpServerCodec; -import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; -import java.net.InetAddress; -import java.util.Objects; -import javax.annotation.Nullable; -import lombok.extern.slf4j.Slf4j; - -@Slf4j -public class Web3WebSocketServer { - private final InetAddress host; - private final int port; - private final XdagJsonRpcHandler jsonRpcHandler; - private final JsonRpcWeb3ServerHandler web3ServerHandler; - private final EventLoopGroup bossGroup; - private final EventLoopGroup workerGroup; - private @Nullable ChannelFuture webSocketChannel; - - public Web3WebSocketServer( - InetAddress host, - int port, - XdagJsonRpcHandler jsonRpcHandler, - JsonRpcWeb3ServerHandler web3ServerHandler) { - this.host = host; - this.port = port; - this.jsonRpcHandler = jsonRpcHandler; - this.web3ServerHandler = web3ServerHandler; - this.bossGroup = new NioEventLoopGroup(); - this.workerGroup = new NioEventLoopGroup(); - } - - public void start() { - log.info("RPC WebSocket enabled"); - ServerBootstrap b = new ServerBootstrap(); - b.group(bossGroup, workerGroup) - .channel(NioServerSocketChannel.class) - .childHandler(new ChannelInitializer() { - @Override - protected void initChannel(SocketChannel ch) { - ChannelPipeline p = ch.pipeline(); - p.addLast(new HttpServerCodec()); - p.addLast(new HttpObjectAggregator(1024 * 1024 * 5)); - p.addLast(new WebSocketServerProtocolHandler("/websocket")); - p.addLast(jsonRpcHandler); - p.addLast(web3ServerHandler); - p.addLast(new Web3ResultWebSocketResponseHandler()); - } - }); - webSocketChannel = b.bind(host, port); - try { - webSocketChannel.sync(); - } catch (InterruptedException e) { - log.error("The RPC WebSocket server couldn't be started", e); - Thread.currentThread().interrupt(); - } - } - - public void stop() { - try { - Objects.requireNonNull(webSocketChannel).channel().close().sync(); - } catch (InterruptedException e) { - log.error("Couldn't stop the RPC WebSocket server", e); - Thread.currentThread().interrupt(); - } - this.bossGroup.shutdownGracefully(); - this.workerGroup.shutdownGracefully(); - } -} diff --git a/src/main/java/io/xdag/rpc/netty/XdagJsonRpcHandler.java b/src/main/java/io/xdag/rpc/netty/XdagJsonRpcHandler.java deleted file mode 100644 index 9adaa618..00000000 --- a/src/main/java/io/xdag/rpc/netty/XdagJsonRpcHandler.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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.rpc.netty; - -import io.netty.buffer.ByteBufHolder; -import io.netty.buffer.ByteBufInputStream; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; -import io.xdag.rpc.jsonrpc.JsonRpcIdentifiableMessage; -import io.xdag.rpc.jsonrpc.JsonRpcResultOrError; -import io.xdag.rpc.modules.XdagJsonRpcRequest; -import io.xdag.rpc.modules.XdagJsonRpcRequestVisitor; -import io.xdag.rpc.serialize.JsonRpcSerializer; -import java.io.IOException; -import lombok.extern.slf4j.Slf4j; - -@Slf4j -public class XdagJsonRpcHandler extends SimpleChannelInboundHandler - implements XdagJsonRpcRequestVisitor { - - private final JsonRpcSerializer serializer; - - public XdagJsonRpcHandler(JsonRpcSerializer serializer) { - this.serializer = serializer; - } - - @Override - protected void channelRead0(ChannelHandlerContext ctx, ByteBufHolder msg) { - try { - XdagJsonRpcRequest request = serializer.deserializeRequest( - new ByteBufInputStream(msg.copy().content()) - ); - - // TODO(mc) we should support the ModuleDescription method filters - JsonRpcResultOrError resultOrError = request.accept(this, ctx); - JsonRpcIdentifiableMessage response = resultOrError.responseFor(request.getId()); - ctx.writeAndFlush(new TextWebSocketFrame(serializer.serializeMessage(response))); - return; - } catch (IOException e) { - log.error("Not a known or valid JsonRpcRequest:{}", e.getMessage(), e); - } - - // delegate to the next handler if the message can't be matched to a known JSON-RPC request - ctx.fireChannelRead(msg.retain()); - } - - @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception { - super.channelInactive(ctx); - } - -} diff --git a/src/test/java/io/xdag/rpc/netty/Web3WebSocketServerTest.java b/src/test/java/io/xdag/rpc/netty/Web3WebSocketServerTest.java deleted file mode 100644 index 27d65a2e..00000000 --- a/src/test/java/io/xdag/rpc/netty/Web3WebSocketServerTest.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * 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.rpc.netty; - -import static io.xdag.rpc.netty.Web3HttpServerTest.APPLICATION_JSON; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.JsonNodeFactory; -import io.xdag.rpc.Web3; -import io.xdag.rpc.modules.ModuleDescription; -import io.xdag.rpc.serialize.JacksonBasedRpcSerializer; -import java.io.IOException; -import java.net.InetAddress; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -import lombok.SneakyThrows; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.WebSocket; -import okhttp3.WebSocketListener; -import okio.Buffer; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class Web3WebSocketServerTest { - - private static JsonNodeFactory JSON_NODE_FACTORY = JsonNodeFactory.instance; - private static ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - - private ExecutorService wsExecutor; - - @Before - public void setup() { - wsExecutor = Executors.newSingleThreadExecutor(); - } - - @Test - public void smokeTest() throws Exception { - Web3 web3Mock = mock(Web3.class); - String mockResult = "output"; - when(web3Mock.web3_sha3(anyString())).thenReturn(mockResult); - - int randomPort = 9998;//new ServerSocket(0).getLocalPort(); - - List filteredModules = Collections.singletonList( - new ModuleDescription("web3", "1.0", true, Collections.emptyList(), Collections.emptyList())); - XdagJsonRpcHandler handler = new XdagJsonRpcHandler(new JacksonBasedRpcSerializer()); - JsonRpcWeb3ServerHandler serverHandler = new JsonRpcWeb3ServerHandler(web3Mock, filteredModules); - - Web3WebSocketServer websocketServer = new Web3WebSocketServer(InetAddress.getLoopbackAddress(), randomPort, - handler, serverHandler); - websocketServer.start(); - - OkHttpClient wsClient = new OkHttpClient(); - Request wsRequest = new Request.Builder().url("ws://localhost:" + randomPort + "/websocket").build(); - - CountDownLatch wsAsyncResultLatch = new CountDownLatch(1); - CountDownLatch wsAsyncCloseLatch = new CountDownLatch(1); - AtomicReference failureReference = new AtomicReference<>(); - - wsClient.newWebSocket(wsRequest, new WebSocketListener() { - - private WebSocket webSocket; - - @Override - public void onOpen(WebSocket webSocket, Response response) { - wsExecutor.submit(() -> { - Buffer buffer = new Buffer(); - try { - RequestBody.create(getJsonRpcDummyMessage(), MediaType.get(APPLICATION_JSON)).writeTo(buffer); - } catch (IOException e) { - e.printStackTrace(); - } - String req = buffer.readUtf8(); - try { - this.webSocket = webSocket; - this.webSocket.send(req); - this.webSocket.close(1000, null); - } catch (Throwable e) { - failureReference.set(e); - } - }); - } - - @Override - public void onFailure(WebSocket webSocket, Throwable t, Response response) { - failureReference.set(t); - } - - @SneakyThrows - @Override - public void onMessage(WebSocket webSocket, String bytes) { - JsonNode jsonRpcResponse = OBJECT_MAPPER.readTree(bytes); - assertEquals(jsonRpcResponse.at("/result").asText(), mockResult); - wsAsyncResultLatch.countDown(); - } - -// @Override -// public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) { -// wsAsyncCloseLatch.countDown(); -// } - - @Override - public void onClosing(WebSocket webSocket, int code, String reason) { - wsAsyncCloseLatch.countDown(); - } - }); - - if (!wsAsyncResultLatch.await(10, TimeUnit.SECONDS)) { - fail("Result timed out"); - } - - if (!wsAsyncCloseLatch.await(10, TimeUnit.SECONDS)) { - fail("Close timed out"); - } - - websocketServer.stop(); - - Throwable failure = failureReference.get(); - if (failure != null) { - failure.printStackTrace(); - fail(failure.getMessage()); - } - } - - @After - public void tearDown() { - wsExecutor.shutdown(); - } - - private byte[] getJsonRpcDummyMessage() { - Map jsonRpcRequestProperties = new HashMap<>(); - jsonRpcRequestProperties.put("jsonrpc", JSON_NODE_FACTORY.textNode("2.0")); - jsonRpcRequestProperties.put("id", JSON_NODE_FACTORY.numberNode(13)); - jsonRpcRequestProperties.put("method", JSON_NODE_FACTORY.textNode("web3_sha3")); - jsonRpcRequestProperties.put("params", JSON_NODE_FACTORY.arrayNode().add("value")); - - byte[] request = new byte[0]; - try { - request = OBJECT_MAPPER.writeValueAsBytes(OBJECT_MAPPER.treeToValue( - JSON_NODE_FACTORY.objectNode().setAll(jsonRpcRequestProperties), Object.class)); - } catch (JsonProcessingException e) { - fail(e.getMessage()); - } - return request; - - } -} From eda64b741bc728787d701c4b69054cc2280a94d3 Mon Sep 17 00:00:00 2001 From: June <2571240520@qq.com> Date: Sat, 18 May 2024 10:05:00 +0800 Subject: [PATCH 12/19] refactor some code. --- pom.xml | 25 +++++++++++++++++++ src/main/java/io/xdag/Kernel.java | 14 ++++++++++- .../java/io/xdag/config/AbstractConfig.java | 12 +++++++++ src/main/java/io/xdag/config/Config.java | 2 ++ .../xdag/net/websocket/WebSocketServer.java | 18 +++++++++++-- 5 files changed, 68 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 29ccbea6..cd4d8709 100644 --- a/pom.xml +++ b/pom.xml @@ -69,10 +69,35 @@ + + 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/ + + maven_central + Maven Central + https://repo.maven.apache.org/maven2/ + diff --git a/src/main/java/io/xdag/Kernel.java b/src/main/java/io/xdag/Kernel.java index c2aa5eb0..7c3ec59b 100644 --- a/src/main/java/io/xdag/Kernel.java +++ b/src/main/java/io/xdag/Kernel.java @@ -41,6 +41,7 @@ import io.xdag.net.*; import io.xdag.net.message.MessageQueue; import io.xdag.net.node.NodeManager; +import io.xdag.net.websocket.WebSocketServer; import io.xdag.pool.PoolAwardManagerImpl; import io.xdag.rpc.Web3; import io.xdag.rpc.Web3Impl; @@ -89,6 +90,7 @@ public class Kernel { protected byte[] firstAccount; protected Block firstBlock; + protected WebSocketServer webSocketServer; protected PoolAwardManagerImpl poolAwardManager; protected XdagState xdagState; @@ -277,7 +279,7 @@ public synchronized void testStart() throws Exception { // pow // ==================================== pow = new XdagPow(this); - + getWsServer().start(); log.info("Node to pool websocket start..."); // register pow blockchain.registerListener(pow); @@ -351,6 +353,14 @@ private Web3HttpServer getWeb3HttpServer() throws UnknownHostException { return web3HttpServer; } + public WebSocketServer getWsServer() { + if (webSocketServer == null) { + webSocketServer = new WebSocketServer(this, config.getPoolWhiteIPList(), + config.getWebsocketServerPort()); + } + return webSocketServer; + } + private JsonRpcWeb3FilterHandler getJsonRpcWeb3FilterHandler() throws UnknownHostException { if (jsonRpcWeb3FilterHandler == null) { jsonRpcWeb3FilterHandler = new JsonRpcWeb3FilterHandler( @@ -418,6 +428,8 @@ public synchronized void testStop() { // release randomx.randomXPoolReleaseMem(); log.info("Release randomx"); + webSocketServer.stop(); + log.info("WebSocket server stop."); poolAwardManager.stop(); log.info("Pool award manager stop."); } diff --git a/src/main/java/io/xdag/config/AbstractConfig.java b/src/main/java/io/xdag/config/AbstractConfig.java index e736581c..cd94f3be 100644 --- a/src/main/java/io/xdag/config/AbstractConfig.java +++ b/src/main/java/io/xdag/config/AbstractConfig.java @@ -57,6 +57,12 @@ public class AbstractConfig implements Config, AdminSpec, NodeSpec, WalletSpec, protected int telnetPort = 7001; protected String telnetPassword; + // ========================= + // Pool websocket spec + // ========================= + + protected int websocketServerPort; + protected int maxShareCountPerChannel = 20; protected int awardEpoch = 0xf; protected int waitEpoch = 32; @@ -246,6 +252,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; 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"; @@ -382,6 +389,11 @@ public List getPoolWhiteIPList() { return poolWhiteIPList; } + @Override + public int getWebsocketServerPort() { + return websocketServerPort; + } + @Override public boolean isRPCEnabled() { return rpcEnabled; diff --git a/src/main/java/io/xdag/config/Config.java b/src/main/java/io/xdag/config/Config.java index e7384521..a2c0744a 100644 --- a/src/main/java/io/xdag/config/Config.java +++ b/src/main/java/io/xdag/config/Config.java @@ -96,6 +96,8 @@ public interface Config { //websocket List getPoolWhiteIPList(); + int getWebsocketServerPort(); + FundSpec getFundSpec(); } diff --git a/src/main/java/io/xdag/net/websocket/WebSocketServer.java b/src/main/java/io/xdag/net/websocket/WebSocketServer.java index f7280719..2dd589ca 100644 --- a/src/main/java/io/xdag/net/websocket/WebSocketServer.java +++ b/src/main/java/io/xdag/net/websocket/WebSocketServer.java @@ -25,14 +25,18 @@ import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; +import io.netty.channel.epoll.EpollEventLoopGroup; +import io.netty.channel.kqueue.KQueueEventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; +import io.netty.util.NettyRuntime; import io.xdag.Kernel; import lombok.Getter; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.SystemUtils; import javax.annotation.Nullable; import java.util.List; @@ -48,8 +52,18 @@ public class WebSocketServer { private final PoolHandShakeHandler poolHandShakeHandler; public WebSocketServer(Kernel kernel, List poolWhiteIPList, int port) { - this.bossGroup = new NioEventLoopGroup(); - this.workerGroup = new NioEventLoopGroup(); + int workerThreadPoolSize = NettyRuntime.availableProcessors() * 2; + if(SystemUtils.IS_OS_LINUX) { + this.bossGroup = new EpollEventLoopGroup(); + this.workerGroup = new EpollEventLoopGroup(workerThreadPoolSize); + } else if(SystemUtils.IS_OS_MAC) { + this.bossGroup = new KQueueEventLoopGroup(); + this.workerGroup = new KQueueEventLoopGroup(workerThreadPoolSize); + + } else { + this.bossGroup = new NioEventLoopGroup(); + this.workerGroup = new NioEventLoopGroup(workerThreadPoolSize); + } this.poolHandShakeHandler = new PoolHandShakeHandler(kernel, poolWhiteIPList, port); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) From cf2cdaa95e5d002622ab694b30538f4661872d71 Mon Sep 17 00:00:00 2001 From: June <2571240520@qq.com> Date: Mon, 20 May 2024 11:22:44 +0800 Subject: [PATCH 13/19] refactor some code. --- src/main/resources/xdag-mainnet.conf | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/main/resources/xdag-mainnet.conf b/src/main/resources/xdag-mainnet.conf index b4a80b31..8d520a87 100644 --- a/src/main/resources/xdag-mainnet.conf +++ b/src/main/resources/xdag-mainnet.conf @@ -31,11 +31,6 @@ rpc.http.host = 127.0.0.1 rpc.http.port = 10001 rpc.ws.port = 10002 -# Miner Config -miner.globalMinerLimit = 8192 -miner.globalMinerChannelLimit = 8192 -miner.maxConnectPerIp = 256 -miner.maxMinerPerAccount = 256 # Randomx Config randomx.flags.fullmem = false \ No newline at end of file From 3ffeeb96ff255ebbf078aa23c6c882a6e4650598 Mon Sep 17 00:00:00 2001 From: June <2571240520@qq.com> Date: Fri, 21 Jun 2024 15:03:43 +0800 Subject: [PATCH 14/19] fixed node create TX block diff is 1. --- src/main/java/io/xdag/core/BlockchainImpl.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/io/xdag/core/BlockchainImpl.java b/src/main/java/io/xdag/core/BlockchainImpl.java index 4e300dcf..0a3808b6 100644 --- a/src/main/java/io/xdag/core/BlockchainImpl.java +++ b/src/main/java/io/xdag/core/BlockchainImpl.java @@ -1105,6 +1105,11 @@ public BigInteger calculateCurrentBlockDiff(Block block) { if (block.getInfo().getDifficulty() != null) { return block.getInfo().getDifficulty(); } + //TX block would not set diff, fix a diff = 1; + if (!block.getInputs().isEmpty()) { + return BigInteger.ONE; + } + BigInteger blockDiff; // 初始区块自身难度设置 if (randomx != null && randomx.isRandomxFork(XdagTime.getEpoch(block.getTimestamp())) From c412d99e59281ae2794a81b9ad900dd11459000e Mon Sep 17 00:00:00 2001 From: June <2571240520@qq.com> Date: Thu, 27 Jun 2024 19:23:09 +0800 Subject: [PATCH 15/19] Fix the endless Link Bug in LinkBlock link LinkBlock by non-mining nodes in the mainnet. --- src/main/java/io/xdag/core/BlockchainImpl.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/xdag/core/BlockchainImpl.java b/src/main/java/io/xdag/core/BlockchainImpl.java index 0a3808b6..33791fa0 100644 --- a/src/main/java/io/xdag/core/BlockchainImpl.java +++ b/src/main/java/io/xdag/core/BlockchainImpl.java @@ -435,7 +435,10 @@ public synchronized ImportResult tryToConnect(Block block) { // result = ImportResult.IMPORTED_EXTRA; } else { saveBlock(block); - orphanBlockStore.addOrphan(block); + // prohibited non-mining node set Tx pool + if (kernel.getConfig().getEnableGenerateBlock()) { + orphanBlockStore.addOrphan(block); + } xdagStats.nnoref++; } blockStore.saveXdagStatus(xdagStats); @@ -1543,7 +1546,9 @@ public void startCheckMain(long period) { } public void checkState() { - if (kernel.getXdagState() == XdagState.SDST || XdagState.STST == kernel.getXdagState() || XdagState.SYNC == kernel.getXdagState()) { + // Prohibit Non-mining nodes generate link blocks + if (kernel.getConfig().getEnableGenerateBlock() && + (kernel.getXdagState() == XdagState.SDST || XdagState.STST == kernel.getXdagState() || XdagState.SYNC == kernel.getXdagState())) { checkOrphan(); } checkMain(); From 3e52b62203ddb94c630f84a11a36fa7f04fc3300 Mon Sep 17 00:00:00 2001 From: June <2571240520@qq.com> Date: Fri, 28 Jun 2024 10:40:01 +0800 Subject: [PATCH 16/19] Bug fix: All nodes temporarily close tx pool when syncing. --- src/main/java/io/xdag/core/BlockchainImpl.java | 5 +++-- src/test/java/io/xdag/core/ExtraBlockTest.java | 2 ++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/xdag/core/BlockchainImpl.java b/src/main/java/io/xdag/core/BlockchainImpl.java index 33791fa0..5c859dd6 100644 --- a/src/main/java/io/xdag/core/BlockchainImpl.java +++ b/src/main/java/io/xdag/core/BlockchainImpl.java @@ -435,8 +435,9 @@ public synchronized ImportResult tryToConnect(Block block) { // result = ImportResult.IMPORTED_EXTRA; } else { saveBlock(block); - // prohibited non-mining node set Tx pool - if (kernel.getConfig().getEnableGenerateBlock()) { + // 1. prohibited non-mining node set Tx pool, + // 2. all nodes temporarily close tx pool when syncing. + if (kernel.getConfig().getEnableGenerateBlock() && kernel.getPow() != null) { orphanBlockStore.addOrphan(block); } xdagStats.nnoref++; diff --git a/src/test/java/io/xdag/core/ExtraBlockTest.java b/src/test/java/io/xdag/core/ExtraBlockTest.java index 5a283697..c0544e76 100644 --- a/src/test/java/io/xdag/core/ExtraBlockTest.java +++ b/src/test/java/io/xdag/core/ExtraBlockTest.java @@ -29,6 +29,7 @@ import io.xdag.Wallet; import io.xdag.config.Config; import io.xdag.config.DevnetConfig; +import io.xdag.consensus.XdagPow; import io.xdag.crypto.SampleKeys; import io.xdag.crypto.Sign; import io.xdag.db.BlockStore; @@ -102,6 +103,7 @@ public void setUp() throws Exception { kernel.setBlockStore(blockStore); kernel.setOrphanBlockStore(orphanBlockStore); kernel.setWallet(wallet); + kernel.setPow(new XdagPow(kernel)); } @Test From d7a9d45e075be5715ea2e13dcbbb32aa3ffdbdf1 Mon Sep 17 00:00:00 2001 From: LucasMLK Date: Fri, 28 Jun 2024 10:56:40 +0800 Subject: [PATCH 17/19] update some maven dependency --- pom.xml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/pom.xml b/pom.xml index cd4d8709..4ea227a1 100644 --- a/pom.xml +++ b/pom.xml @@ -17,13 +17,13 @@ package ${project.basedir}/dist - 4.1.108.Final + 4.1.111.Final 2.4.2 2.17.1 5.5.0 1.18.32 3.1.8 - 3.25.1 + 3.26.2 4.13.2 5.11.0 1.2.1 @@ -33,11 +33,11 @@ 4.5.0-M1 1.17.0 2.16.1 - 1.7.0 - 33.2.0-jre - 9.1.1 + 1.8.0 + 33.2.1-jre + 9.2.1 4.12.0 - 3.25.3 + 3.26.0 23.1.3 1.78 1.78 @@ -45,9 +45,9 @@ 1.6 4.0.2 1.4.3 - 1.21.1 + 1.21.2 1.1.10.4 - 1.2.22 + 1.2.23 8.4.0 2.2.224 2.10 From 563d781d609ce0be391418e8cf7f4ae4ec9da570 Mon Sep 17 00:00:00 2001 From: LucasMLK Date: Fri, 28 Jun 2024 11:05:47 +0800 Subject: [PATCH 18/19] update version and some maven dependency --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 4ea227a1..e72dc8cf 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ io.xdag xdagj - 0.7.1 + 0.7.2 UTF-8 From 0378ac79f376e8fda1052ec788b746205d56c3b6 Mon Sep 17 00:00:00 2001 From: June <2571240520@qq.com> Date: Sun, 30 Jun 2024 16:22:53 +0800 Subject: [PATCH 19/19] refactor. --- .../io/xdag/net/websocket/WebSocketServer.java | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/src/main/java/io/xdag/net/websocket/WebSocketServer.java b/src/main/java/io/xdag/net/websocket/WebSocketServer.java index 2dd589ca..f7280719 100644 --- a/src/main/java/io/xdag/net/websocket/WebSocketServer.java +++ b/src/main/java/io/xdag/net/websocket/WebSocketServer.java @@ -25,18 +25,14 @@ import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; -import io.netty.channel.epoll.EpollEventLoopGroup; -import io.netty.channel.kqueue.KQueueEventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; -import io.netty.util.NettyRuntime; import io.xdag.Kernel; import lombok.Getter; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.SystemUtils; import javax.annotation.Nullable; import java.util.List; @@ -52,18 +48,8 @@ public class WebSocketServer { private final PoolHandShakeHandler poolHandShakeHandler; public WebSocketServer(Kernel kernel, List poolWhiteIPList, int port) { - int workerThreadPoolSize = NettyRuntime.availableProcessors() * 2; - if(SystemUtils.IS_OS_LINUX) { - this.bossGroup = new EpollEventLoopGroup(); - this.workerGroup = new EpollEventLoopGroup(workerThreadPoolSize); - } else if(SystemUtils.IS_OS_MAC) { - this.bossGroup = new KQueueEventLoopGroup(); - this.workerGroup = new KQueueEventLoopGroup(workerThreadPoolSize); - - } else { - this.bossGroup = new NioEventLoopGroup(); - this.workerGroup = new NioEventLoopGroup(workerThreadPoolSize); - } + this.bossGroup = new NioEventLoopGroup(); + this.workerGroup = new NioEventLoopGroup(); this.poolHandShakeHandler = new PoolHandShakeHandler(kernel, poolWhiteIPList, port); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup)