diff --git a/pom.xml b/pom.xml index 494950bc..b75481cc 100644 --- a/pom.xml +++ b/pom.xml @@ -337,7 +337,7 @@ io.xdag xdagj-native-randomx - 0.1.5 + 0.1.6 diff --git a/src/main/java/io/xdag/Kernel.java b/src/main/java/io/xdag/Kernel.java index e899fa39..708bcdb4 100644 --- a/src/main/java/io/xdag/Kernel.java +++ b/src/main/java/io/xdag/Kernel.java @@ -70,8 +70,8 @@ import io.xdag.rpc.Web3; import io.xdag.rpc.Web3Impl; import io.xdag.rpc.cors.CorsConfiguration; -import io.xdag.rpc.modules.web3.Web3XdagModule; -import io.xdag.rpc.modules.web3.Web3XdagModuleImpl; +import io.xdag.rpc.modules.xdag.Web3XdagModule; +import io.xdag.rpc.modules.xdag.Web3XdagModuleImpl; import io.xdag.rpc.modules.xdag.XdagModule; import io.xdag.rpc.modules.xdag.XdagModuleChainBase; import io.xdag.rpc.modules.xdag.XdagModuleTransactionEnabled; @@ -83,7 +83,7 @@ import io.xdag.rpc.netty.XdagJsonRpcHandler; import io.xdag.rpc.serialize.JacksonBasedRpcSerializer; import io.xdag.rpc.serialize.JsonRpcSerializer; -import io.xdag.utils.ByteArrayToByte32; +import io.xdag.utils.BytesUtils; import io.xdag.utils.XdagTime; import java.net.InetAddress; import java.net.UnknownHostException; @@ -232,7 +232,7 @@ public synchronized void testStart() throws Exception { // 如果是第一次启动,则新建一个创世块 if (xdagStats.getOurLastBlockHash() == null) { firstAccount = Keys.toBytesAddress(wallet.getDefKey().getPublicKey()); - poolMiner = new Miner(ByteArrayToByte32.arrayToByte32(firstAccount)); + poolMiner = new Miner(BytesUtils.arrayToByte32(firstAccount)); firstBlock = new Block(config, XdagTime.getCurrentTimestamp(), null, null, false, null, null, -1); firstBlock.signOut(wallet.getDefKey()); xdagStats.setOurLastBlockHash(firstBlock.getHashLow().toArray()); @@ -242,7 +242,7 @@ public synchronized void testStart() throws Exception { blockchain.tryToConnect(firstBlock); } else { firstAccount = Keys.toBytesAddress(wallet.getDefKey().getPublicKey()); - poolMiner = new Miner(ByteArrayToByte32.arrayToByte32(firstAccount)); + poolMiner = new Miner(BytesUtils.arrayToByte32(firstAccount)); } log.info("Blockchain init"); diff --git a/src/main/java/io/xdag/Wallet.java b/src/main/java/io/xdag/Wallet.java index 5cfd129b..a202ffe7 100644 --- a/src/main/java/io/xdag/Wallet.java +++ b/src/main/java/io/xdag/Wallet.java @@ -43,11 +43,11 @@ import io.xdag.crypto.Sign; import io.xdag.utils.Numeric; import io.xdag.utils.SimpleDecoder; -import io.xdag.utils.SystemUtil; import io.xdag.utils.WalletUtils; import io.xdag.utils.XdagTime; import java.io.File; import java.io.IOException; +import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.attribute.PosixFilePermission; import java.security.InvalidAlgorithmParameterException; @@ -339,7 +339,7 @@ public boolean flush() { } // set posix permissions - if (SystemUtil.isPosix() && !file.exists()) { + if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix") && !file.exists()) { Files.createFile(file.toPath()); Files.setPosixFilePermissions(file.toPath(), POSIX_SECURED_PERMISSIONS); } diff --git a/src/main/java/io/xdag/cli/Commands.java b/src/main/java/io/xdag/cli/Commands.java index 33f5128a..69f47864 100644 --- a/src/main/java/io/xdag/cli/Commands.java +++ b/src/main/java/io/xdag/cli/Commands.java @@ -49,9 +49,9 @@ import static io.xdag.utils.BasicUtils.pubAddress2Hash; import static io.xdag.utils.BasicUtils.xdag2amount; import static io.xdag.utils.BasicUtils.xdagHashRate; -import static io.xdag.utils.PubkeyAddressUtils.checkAddress; -import static io.xdag.utils.PubkeyAddressUtils.fromBase58; -import static io.xdag.utils.PubkeyAddressUtils.toBase58; +import static io.xdag.utils.WalletUtils.checkAddress; +import static io.xdag.utils.WalletUtils.fromBase58; +import static io.xdag.utils.WalletUtils.toBase58; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -73,8 +73,7 @@ import io.xdag.mine.miner.MinerStates; import io.xdag.net.node.Node; import io.xdag.utils.BasicUtils; -import io.xdag.utils.ByteArrayToByte32; -import io.xdag.utils.PubkeyAddressUtils; +import io.xdag.utils.BytesUtils; import io.xdag.utils.XdagTime; import java.math.BigInteger; import java.net.InetSocketAddress; @@ -740,7 +739,7 @@ public String address(Bytes32 wrap) { .format(XdagTime.xdagTimestampToMs(txHistory.getTimeStamp())))); } }else { - tx.append(String.format(" snapshot: %s %.9f %s%n", (PubkeyAddressUtils.toBase58(ByteArrayToByte32.byte32ToArray(address.getAddress()))), + tx.append(String.format(" snapshot: %s %.9f %s%n", (toBase58(BytesUtils.byte32ToArray(address.getAddress()))), amount2xdag(address.getAmount()), FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.SSS") .format(XdagTime.xdagTimestampToMs(txHistory.getTimeStamp())))); diff --git a/src/main/java/io/xdag/cli/Shell.java b/src/main/java/io/xdag/cli/Shell.java index df6d5ea5..df0afce9 100644 --- a/src/main/java/io/xdag/cli/Shell.java +++ b/src/main/java/io/xdag/cli/Shell.java @@ -30,7 +30,6 @@ import io.xdag.Kernel; import io.xdag.Wallet; import io.xdag.utils.BasicUtils; -import io.xdag.utils.PubkeyAddressUtils; import io.xdag.utils.WalletUtils; import java.util.HashMap; import java.util.List; @@ -130,7 +129,7 @@ private void processAddress(CommandInput input) { String address = argv.get(0); try { Bytes32 hash; - if (PubkeyAddressUtils.checkAddress(address)) { + if (WalletUtils.checkAddress(address)) { hash = pubAddress2Hash(address); } else { println("Incorrect address"); @@ -377,7 +376,7 @@ private void processXfer(CommandInput input) { return; } - if (PubkeyAddressUtils.checkAddress(argv.get(1))) { + if (WalletUtils.checkAddress(argv.get(1))) { hash = pubAddress2Hash(argv.get(1)); } else { println("Incorrect address"); diff --git a/src/main/java/io/xdag/consensus/XdagPow.java b/src/main/java/io/xdag/consensus/XdagPow.java index 9ab4b757..98c7f34b 100644 --- a/src/main/java/io/xdag/consensus/XdagPow.java +++ b/src/main/java/io/xdag/consensus/XdagPow.java @@ -83,6 +83,8 @@ public class XdagPow implements PoW, Listener, Runnable { protected AtomicReference currentTask = new AtomicReference<>(); protected AtomicLong taskIndex = new AtomicLong(0L); + private boolean isWorking = false; + private final ExecutorService timerExecutor = Executors.newSingleThreadExecutor(new BasicThreadFactory.Builder() .namingPattern("XdagPow-timer-thread") @@ -267,11 +269,15 @@ public void receiveNewShare(MinerChannel channel, Message msg) { } public void receiveNewPretop(Bytes pretop) { - if (!this.isRunning) { + // make sure the PoW is running and the main block is generating + if (!this.isRunning || !isWorking) { return; } - if (!equalBytes(pretop.toArray(), globalPretop.toArray())) { - globalPretop = Bytes32.wrap(blockchain.getXdagTopStatus().getPreTop()); + + // prevent duplicate event + if (globalPretop == null || !equalBytes(pretop.toArray(), globalPretop.toArray())) { + log.debug("update global pretop:{}", Bytes32.wrap(pretop).toHexString()); + globalPretop = Bytes32.wrap(pretop); events.add(new Event(Event.Type.NEW_PRETOP, pretop)); } } @@ -327,17 +333,20 @@ protected void onNewShare(XdagField shareInfo, MinerChannel channel) { protected void onTimeout() { Block b = generateBlock.get(); + // stop generate main block + isWorking = false; if (b != null) { Block newBlock = new Block(new XdagBlock(b.toBytes())); log.debug("Broadcast locally generated blockchain, waiting to be verified. block hash = [{}]", newBlock.getHash().toHexString()); - // 发送区块 如果有的话 然后开始生成新区块 + // add new block, reward miner, and broadcast the new block kernel.getBlockchain().tryToConnect(newBlock); awardManager.addAwardBlock(minShare.get(), newBlock.getHash(), newBlock.getTimestamp()); BlockWrapper bw = new BlockWrapper(newBlock, kernel.getConfig().getNodeSpec().getTTL()); - broadcaster.broadcast(bw); } + // start generate main block + isWorking = true; newBlock(); } @@ -405,7 +414,7 @@ public void run() { // resetTimeout(XdagTime.getEndOfEpoch(XdagTime.getCurrentTimestamp() + 64)); timer.timeout(XdagTime.getEndOfEpoch(XdagTime.getCurrentTimestamp() + 64)); // init pretop - globalPretop = Bytes32.wrap(blockchain.getXdagTopStatus().getPreTop()); + globalPretop = null; while (this.isRunning) { try { Event ev = events.poll(10, TimeUnit.MILLISECONDS); diff --git a/src/main/java/io/xdag/core/Address.java b/src/main/java/io/xdag/core/Address.java index d2768a45..04dc06c9 100644 --- a/src/main/java/io/xdag/core/Address.java +++ b/src/main/java/io/xdag/core/Address.java @@ -25,7 +25,7 @@ package io.xdag.core; import io.xdag.utils.BytesUtils; -import io.xdag.utils.PubkeyAddressUtils; +import io.xdag.utils.WalletUtils; import lombok.Getter; import lombok.Setter; import org.apache.tuweni.bytes.Bytes; @@ -167,7 +167,7 @@ public boolean getIsAddress() { @Override public String toString() { if(isAddress){ - return "Address [" + PubkeyAddressUtils.toBase58(addressHash.slice(8,20).toArray()) + "]"; + return "Address [" + WalletUtils.toBase58(addressHash.slice(8,20).toArray()) + "]"; }else { return "Block Hash[" + addressHash.toHexString() + "]"; } diff --git a/src/main/java/io/xdag/core/BlockchainImpl.java b/src/main/java/io/xdag/core/BlockchainImpl.java index 1af2d0f4..25537e76 100644 --- a/src/main/java/io/xdag/core/BlockchainImpl.java +++ b/src/main/java/io/xdag/core/BlockchainImpl.java @@ -73,8 +73,8 @@ import io.xdag.listener.PretopMessage; import io.xdag.mine.randomx.RandomX; import io.xdag.utils.BasicUtils; -import io.xdag.utils.ByteArrayToByte32; -import io.xdag.utils.PubkeyAddressUtils; +import io.xdag.utils.BytesUtils; +import io.xdag.utils.WalletUtils; import io.xdag.utils.XdagTime; import java.math.BigInteger; import java.util.ArrayList; @@ -324,7 +324,7 @@ public synchronized ImportResult tryToConnect(Block block) { log.debug("Block have no parent for " + result.getHashlow().toHexString()); return result; } else { - // 链接块的时间需要小于该块时间,否则为不合法区块 + // ensure ref block's time is earlier than block's time if (refBlock.getTimestamp() >= block.getTimestamp()) { result = ImportResult.INVALID_BLOCK; result.setHashlow(refBlock.getHashLow()); @@ -337,10 +337,10 @@ public synchronized ImportResult tryToConnect(Block block) { } }else { - if(ref.type == XDAG_FIELD_INPUT && !addressStore.addressIsExist(ByteArrayToByte32.byte32ToArray(ref.getAddress()))){ + if(ref.type == XDAG_FIELD_INPUT && !addressStore.addressIsExist(BytesUtils.byte32ToArray(ref.getAddress()))){ result = ImportResult.INVALID_BLOCK; - result.setErrorInfo("Address isn't exist " + PubkeyAddressUtils.toBase58(ByteArrayToByte32.byte32ToArray(ref.getAddress()))); - log.debug("Address isn't exist " + PubkeyAddressUtils.toBase58(ByteArrayToByte32.byte32ToArray(ref.getAddress()))); + result.setErrorInfo("Address isn't exist " + WalletUtils.toBase58(BytesUtils.byte32ToArray(ref.getAddress()))); + log.debug("Address isn't exist " + WalletUtils.toBase58(BytesUtils.byte32ToArray(ref.getAddress()))); return result; } } @@ -408,17 +408,10 @@ public synchronized ImportResult tryToConnect(Block block) { updateBlockFlag(block, BI_OURS, true); } - // 更新区块难度和maxDiffLink + // calculate block's self difficulty BigInteger cuDiff = calculateCurrentBlockDiff(block); - BigInteger diff = calculateBlockDiff(block,cuDiff); - - // 更新preTop - setPreTop(block, diff); - setPreTop(getBlockByHash(xdagTopStatus.getTop() == null ? null : Bytes32.wrap(xdagTopStatus.getTop()), - false), xdagTopStatus.getTopDiff()); - - // 通知XdagPoW 新pretop产生 - onNewPretop(); + // calculate block's chain difficulty + calculateBlockDiff(block,cuDiff); // TODO:extra 处理 processExtraBlock(); @@ -439,9 +432,20 @@ public synchronized ImportResult tryToConnect(Block block) { log.info("XDAG:Before unwind, height = {}, After unwind, height = {}, unwind number = {}", currentHeight, xdagStats.nmain, currentHeight - xdagStats.nmain); } + + Block currentTop = getBlockByHash(xdagTopStatus.getTop() == null ? null : + Bytes32.wrap(xdagTopStatus.getTop()), false); + BigInteger currentTopDiff = xdagTopStatus.getTopDiff(); log.debug("update top: {}", block.getHashLow()); + // update Top xdagTopStatus.setTopDiff(block.getInfo().getDifficulty()); xdagTopStatus.setTop(block.getHashLow().toArray()); + // update preTop + setPreTop(currentTop,currentTopDiff); + // if block's epoch is earlier than current epoch, then notify the PoW thread to regenerate the main block + if (XdagTime.getEpoch(block.getTimestamp()) < XdagTime.getCurrentEpoch()) { + onNewPretop(); + } result = ImportResult.IMPORTED_BEST; xdagStats.updateMaxDiff(xdagTopStatus.getTopDiff()); xdagStats.updateDiff(xdagTopStatus.getTopDiff()); @@ -450,20 +454,13 @@ public synchronized ImportResult tryToConnect(Block block) { // 新增区块 xdagStats.nblocks++; xdagStats.totalnblocks = Math.max(xdagStats.nblocks, xdagStats.totalnblocks); -// if (xdagStats.getTotalnblocks() < xdagStats.getNblocks()) { -// xdagStats.setTotalnblocks(xdagStats.getNblocks()); -// } - //orphan (hash , block) -// log.debug("======New block waiting to link======,{}",Hex.toHexString(block.getHashLow())); if ((block.getInfo().flags & BI_EXTRA) != 0) { -// log.debug("block:{} is extra, put it into memOrphanPool waiting to link.", Hex.toHexString(block.getHashLow())); memOrphanPool.put(block.getHashLow(), block); xdagStats.nextra++; // TODO:设置为返回 IMPORTED_EXTRA // result = ImportResult.IMPORTED_EXTRA; } else { -// log.debug("block:{} is extra, put it into orphanPool waiting to link.", Hex.toHexString(block.getHashLow())); saveBlock(block); orphanBlockStore.addOrphan(block); xdagStats.nnoref++; @@ -594,7 +591,7 @@ public void processExtraBlock() { protected void onNewPretop() { for (Listener listener : listeners) { - listener.onMessage(new PretopMessage(Bytes.wrap(xdagTopStatus.getPreTop()), PRE_TOP)); + listener.onMessage(new PretopMessage(Bytes.wrap(xdagTopStatus.getTop()), PRE_TOP)); } } @@ -638,9 +635,8 @@ public synchronized void checkNewMain() { */ public void unWindMain(Block block) { log.debug("Unwind main to block,{}", block == null ? "null" : block.getHashLow().toHexString()); -// log.debug("xdagTopStatus.getTop(),{}",xdagTopStatus.getTop()==null?"null":Hex.toHexString(xdagTopStatus.getTop())); if (xdagTopStatus.getTop() != null) { - log.debug("now top : {}", Bytes32.wrap(xdagTopStatus.getPreTop()).toHexString()); + log.debug("now pretop : {}",xdagTopStatus.getPreTop() == null?"null": Bytes32.wrap(xdagTopStatus.getPreTop()).toHexString()); for (Block tmp = getBlockByHash(Bytes32.wrap(xdagTopStatus.getTop()), true); tmp != null && !blockEqual(block, tmp); tmp = getMaxDiffLink(tmp, true)) { updateBlockFlag(tmp, BI_MAIN_CHAIN, false); @@ -1005,37 +1001,49 @@ public Bytes32 getPreTopMainBlockForLink(long sendTime) { return null; } if (XdagTime.getEpoch(topInfo.getTimestamp()) == mainTime) { + log.debug("use pretop:{}", Bytes32.wrap(xdagTopStatus.getPreTop()).toHexString()); return Bytes32.wrap(xdagTopStatus.getPreTop()); } else { + log.debug("use top:{}", Bytes32.wrap(xdagTopStatus.getTop()).toHexString()); return Bytes32.wrap(xdagTopStatus.getTop()); } } /** * update pretop - * @param block block - * @param diff difficulty of block + * @param target target + * @param targetDiff difficulty of block */ - public void setPreTop(Block block, BigInteger diff) { - if (block == null) { + public void setPreTop(Block target, BigInteger targetDiff) { + if (target == null) { return; } - if (XdagTime.getEpoch(block.getTimestamp()) > XdagTime.getCurrentEpoch()) { - return; + + // make sure the target's epoch is earlier than current top's epoch + Block block = getBlockByHash(xdagTopStatus.getTop() == null ? null : + Bytes32.wrap(xdagTopStatus.getTop()), false); + if (block != null) { + if (XdagTime.getEpoch(target.getTimestamp()) >= XdagTime.getEpoch(block.getTimestamp())) { + return; + } } + + // if pretop is null, then update pretop to target if (xdagTopStatus.getPreTop() == null) { - xdagTopStatus.setPreTop(block.getHashLow().toArray()); - xdagTopStatus.setPreTopDiff(diff); - block.setPretopCandidate(true); - block.setPretopCandidateDiff(diff); + xdagTopStatus.setPreTop(target.getHashLow().toArray()); + xdagTopStatus.setPreTopDiff(targetDiff); + target.setPretopCandidate(true); + target.setPretopCandidateDiff(targetDiff); return; } - if (diff.compareTo(xdagTopStatus.getPreTopDiff()) > 0) { - xdagTopStatus.setPreTop(block.getHashLow().toArray()); - xdagTopStatus.setPreTopDiff(diff); - block.setPretopCandidate(true); - block.setPretopCandidateDiff(diff); + // if targetDiff greater than pretop diff, then update pretop to target + if (targetDiff.compareTo(xdagTopStatus.getPreTopDiff()) > 0) { + log.debug("update pretop:{}", Bytes32.wrap(target.getHashLow()).toHexString()); + xdagTopStatus.setPreTop(target.getHashLow().toArray()); + xdagTopStatus.setPreTopDiff(targetDiff); + target.setPretopCandidate(true); + target.setPretopCandidateDiff(targetDiff); } } /** diff --git a/src/main/java/io/xdag/db/rocksdb/SnapshotStoreImpl.java b/src/main/java/io/xdag/db/rocksdb/SnapshotStoreImpl.java index ee61f8c2..dd1146f4 100644 --- a/src/main/java/io/xdag/db/rocksdb/SnapshotStoreImpl.java +++ b/src/main/java/io/xdag/db/rocksdb/SnapshotStoreImpl.java @@ -23,7 +23,6 @@ */ package io.xdag.db.rocksdb; -import static io.xdag.config.Constants.BI_MAIN; import static io.xdag.config.Constants.BI_OURS; import static io.xdag.db.BlockStore.HASH_BLOCK_INFO; import static io.xdag.db.BlockStore.SUMS_BLOCK_INFO; @@ -31,7 +30,6 @@ import static io.xdag.db.AddressStore.ADDRESS_SIZE; import static io.xdag.db.AddressStore.AMOUNT_SUM; import static io.xdag.utils.BasicUtils.compareAmountTo; -import static io.xdag.utils.ByteArrayToByte32.arrayToByte32; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.KryoException; @@ -256,7 +254,7 @@ public void saveAddress(BlockStore blockStore,AddressStore addressStore, List out) { byte[] addressHash = Arrays.copyOfRange(message,0,20); checkProtocol(ctx,addressHash); - if (!initMiner(ByteArrayToByte32.arrayToByte32(addressHash))) { + if (!initMiner(BytesUtils.arrayToByte32(addressHash))) { log.debug("too many connect for the miner: {},ip&port:{}", - PubkeyAddressUtils.toBase58(channel.getAccountAddressHashByte()),channel.getInetAddress().toString()); + WalletUtils.toBase58(channel.getAccountAddressHashByte()),channel.getInetAddress().toString()); ctx.close(); return; } @@ -95,12 +97,12 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) { minerManager.addActivateChannel(channel); channel.setIsActivate(true); channel.setConnectTime(new Date(System.currentTimeMillis())); - channel.setAccountAddressHash(ByteArrayToByte32.arrayToByte32(addressHash)); + channel.setAccountAddressHash(BytesUtils.arrayToByte32(addressHash)); channel.setAccountAddressHashByte(addressHash); channel.activateHandler(ctx, V03); ctx.pipeline().remove(this); // TODO: 2020/5/8 There may be a bug here. If you join infinitely, won't it be created wirelessly? - log.debug("add a new miner from ip&port:{},miner's address: [" + PubkeyAddressUtils.toBase58(channel.getAccountAddressHashByte()) + "]",channel.getInetAddress()); + log.debug("add a new miner from ip&port:{},miner's address: [" + WalletUtils.toBase58(channel.getAccountAddressHashByte()) + "]",channel.getInetAddress()); } else { log.debug("length less than " + MESSAGE_SIZE + " bytes"); } @@ -111,10 +113,10 @@ public void checkProtocol(ChannelHandlerContext ctx, byte[] address) { if (!importResult) { addressStore.addAddress(address); log.info("XDAG:new miner connect. New address: {} with channel: {} connect.", - PubkeyAddressUtils.toBase58(address), channel.getInetAddress()); + WalletUtils.toBase58(address), channel.getInetAddress()); } else { log.info("XDAG:old miner connect. Address: {} with channel {} connect.", - PubkeyAddressUtils.toBase58(address), channel.getInetAddress()); + WalletUtils.toBase58(address), channel.getInetAddress()); } } diff --git a/src/main/java/io/xdag/mine/handler/MinerMessageHandler.java b/src/main/java/io/xdag/mine/handler/MinerMessageHandler.java index 32ba4694..e9deaadb 100644 --- a/src/main/java/io/xdag/mine/handler/MinerMessageHandler.java +++ b/src/main/java/io/xdag/mine/handler/MinerMessageHandler.java @@ -35,7 +35,7 @@ import io.xdag.net.message.Message; import io.xdag.net.message.MessageFactory; import io.xdag.utils.BytesUtils; -import io.xdag.utils.PubkeyAddressUtils; +import io.xdag.utils.WalletUtils; import jakarta.xml.bind.DatatypeConverter; import java.io.IOException; import java.util.List; @@ -65,7 +65,7 @@ protected void encode(ChannelHandlerContext ctx, byte[] bytes, ByteBuf out) { long sectorNo = channel.getOutBound().get(); if (len == DATA_SIZE) { log.debug("Send a message for miner: {} ip&port:{} with sectorNo={},length={}", - PubkeyAddressUtils.toBase58(channel.getAccountAddressHashByte()),channel.getInetAddress().toString(),sectorNo, len); + WalletUtils.toBase58(channel.getAccountAddressHashByte()),channel.getInetAddress().toString(),sectorNo, len); BytesUtils.arrayReverse(bytes); out.writeBytes(bytes); channel.getOutBound().add(); @@ -87,7 +87,7 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) { // The length of the received message is 32 bytes if (len == DATA_SIZE) { log.debug("Received a message from the miner:{} ip&port:{},msg len == 32", - PubkeyAddressUtils.toBase58(channel.getAccountAddressHashByte()), + WalletUtils.toBase58(channel.getAccountAddressHashByte()), channel.getInetAddress().toString()); byte[] data = new byte[DATA_SIZE]; in.readBytes(data); diff --git a/src/main/java/io/xdag/mine/manager/AwardManagerImpl.java b/src/main/java/io/xdag/mine/manager/AwardManagerImpl.java index f130a95e..ce4ceeeb 100644 --- a/src/main/java/io/xdag/mine/manager/AwardManagerImpl.java +++ b/src/main/java/io/xdag/mine/manager/AwardManagerImpl.java @@ -46,8 +46,8 @@ import io.xdag.mine.miner.Miner; import io.xdag.mine.miner.MinerStates; import io.xdag.utils.BigDecimalUtils; -import io.xdag.utils.ByteArrayToByte32; -import io.xdag.utils.PubkeyAddressUtils; +import io.xdag.utils.BytesUtils; + import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collections; @@ -60,6 +60,8 @@ import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; + +import io.xdag.utils.WalletUtils; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.concurrent.BasicThreadFactory; @@ -580,7 +582,7 @@ public void doPayments(Bytes32 hashLow, int paymentsPerBlock, PayData payData, i if (fundRation!=0) { - if (PubkeyAddressUtils.checkAddress(fundAddress)) { + if (WalletUtils.checkAddress(fundAddress)) { payAmount = payAmount.addExact(payData.fundIncome); receipt.add(new Address(pubAddress2Hash(fundAddress), XDAG_FIELD_OUTPUT, payData.fundIncome,true)); } @@ -590,7 +592,7 @@ public void doPayments(Bytes32 hashLow, int paymentsPerBlock, PayData payData, i //// TODO: 2021/4/19 打印矿工的数据 for (int i = 0; i < miners.size(); i++) { Miner miner = miners.get(i); - log.debug("Do payments for every miner,miner address = [{}]", PubkeyAddressUtils.toBase58(miner.getAddressHashByte())); + log.debug("Do payments for every miner,miner address = [{}]", WalletUtils.toBase58(miner.getAddressHashByte())); // 保存的是一个矿工所有的收入 UInt64 paymentSum = UInt64.ZERO; // 根据历史记录分发奖励 @@ -665,7 +667,7 @@ public boolean checkMine(Block block){ byte[] publicKeyBytes = ecKey.getPublicKey().asEcPoint(Sign.CURVE).getEncoded(true); byte[] publicKeyHash = Hash.sha256hash160(Bytes.wrap(publicKeyBytes)); Address coinBase = block.getCoinBase(); - byte[] coinBaseKey = ByteArrayToByte32.byte32ToArray(coinBase.getAddress()); + byte[] coinBaseKey = BytesUtils.byte32ToArray(coinBase.getAddress()); if (compareTo(publicKeyHash, 0, 20, coinBaseKey, 0, 20) == 0) { return true; } diff --git a/src/main/java/io/xdag/mine/miner/Miner.java b/src/main/java/io/xdag/mine/miner/Miner.java index cc2235a6..d988ff7c 100644 --- a/src/main/java/io/xdag/mine/miner/Miner.java +++ b/src/main/java/io/xdag/mine/miner/Miner.java @@ -25,8 +25,8 @@ package io.xdag.mine.miner; import io.xdag.mine.MinerChannel; -import io.xdag.utils.ByteArrayToByte32; -import io.xdag.utils.PubkeyAddressUtils; +import io.xdag.utils.BytesUtils; + import java.net.InetSocketAddress; import java.util.Calendar; import java.util.Date; @@ -35,6 +35,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; + +import io.xdag.utils.WalletUtils; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @@ -47,8 +49,8 @@ public class Miner { * 保存这个矿工的地址 */ private final Bytes32 addressHash; + @Getter - @Setter private final byte[] addressHashByte; /** * 相同账户地址的channel数量 @@ -58,17 +60,12 @@ public class Miner { * 存放的是连续16个任务本地计算的最大难度 每一轮放的都是最小hash 计算出来的diffs */ private final List maxDiffs = new CopyOnWriteArrayList<>(); - /* 保存的时该矿工每一次进行任务计算的nonce + 低192bites的hash */ - // private XdagField id = new XdagField(); + /** * 保存的是这个矿工对应的channel */ private final Map channels = new ConcurrentHashMap<>(); - /** - * 分别存放的是本轮中 的难度 以及前面所有计算的难度 - */ - private final Map diffSum = new ConcurrentHashMap<>(); - private final Map prevDiffSum = new ConcurrentHashMap<>(); + protected int boundedTaskCounter; /** * 记录收到任务的时间 @@ -109,7 +106,7 @@ public class Miner { public Miner(Bytes32 addressHash) { log.debug("init the new miner:{}", addressHash.toHexString()); this.addressHash = addressHash; - addressHashByte = ByteArrayToByte32.byte32ToArray(addressHash.mutableCopy()); + addressHashByte = BytesUtils.byte32ToArray(addressHash.mutableCopy()); this.minerStates = MinerStates.MINER_UNKNOWN; this.taskTime = 0; this.meanLogDiff = 0.0; @@ -150,7 +147,7 @@ public boolean canRemove() { return false; } } - log.debug("remove Miner: {}", PubkeyAddressUtils.toBase58(addressHashByte)); + log.debug("remove Miner: {}", WalletUtils.toBase58(addressHashByte)); return true; } else { return false; diff --git a/src/main/java/io/xdag/mine/miner/MinerCalculate.java b/src/main/java/io/xdag/mine/miner/MinerCalculate.java index 20195ee5..dbfaca4d 100644 --- a/src/main/java/io/xdag/mine/miner/MinerCalculate.java +++ b/src/main/java/io/xdag/mine/miner/MinerCalculate.java @@ -34,7 +34,7 @@ import io.xdag.utils.BasicUtils; import io.xdag.utils.BigDecimalUtils; import io.xdag.utils.BytesUtils; -import io.xdag.utils.PubkeyAddressUtils; +import io.xdag.utils.WalletUtils; import io.xdag.utils.XdagTime; import java.net.InetSocketAddress; import java.util.Map; @@ -87,13 +87,13 @@ public static double calculateUnpaidShares(MinerChannel channel) { } } log.debug("print unpaid for miner: {} , sum= [{}] , count = [{}]", - PubkeyAddressUtils.toBase58(channel.getMiner().getAddressHashByte()),sum, count); + WalletUtils.toBase58(channel.getMiner().getAddressHashByte()),sum, count); return diffToPay(sum, count); } public static String minerStats(Miner miner) { StringBuilder res = new StringBuilder(); - String address = PubkeyAddressUtils.toBase58(miner.getAddressHashByte()); + String address = WalletUtils.toBase58(miner.getAddressHashByte()); double unpaid = calculateUnpaidShares(miner); String minerRegTime = XdagTime.format(miner.getRegTime()); res.append("miner: ") diff --git a/src/main/java/io/xdag/rpc/Web3.java b/src/main/java/io/xdag/rpc/Web3.java index a9365929..c1a898cd 100644 --- a/src/main/java/io/xdag/rpc/Web3.java +++ b/src/main/java/io/xdag/rpc/Web3.java @@ -24,107 +24,26 @@ package io.xdag.rpc; -import io.xdag.rpc.modules.web3.Web3XdagModule; -import java.util.Arrays; -import java.util.Map; +import io.xdag.rpc.modules.xdag.Web3XdagModule; public interface Web3 extends Web3XdagModule { - String web3_clientVersion(); - String web3_sha3(String data) throws Exception; - String net_version(); - - String net_peerCount(); - - boolean net_listening(); - - String[] net_peerList(); - - // methods required by dev environments - Map rpc_modules(); - - void db_putString(); - - void db_getString(); - - void db_putHex(); - - void db_getHex(); - - String personal_newAccount(String passphrase); - - String[] personal_listAccounts(); - - String personal_importRawKey(String key, String passphrase); - - Object personal_sendTransaction(CallArguments transactionArgs, String passphrase) throws Exception; - - boolean personal_unlockAccount(String key, String passphrase, String duration); - - boolean personal_lockAccount(String key); - - String personal_dumpRawKey(String address) throws Exception; - class CallArguments { - public String from; public String to; - // public String gas; -// public String gasPrice; public String value; - // public String data; // compiledCode public String remark; -// public String netType; - // public String nonce; -// public String chainId; //NOSONAR - @Override public String toString() { return "CallArguments{" + "from='" + from + '\'' + ", to='" + to + '\'' + -// ", gasLimit='" + gas + '\'' + -// ", gasPrice='" + gasPrice + '\'' + ", value='" + value + '\'' + ", remark='" + remark + '\'' + -// ", netType='" + netType + '\'' + -// ", data='" + data + '\'' + -// ", nonce='" + nonce + '\'' + -// ", chainId='" + chainId + '\'' + - '}'; - } - } - - class BlockInformationResult { - - public String hash; - public String totalDifficulty; - public boolean inMainChain; - } - - class FilterRequest { - - public String fromBlock; - public String toBlock; - public Object address; - public Object[] topics; - - @Override - public String toString() { - return "FilterRequest{" + - "fromBlock='" + fromBlock + '\'' + - ", toBlock='" + toBlock + '\'' + - ", address=" + address + - ", topics=" + Arrays.toString(topics) + '}'; } } -// void sco_banAddress(String address); -// void sco_unbanAddress(String address); -// PeerScoringInformation[] sco_peerList(); -// String[] sco_bannedAddresses(); -// PeerScoringReputationSummary sco_reputationSummary(); } diff --git a/src/main/java/io/xdag/rpc/Web3Impl.java b/src/main/java/io/xdag/rpc/Web3Impl.java index 2c2e1e19..421b8bea 100644 --- a/src/main/java/io/xdag/rpc/Web3Impl.java +++ b/src/main/java/io/xdag/rpc/Web3Impl.java @@ -27,9 +27,8 @@ import io.xdag.rpc.dto.BlockResultDTO; import io.xdag.rpc.dto.ConfigDTO; import io.xdag.rpc.dto.StatusDTO; -import io.xdag.rpc.modules.web3.Web3XdagModule; +import io.xdag.rpc.modules.xdag.Web3XdagModule; import io.xdag.rpc.modules.xdag.XdagModule; -import java.util.Map; public class Web3Impl implements Web3 { @@ -39,95 +38,11 @@ public Web3Impl(Web3XdagModule web3XdagModule) { this.web3XdagModule = web3XdagModule; } - @Override - public String web3_clientVersion() { - return null; - } - @Override public String web3_sha3(String data) { return null; } - @Override - public String net_version() { - return null; - } - - @Override - public String net_peerCount() { - return null; - } - - @Override - public boolean net_listening() { - return false; - } - - @Override - public String[] net_peerList() { - return new String[0]; - } - - @Override - public Map rpc_modules() { - return null; - } - - @Override - public void db_putString() { - - } - - @Override - public void db_getString() { - - } - - @Override - public void db_putHex() { - - } - - @Override - public void db_getHex() { - - } - - @Override - public String personal_newAccount(String passphrase) { - return null; - } - - @Override - public String[] personal_listAccounts() { - return new String[0]; - } - - @Override - public String personal_importRawKey(String key, String passphrase) { - return null; - } - - @Override - public Object personal_sendTransaction(CallArguments transactionArgs, String passphrase) { - return web3XdagModule.xdag_personal_sendTransaction(transactionArgs, passphrase); - } - - @Override - public boolean personal_unlockAccount(String key, String passphrase, String duration) { - return false; - } - - @Override - public boolean personal_lockAccount(String key) { - return false; - } - - @Override - public String personal_dumpRawKey(String address) { - return null; - } @Override public XdagModule getXdagModule() { diff --git a/src/main/java/io/xdag/rpc/cors/CorsConfiguration.java b/src/main/java/io/xdag/rpc/cors/CorsConfiguration.java index ebd41ec8..cffb858e 100644 --- a/src/main/java/io/xdag/rpc/cors/CorsConfiguration.java +++ b/src/main/java/io/xdag/rpc/cors/CorsConfiguration.java @@ -24,19 +24,18 @@ package io.xdag.rpc.cors; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; +@Slf4j public class CorsConfiguration { - private static final Logger logger = LoggerFactory.getLogger("cors"); private final String header; public CorsConfiguration(String header) { this.header = header; if ("*".equals(header)) { - logger.warn("CORS header set to '*'"); + log.warn("CORS header set to '*'"); } if (header != null && (header.contains("\n") || header.contains("\r"))) { diff --git a/src/main/java/io/xdag/rpc/dto/BlockResultDTO.java b/src/main/java/io/xdag/rpc/dto/BlockResultDTO.java index d15eba88..e9421912 100644 --- a/src/main/java/io/xdag/rpc/dto/BlockResultDTO.java +++ b/src/main/java/io/xdag/rpc/dto/BlockResultDTO.java @@ -62,7 +62,6 @@ public static class TxLink { @Data @Builder public static class Link { - private int direction; // 0 input 1 output 2 fee private String address; private String hashlow; diff --git a/src/main/java/io/xdag/rpc/dto/ETHBlockResultDTO.java b/src/main/java/io/xdag/rpc/dto/ETHBlockResultDTO.java deleted file mode 100644 index e7a66ec4..00000000 --- a/src/main/java/io/xdag/rpc/dto/ETHBlockResultDTO.java +++ /dev/null @@ -1,86 +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.dto; - -import static io.xdag.rpc.utils.TypeConverter.toQuantityJsonHex; - -import java.util.Collections; -import java.util.List; -import lombok.Data; - -@Data -public class ETHBlockResultDTO { - - private final String number; // QUANTITY - the block number. null when its pending block. - private final String hash; // DATA, 32 Bytes - hash of the block. null when its pending block. - private final String parentHash; // DATA, 32 Bytes - hash of the parent block. - private final String sha3Uncles; // DATA, 32 Bytes - SHA3 of the uncles data in the block. - private final String logsBloom; // DATA, 256 Bytes - the bloom filter for the logs of the block. null when its pending block. - private final String transactionsRoot; // DATA, 32 Bytes - the root of the transaction trie of the block. - private final String stateRoot; // DATA, 32 Bytes - the root of the final state trie of the block. - private final String receiptsRoot; // DATA, 32 Bytes - the root of the receipts trie of the block. - private final String miner; // DATA, 20 Bytes - the address of the beneficiary to whom the mining rewards were given. - private final String difficulty; // QUANTITY - integer of the difficulty for this block. - private final String totalDifficulty; // QUANTITY - integer of the total difficulty of the chain until this block. - private final String extraData; // DATA - the "extra data" field of this block - private final String size;//QUANTITY - integer the size of this block in bytes. - private final String gasLimit;//: QUANTITY - the maximum gas allowed in this block. - private final String gasUsed; // QUANTITY - the total used gas by all transactions in this block. - private final String timestamp; //: QUANTITY - the unix timestamp for when the block was collated. - private final List transactions; //: Collection - Collection of transaction objects, or 32 Bytes transaction hashes depending on the last given parameter. - private final List uncles; //: Collection - Collection of uncle hashes. - private final String cumulativeDifficulty; - - - public ETHBlockResultDTO( - long timestamp, - List transactions, - List uncles - ) { - this.number = toQuantityJsonHex(12); - this.hash = "0x88b221a282a64df608a820bae740425e5f439d1c"; - this.parentHash = "0x88b221a282a64df608a820bae740425e5f439d1c"; - this.sha3Uncles = "0x88b221a282a64df608a820bae740425e5f439d1c"; - this.logsBloom = null; - this.transactionsRoot = "0x88b221a282a64df608a820bae740425e5f439d1c"; - this.stateRoot = "0x88b221a282a64df608a820bae740425e5f439d1c"; - this.receiptsRoot = "0x88b221a282a64df608a820bae740425e5f439d1c"; - this.miner = null; - - this.difficulty = "0x0"; - this.totalDifficulty = "0x0"; - this.cumulativeDifficulty = "0x0"; - - this.extraData = "0x"; - this.size = toQuantityJsonHex(234); - this.gasLimit = toQuantityJsonHex(1233); - this.gasUsed = toQuantityJsonHex(12); - this.timestamp = toQuantityJsonHex(timestamp); - - this.transactions = Collections.unmodifiableList(transactions); - this.uncles = Collections.unmodifiableList(uncles); - - } -} diff --git a/src/main/java/io/xdag/rpc/dto/ETHTransactionReceiptDTO.java b/src/main/java/io/xdag/rpc/dto/ETHTransactionReceiptDTO.java deleted file mode 100644 index 33749f17..00000000 --- a/src/main/java/io/xdag/rpc/dto/ETHTransactionReceiptDTO.java +++ /dev/null @@ -1,74 +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.dto; - -import static io.xdag.rpc.utils.TypeConverter.toQuantityJsonHex; -import static io.xdag.rpc.utils.TypeConverter.toUnformattedJsonHex; -import static io.xdag.utils.BytesUtils.EMPTY_BYTE_ARRAY; - -import io.xdag.core.Block; - -public class ETHTransactionReceiptDTO { - - public static final int BLOOM_BYTES = 256; - protected static final byte[] FAILED_STATUS = EMPTY_BYTE_ARRAY; - protected static final byte[] PENDING_STATUS = new byte[]{0x02}; - protected static final byte[] SUCCESS_STATUS = new byte[]{0x01}; - private byte[] data = new byte[BLOOM_BYTES]; - private String transactionHash; // hash of the transaction. - private String transactionIndex; // integer of the transactions index position in the block. - private String blockHash; // hash of the block where this transaction was in. - private String blockNumber; // block number where this transaction was in. - private String cumulativeGasUsed; // The total amount of gas used when this transaction was executed in the block. - private String gasUsed; // The amount of gas used by this specific transaction alone. - private String contractAddress; // The contract address created, if the transaction was a contract creation, otherwise null . - private String from; // address of the sender. - private String to; // address of the receiver. null when it's a contract creation transaction. - private String status; // either 1 (success) or 0 (failure) - - // TODO : ignore - private String[] logs; // Array of log objects, which this transaction generated. - private String logsBloom; // Bloom filter for light clients to quickly retrieve related logs. - - public ETHTransactionReceiptDTO(Block block) { - - status = toQuantityJsonHex(SUCCESS_STATUS); - - blockHash = toUnformattedJsonHex(block.getHash().toArray()); - blockNumber = toQuantityJsonHex(19); - - cumulativeGasUsed = toQuantityJsonHex(123); - from = "0x88b221a282a64df608a820bae740425e5f439d1c"; - gasUsed = toQuantityJsonHex(123); - - logs = new String[0]; - - to = "0x88b221a282a64df608a820bae740425e5f439d1c"; - transactionHash = "0x647edff965606eb655103f6dee0c3b2805a56c40b3592eb7a8d011552d1e1839"; - transactionIndex = toQuantityJsonHex(1); - logsBloom = toUnformattedJsonHex(data); - } - -} diff --git a/src/main/java/io/xdag/rpc/dto/StatusDTO.java b/src/main/java/io/xdag/rpc/dto/StatusDTO.java index 5a46a624..e92cc60d 100644 --- a/src/main/java/io/xdag/rpc/dto/StatusDTO.java +++ b/src/main/java/io/xdag/rpc/dto/StatusDTO.java @@ -29,10 +29,9 @@ @Data @Builder -//TODO: return xdag status public class StatusDTO { - // status 状态信息 + // status info private final String nblock; private final String totalNblocks; private final String nmain; diff --git a/src/main/java/io/xdag/rpc/exception/XdagErrorResolver.java b/src/main/java/io/xdag/rpc/exception/XdagErrorResolver.java index b82ba1bd..1ee3058d 100644 --- a/src/main/java/io/xdag/rpc/exception/XdagErrorResolver.java +++ b/src/main/java/io/xdag/rpc/exception/XdagErrorResolver.java @@ -29,12 +29,11 @@ import com.googlecode.jsonrpc4j.ErrorResolver; import java.lang.reflect.Method; import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -public class XdagErrorResolver implements ErrorResolver { +import lombok.extern.slf4j.Slf4j; - private static final Logger logger = LoggerFactory.getLogger("web3"); +@Slf4j +public class XdagErrorResolver implements ErrorResolver { @Override public ErrorResolver.JsonError resolveError(Throwable t, Method method, List arguments) { @@ -45,7 +44,7 @@ public ErrorResolver.JsonError resolveError(Throwable t, Method method, List eth_bridgeState() throws Exception { -// return getEthModule().bridgeState(); -// } - - default String eth_chainId() { - return getEthModule().chainId(); - } - - EthModule getEthModule(); - - String eth_protocolVersion(); - -// Object eth_syncing(); - - String eth_coinbase(); - -// boolean eth_mining(); - -// BigInteger eth_hashrate(); - - default String eth_gasPrice() { - return "0x1"; - } - - String eth_blockNumber(); - - String eth_getBalance(String address, String block) throws Exception; - - String eth_getBalance(String address) throws Exception; - - String eth_getStorageAt(String address, String storageIdx, String blockId) throws Exception; - - default String eth_getTransactionCount(String address, String blockId) { - return "0x1"; - } - -// String eth_getBlockTransactionCountByHash(String blockHash)throws Exception; - -// String eth_getBlockTransactionCountByNumber(String bnOrId)throws Exception; - -// String eth_getUncleCountByBlockHash(String blockHash)throws Exception; - -// String eth_getUncleCountByBlockNumber(String bnOrId)throws Exception; - - default String eth_getCode(String address, String blockId) { - return getEthModule().getCode(address, blockId); - } - - default String eth_sendRawTransaction(String rawData) { - return getEthModule().sendRawTransaction(rawData); - } - -// default String eth_sendTransaction(Web3.CallArguments args) { -// return getEthModule().sendTransaction(args); -// } - -// BlockResultDTO eth_getBlockByHash(String blockHash, Boolean fullTransactionObjects) throws Exception; - - ETHBlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects) throws Exception; - -// BlockResultDTO eth_getTransactionByHash(String transactionHash) throws Exception; - -// BlockResultDTO eth_getTransactionByBlockHashAndIndex(String blockHash, String index) throws Exception; - -// BlockResultDTO eth_getTransactionByBlockNumberAndIndex(String bnOrId, String index) throws Exception; - - ETHTransactionReceiptDTO eth_getTransactionReceipt(String transactionHash) throws Exception; - -// BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx) throws Exception; - -// BlockResultDTO eth_getUncleByBlockNumberAndIndex(String blockId, String uncleIdx) throws Exception; - -// String[] eth_getCompilers(); - -// Map eth_compileLLL(String contract); - -// Map eth_compileSerpent(String contract); - -// Map eth_compileSolidity(String contract); - -// String eth_newFilter(Web3.FilterRequest fr) throws Exception; - -// String eth_newBlockFilter(); - -// String eth_newPendingTransactionFilter(); - -// boolean eth_uninstallFilter(String id); - -// Object[] eth_getFilterChanges(String id); - -// Object[] eth_getFilterLogs(String id); - -// Object[] eth_getLogs(Web3.FilterRequest fr) throws Exception; - -// BigInteger eth_netHashrate(); - -// boolean eth_submitWork(String nonce, String header, String mince); - -// boolean eth_submitHashrate(String hashrate, String id); -} - - diff --git a/src/main/java/io/xdag/rpc/modules/web3/Web3EthModuleImpl.java b/src/main/java/io/xdag/rpc/modules/web3/Web3EthModuleImpl.java deleted file mode 100644 index 8e01fb67..00000000 --- a/src/main/java/io/xdag/rpc/modules/web3/Web3EthModuleImpl.java +++ /dev/null @@ -1,93 +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.modules.web3; - -import static io.xdag.rpc.utils.TypeConverter.toQuantityJsonHex; - -import io.xdag.rpc.dto.ETHBlockResultDTO; -import io.xdag.rpc.dto.ETHTransactionReceiptDTO; -import io.xdag.rpc.modules.eth.EthModule; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Web3EthModuleImpl implements Web3EthModule { - - private static final Logger logger = LoggerFactory.getLogger(Web3XdagModuleImpl.class); - private final EthModule ethModule; - - public Web3EthModuleImpl(EthModule ethModule) { - this.ethModule = ethModule; - } - - @Override - public EthModule getEthModule() { - return ethModule; - } - - @Override - public String eth_protocolVersion() { - return Integer.toString(1); - } - - @Override - public String eth_coinbase() { - return "0x88b221a282a64df608a820bae740425e5f439d1c"; - } - - @Override - public String eth_blockNumber() { - return toQuantityJsonHex(12); - } - - @Override - public String eth_getBalance(String address, String block) throws Exception { - return toQuantityJsonHex(1000); - } - - @Override - public String eth_getBalance(String address) throws Exception { - return toQuantityJsonHex(2000); - } - - @Override - public String eth_getStorageAt(String address, String storageIdx, String blockId) throws Exception { - return "0x0"; - } - - @Override - public ETHBlockResultDTO eth_getBlockByNumber(String bnOrId, Boolean fullTransactionObjects) throws Exception { - return null; - } - - @Override - public ETHTransactionReceiptDTO eth_getTransactionReceipt(String transactionHash) throws Exception { - return null; - } - - static class SyncingResult { - public String currentBlock; - public String highestBlock; - } -} diff --git a/src/main/java/io/xdag/rpc/modules/web3/Web3XdagModule.java b/src/main/java/io/xdag/rpc/modules/xdag/Web3XdagModule.java similarity index 97% rename from src/main/java/io/xdag/rpc/modules/web3/Web3XdagModule.java rename to src/main/java/io/xdag/rpc/modules/xdag/Web3XdagModule.java index 121d8d43..bd81d5cd 100644 --- a/src/main/java/io/xdag/rpc/modules/web3/Web3XdagModule.java +++ b/src/main/java/io/xdag/rpc/modules/xdag/Web3XdagModule.java @@ -22,13 +22,12 @@ * THE SOFTWARE. */ -package io.xdag.rpc.modules.web3; +package io.xdag.rpc.modules.xdag; import io.xdag.rpc.Web3; import io.xdag.rpc.dto.BlockResultDTO; import io.xdag.rpc.dto.ConfigDTO; import io.xdag.rpc.dto.StatusDTO; -import io.xdag.rpc.modules.xdag.XdagModule; public interface Web3XdagModule { diff --git a/src/main/java/io/xdag/rpc/modules/web3/Web3XdagModuleImpl.java b/src/main/java/io/xdag/rpc/modules/xdag/Web3XdagModuleImpl.java similarity index 92% rename from src/main/java/io/xdag/rpc/modules/web3/Web3XdagModuleImpl.java rename to src/main/java/io/xdag/rpc/modules/xdag/Web3XdagModuleImpl.java index 247817bc..3b3e731b 100644 --- a/src/main/java/io/xdag/rpc/modules/web3/Web3XdagModuleImpl.java +++ b/src/main/java/io/xdag/rpc/modules/xdag/Web3XdagModuleImpl.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package io.xdag.rpc.modules.web3; +package io.xdag.rpc.modules.xdag; import static io.xdag.config.Constants.CLIENT_VERSION; import static io.xdag.rpc.utils.TypeConverter.toQuantityJsonHex; @@ -31,9 +31,9 @@ import static io.xdag.utils.BasicUtils.amount2xdag; import static io.xdag.utils.BasicUtils.getHash; import static io.xdag.utils.BasicUtils.pubAddress2Hash; -import static io.xdag.utils.PubkeyAddressUtils.checkAddress; -import static io.xdag.utils.PubkeyAddressUtils.fromBase58; -import static io.xdag.utils.PubkeyAddressUtils.toBase58; +import static io.xdag.utils.WalletUtils.checkAddress; +import static io.xdag.utils.WalletUtils.fromBase58; +import static io.xdag.utils.WalletUtils.toBase58; import io.xdag.Kernel; import io.xdag.Wallet; @@ -55,7 +55,6 @@ import io.xdag.rpc.dto.NetConnDTO; import io.xdag.rpc.dto.PoolWorkerDTO; import io.xdag.rpc.dto.StatusDTO; -import io.xdag.rpc.modules.xdag.XdagModule; import io.xdag.utils.BasicUtils; import java.net.InetSocketAddress; import java.util.Collection; @@ -64,18 +63,17 @@ import java.util.Map; import java.util.Objects; -import io.xdag.utils.PubkeyAddressUtils; +import lombok.extern.slf4j.Slf4j; + import org.apache.commons.lang3.StringUtils; import org.apache.tuweni.bytes.Bytes32; import org.apache.tuweni.bytes.MutableBytes32; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; +@Slf4j public class Web3XdagModuleImpl implements Web3XdagModule { - private static final Logger logger = LoggerFactory.getLogger(Web3XdagModuleImpl.class); private final Blockchain blockchain; private final XdagModule xdagModule; private final Kernel kernel; @@ -125,7 +123,7 @@ public Object xdag_syncing() { return s; } finally { - logger.debug("xdag_syncing():current {}, highest {}, isSyncDone {}", s.currentBlock, s.highestBlock, + log.debug("xdag_syncing():current {}, highest {}, isSyncDone {}", s.currentBlock, s.highestBlock, s.isSyncDone); } } @@ -138,7 +136,7 @@ public String xdag_coinbase() { @Override public String xdag_blockNumber() { long b = blockchain.getXdagStats().nmain; - logger.debug("xdag_blockNumber(): {}", b); + log.debug("xdag_blockNumber(): {}", b); return Long.toString(b); } @@ -196,12 +194,12 @@ public StatusDTO xdag_getStatus() { } @Override - public Object xdag_netType() throws Exception { + public Object xdag_netType() { return kernel.getConfig().getRootDir(); } @Override - public Object xdag_poolConfig() throws Exception { + public Object xdag_poolConfig() { PoolSpec poolSpec = kernel.getConfig().getPoolSpec(); NodeSpec nodeSpec = kernel.getConfig().getNodeSpec(); ConfigDTO.ConfigDTOBuilder configDTOBuilder = ConfigDTO.builder(); @@ -222,7 +220,7 @@ public Object xdag_poolConfig() throws Exception { } @Override - public Object xdag_netConnectionList() throws Exception { + public Object xdag_netConnectionList() { List netConnDTOList = Lists.newArrayList(); NetConnDTO.NetConnDTOBuilder netConnDTOBuilder = NetConnDTO.builder(); Map map = kernel.getNodeMgr().getActiveNode(); @@ -247,7 +245,7 @@ static class SyncingResult { } @Override - public Object xdag_updatePoolConfig(ConfigDTO configDTO, String passphrase) throws Exception { + public Object xdag_updatePoolConfig(ConfigDTO configDTO, String passphrase) { try { //unlock if (checkPassword(passphrase)) { @@ -282,12 +280,12 @@ public Object xdag_getPoolWorkers() { } @Override - public String xdag_getMaxXferBalance() throws Exception { + public String xdag_getMaxXferBalance() { return xdagModule.getMaxXferBalance(); } private PoolWorkerDTO getPoolWorkerDTO(PoolWorkerDTO.PoolWorkerDTOBuilder poolWorkerDTOBuilder,Miner miner){ - poolWorkerDTOBuilder.address(PubkeyAddressUtils.toBase58(miner.getAddressHashByte())) + poolWorkerDTOBuilder.address(toBase58(miner.getAddressHashByte())) .status(miner.getMinerStates().toString()) .unpaidShares(MinerCalculate.calculateUnpaidShares(miner)) .hashrate(BasicUtils.xdag_log_difficulty2hashrate(miner.getMeanLogDiff())) diff --git a/src/main/java/io/xdag/rpc/modules/xdag/XdagModuleChainBase.java b/src/main/java/io/xdag/rpc/modules/xdag/XdagModuleChainBase.java index 4ad09667..8fbc2214 100644 --- a/src/main/java/io/xdag/rpc/modules/xdag/XdagModuleChainBase.java +++ b/src/main/java/io/xdag/rpc/modules/xdag/XdagModuleChainBase.java @@ -42,8 +42,8 @@ import static io.xdag.utils.BasicUtils.amount2xdag; import static io.xdag.utils.BasicUtils.hash2Address; import static io.xdag.utils.BasicUtils.pubAddress2Hash; -import static io.xdag.utils.PubkeyAddressUtils.checkAddress; -import static io.xdag.utils.PubkeyAddressUtils.toBase58; +import static io.xdag.utils.WalletUtils.checkAddress; +import static io.xdag.utils.WalletUtils.toBase58; import static io.xdag.utils.XdagTime.xdagTimestampToMs; import io.xdag.Kernel; @@ -57,10 +57,11 @@ import io.xdag.rpc.dto.BlockResultDTO.Link; import io.xdag.rpc.dto.BlockResultDTO.TxLink; import io.xdag.utils.BasicUtils; +import io.xdag.utils.BytesUtils; + import java.nio.charset.StandardCharsets; import java.util.List; -import io.xdag.utils.ByteArrayToByte32; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.tuweni.bytes.Bytes32; @@ -338,7 +339,7 @@ private List getTxHistory(String address) { .time(xdagTimestampToMs(txHistory.getTimeStamp())) .remark(txHistory.getRemark()); } else { - txLinkBuilder.address(toBase58(ByteArrayToByte32.byte32ToArray(txHistory.getAddress().getAddress()))) + txLinkBuilder.address(toBase58(BytesUtils.byte32ToArray(txHistory.getAddress().getAddress()))) .hashlow(txHistory.getAddress().getAddress().toUnprefixedHexString()) .amount(String.format("%.9f", amount2xdag(txHistory.getAddress().getAmount()))) .direction(txHistory.getAddress().getType().equals(XDAG_FIELD_IN) ? 0 : diff --git a/src/main/java/io/xdag/rpc/modules/xdag/XdagModuleTransactionBase.java b/src/main/java/io/xdag/rpc/modules/xdag/XdagModuleTransactionBase.java index 709ba757..3019a1ff 100644 --- a/src/main/java/io/xdag/rpc/modules/xdag/XdagModuleTransactionBase.java +++ b/src/main/java/io/xdag/rpc/modules/xdag/XdagModuleTransactionBase.java @@ -32,14 +32,13 @@ import io.xdag.rpc.Web3; import io.xdag.rpc.Web3.CallArguments; import io.xdag.utils.BasicUtils; +import lombok.extern.slf4j.Slf4j; + import org.bouncycastle.util.encoders.Hex; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +@Slf4j public class XdagModuleTransactionBase implements XdagModuleTransaction { - protected static final Logger logger = LoggerFactory.getLogger(XdagModuleTransactionBase.class); - private final Kernel kernel; public XdagModuleTransactionBase(Kernel kernel) { diff --git a/src/main/java/io/xdag/rpc/modules/xdag/XdagModuleTransactionEnabled.java b/src/main/java/io/xdag/rpc/modules/xdag/XdagModuleTransactionEnabled.java index d0dc5209..c94ef3d0 100644 --- a/src/main/java/io/xdag/rpc/modules/xdag/XdagModuleTransactionEnabled.java +++ b/src/main/java/io/xdag/rpc/modules/xdag/XdagModuleTransactionEnabled.java @@ -47,9 +47,10 @@ import io.xdag.rpc.Web3.CallArguments; import io.xdag.rpc.dto.ProcessResult; import io.xdag.utils.BasicUtils; -import io.xdag.utils.PubkeyAddressUtils; +import io.xdag.utils.WalletUtils; import io.xdag.utils.exception.XdagOverFlowException; -import java.util.ArrayList; +import lombok.extern.slf4j.Slf4j; + import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; @@ -59,6 +60,7 @@ import org.apache.tuweni.units.bigints.UInt64; import org.hyperledger.besu.crypto.KeyPair; +@Slf4j public class XdagModuleTransactionEnabled extends XdagModuleTransactionBase { private final Kernel kernel; @@ -76,7 +78,7 @@ public String sendRawTransaction(String rawData) { @Override public Object personalSendTransaction(CallArguments args, String passphrase) { - logger.debug("personalSendTransaction args:{}",args); + log.debug("personalSendTransaction args:{}",args); String from = args.from; String to = args.to; @@ -137,7 +139,7 @@ public void doXfer(double sendValue,Bytes32 fromAddress, Bytes32 toAddress,Strin // 如果没有from则从节点账户里搜索 if (fromAddress == null) { - logger.debug("fromAddress is null, search all our blocks"); + log.debug("fromAddress is null, search all our blocks"); // our block select List accounts = kernel.getWallet().getAccounts(); @@ -212,21 +214,12 @@ private Bytes32 checkAddress(String address,ProcessResult processResult) { Bytes32 hash = null; // check whether to is exist in blockchain - if (PubkeyAddressUtils.checkAddress(address)) { + if (WalletUtils.checkAddress(address)) { hash = pubAddress2Hash(address); } else { processResult.setCode(ERR_TO_ADDRESS_INVALID.code()); processResult.setErrMsg(ERR_TO_ADDRESS_INVALID.msg()); } -// if (hash == null) { -// processResult.setCode(ERR_TO_ADDRESS_INVALID.code()); -// processResult.setErrMsg(ERR_TO_ADDRESS_INVALID.msg()); -// } else { -// if (kernel.getBlockchain().getBlockByHash(Bytes32.wrap(hash), false) == null) { -// processResult.setCode(ERR_TO_ADDRESS_INVALID.code()); -// processResult.setErrMsg(ERR_TO_ADDRESS_INVALID.msg()); -// } -// } return hash; } diff --git a/src/main/java/io/xdag/rpc/netty/JsonRpcWeb3ServerHandler.java b/src/main/java/io/xdag/rpc/netty/JsonRpcWeb3ServerHandler.java index 2d0d8fff..07755b69 100644 --- a/src/main/java/io/xdag/rpc/netty/JsonRpcWeb3ServerHandler.java +++ b/src/main/java/io/xdag/rpc/netty/JsonRpcWeb3ServerHandler.java @@ -45,16 +45,16 @@ import io.xdag.rpc.exception.XdagErrorResolver; import io.xdag.rpc.filter.JsonRpcMethodFilter; import io.xdag.rpc.modules.ModuleDescription; +import lombok.extern.slf4j.Slf4j; + import java.util.HashMap; import java.util.List; import java.util.Map; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +@Slf4j @ChannelHandler.Sharable public class JsonRpcWeb3ServerHandler extends SimpleChannelInboundHandler { - private static final Logger LOGGER = LoggerFactory.getLogger("jsonrpc"); private final ObjectMapper mapper = new ObjectMapper(); private final JsonNodeFactory jsonNodeFactory = JsonNodeFactory.instance; private final JsonRpcBasicServer jsonRpcServer; @@ -77,7 +77,7 @@ protected void channelRead0(ChannelHandlerContext ctx, ByteBufHolder request) th responseCode = jsonRpcServer.handleRequest(is, os); } catch (Exception e) { String unexpectedErrorMsg = "Unexpected error"; - LOGGER.error(unexpectedErrorMsg, e); + log.error(unexpectedErrorMsg, e); int errorCode = ErrorResolver.JsonError.CUSTOM_SERVER_ERROR_LOWER; responseContent = buildErrorContent(errorCode, unexpectedErrorMsg); responseCode = errorCode; @@ -91,7 +91,7 @@ protected void channelRead0(ChannelHandlerContext ctx, ByteBufHolder request) th @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - LOGGER.error("Unexpected exception", cause); + log.error("Unexpected exception", cause); ctx.close(); } diff --git a/src/main/java/io/xdag/rpc/netty/Web3HttpServer.java b/src/main/java/io/xdag/rpc/netty/Web3HttpServer.java index 14044c7f..4cde5346 100644 --- a/src/main/java/io/xdag/rpc/netty/Web3HttpServer.java +++ b/src/main/java/io/xdag/rpc/netty/Web3HttpServer.java @@ -43,13 +43,15 @@ import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.xdag.rpc.cors.CorsConfiguration; +import lombok.extern.slf4j.Slf4j; + import java.net.InetAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@Slf4j public class Web3HttpServer { - private static final Logger logger = LoggerFactory.getLogger(Web3HttpServer.class); private final InetAddress bindAddress; private final int port; private final EventLoopGroup bossGroup; @@ -79,7 +81,7 @@ public Web3HttpServer(InetAddress bindAddress, } public void start() { - logger.info("RPC HTTP enabled"); + log.info("RPC HTTP enabled"); ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_REUSEADDR, reuseAddress); @@ -111,7 +113,7 @@ protected void initChannel(SocketChannel ch) { try { b.bind(bindAddress, port).sync(); } catch (InterruptedException e) { - logger.error("The RPC HTTP server couldn't be started", e); + log.error("The RPC HTTP server couldn't be started", e); Thread.currentThread().interrupt(); } } diff --git a/src/main/java/io/xdag/utils/BasicUtils.java b/src/main/java/io/xdag/utils/BasicUtils.java index 478ae0d8..2c309ebf 100644 --- a/src/main/java/io/xdag/utils/BasicUtils.java +++ b/src/main/java/io/xdag/utils/BasicUtils.java @@ -61,7 +61,6 @@ public static BigInteger getDiffByHash(Bytes32 hash) { public static Bytes32 getHash(String address) { Bytes32 hash = null; if (address != null) { -// hash = Hex.decode(address); hash = Bytes32.fromHexString(address); } return hash; @@ -78,17 +77,14 @@ public static String hash2Address(Bytes32 hash) { } public static Bytes32 address2Hash(String address) { -// byte[] ret = Base64.decode(address); Bytes ret = Bytes.fromBase64String(address); -// byte[] res = new byte[32]; MutableBytes32 res = MutableBytes32.create(); -// System.arraycopy(Arrays.reverse(ret),0,res,8,24); res.set(8, ret.reverse().slice(0, 24)); return res; } public static Bytes32 pubAddress2Hash(String address) { - Bytes ret = Bytes.wrap(PubkeyAddressUtils.fromBase58(address)); + Bytes ret = Bytes.wrap(WalletUtils.fromBase58(address)); MutableBytes32 res = MutableBytes32.create(); res.set(8, ret); return res; diff --git a/src/main/java/io/xdag/utils/BlockUtils.java b/src/main/java/io/xdag/utils/BlockUtils.java index b6972851..45e17c7c 100644 --- a/src/main/java/io/xdag/utils/BlockUtils.java +++ b/src/main/java/io/xdag/utils/BlockUtils.java @@ -44,7 +44,6 @@ public static byte[] getOurKey(int index, byte[] hashlow) { return key; } - // ADD: 高度键 public static byte[] getHeight(long height) { return BytesUtils.merge(BlockStore.BLOCK_HEIGHT, BytesUtils.longToBytes(height, false)); } diff --git a/src/main/java/io/xdag/utils/ByteArrayToByte32.java b/src/main/java/io/xdag/utils/ByteArrayToByte32.java deleted file mode 100644 index ef1022f7..00000000 --- a/src/main/java/io/xdag/utils/ByteArrayToByte32.java +++ /dev/null @@ -1,43 +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.utils; - -import org.apache.tuweni.bytes.Bytes; -import org.apache.tuweni.bytes.MutableBytes32; - -/** - * @author Dcj_Cory - * @date 2022/11/7 4:47 PM - */ -public class ByteArrayToByte32 { - public static MutableBytes32 arrayToByte32(byte[] value){ - MutableBytes32 mutableBytes32 = MutableBytes32.wrap(new byte[32]); - mutableBytes32.set(8, Bytes.wrap(value)); - return mutableBytes32; - } - public static byte[] byte32ToArray(MutableBytes32 value){ - return value.mutableCopy().slice(8,20).toArray(); - } - -} diff --git a/src/main/java/io/xdag/utils/BytesUtils.java b/src/main/java/io/xdag/utils/BytesUtils.java index 33aed471..0086ce13 100644 --- a/src/main/java/io/xdag/utils/BytesUtils.java +++ b/src/main/java/io/xdag/utils/BytesUtils.java @@ -32,13 +32,12 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; 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; public class BytesUtils { - public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; - private static final byte[] ZERO_BYTE_ARRAY = new byte[]{0}; - public static byte[] intToBytes(int value, boolean littleEndian) { ByteBuffer buffer = ByteBuffer.allocate(4); if (littleEndian) { @@ -364,7 +363,14 @@ public int compareTo( } } - + public static MutableBytes32 arrayToByte32(byte[] value){ + MutableBytes32 mutableBytes32 = MutableBytes32.wrap(new byte[32]); + mutableBytes32.set(8, Bytes.wrap(value)); + return mutableBytes32; + } + public static byte[] byte32ToArray(MutableBytes32 value){ + return value.mutableCopy().slice(8,20).toArray(); + } public static UnsignedLong long2UnsignedLong(long number) { return UnsignedLong.valueOf(toHexString((ByteBuffer.allocate(8).putLong(number).array())),16); diff --git a/src/main/java/io/xdag/utils/PubkeyAddressUtils.java b/src/main/java/io/xdag/utils/PubkeyAddressUtils.java deleted file mode 100644 index aef71d28..00000000 --- a/src/main/java/io/xdag/utils/PubkeyAddressUtils.java +++ /dev/null @@ -1,50 +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.utils; - -import io.xdag.crypto.Base58; -import io.xdag.utils.exception.AddressFormatException; - -public class PubkeyAddressUtils { - - public static String toBase58(byte[] hash160) { - return Base58.encodeChecked(hash160); - } - - public static byte[] fromBase58(String base58) throws AddressFormatException { - byte[] bytes = Base58.decodeChecked(base58); - if (bytes.length != 20) - throw new AddressFormatException.InvalidDataLength("Wrong number of bytes: " + bytes.length); - return bytes; - } - - public static boolean checkAddress(String base58) { - return Base58.checkAddress(base58); - } - - public static boolean checkBytes24(byte[] data) { - return Base58.checkBytes24(data); - } - -} diff --git a/src/main/java/io/xdag/utils/SystemUtil.java b/src/main/java/io/xdag/utils/SystemUtil.java deleted file mode 100644 index 7da74939..00000000 --- a/src/main/java/io/xdag/utils/SystemUtil.java +++ /dev/null @@ -1,94 +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.utils; - -import java.nio.file.FileSystems; -import java.util.Locale; - -public class SystemUtil { - - /** - * Returns whether the JVM is in 32-bit data model - */ - public static boolean is32bitJvm() { - String model = System.getProperty("sun.arch.data.model"); - return model != null && model.contains("32"); - } - - /** - * Returns the operating system name. - */ - public static OsName getOsName() { - String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); - - if (os.contains("win")) { - return OsName.WINDOWS; - } else if (os.contains("linux")) { - return OsName.LINUX; - } else if (os.contains("mac")) { - return OsName.MACOS; - } else { - return OsName.UNKNOWN; - } - } - - /** - * Returns the operating system architecture - */ - public static String getOsArch() { - return System.getProperty("os.arch"); - } - - /** - * Check if current OS is POSIX compliant. - * - * @return whether current OS is POSIX compliant - */ - public static boolean isPosix() { - return FileSystems.getDefault().supportedFileAttributeViews().contains("posix"); - } - - public enum OsName { - WINDOWS("Windows"), - - LINUX("Linux"), - - MACOS("macOS"), - - UNKNOWN("Unknown"); - - private final String name; - - OsName(String name) { - this.name = name; - } - - @Override - public String toString() { - return name; - } - } - -} diff --git a/src/main/java/io/xdag/utils/WalletUtils.java b/src/main/java/io/xdag/utils/WalletUtils.java index d6cf429b..f6df34f3 100644 --- a/src/main/java/io/xdag/utils/WalletUtils.java +++ b/src/main/java/io/xdag/utils/WalletUtils.java @@ -27,8 +27,10 @@ import static io.xdag.crypto.Bip32ECKeyPair.HARDENED_BIT; import io.xdag.Wallet; +import io.xdag.crypto.Base58; import io.xdag.crypto.Bip32ECKeyPair; import io.xdag.crypto.MnemonicUtils; +import io.xdag.utils.exception.AddressFormatException; import lombok.extern.slf4j.Slf4j; @Slf4j @@ -53,4 +55,19 @@ public static Bip32ECKeyPair importMnemonic(Wallet wallet, String password, Stri return generateBip44KeyPair(masterKeypair, index); } + public static String toBase58(byte[] hash160) { + return Base58.encodeChecked(hash160); + } + + public static byte[] fromBase58(String base58) throws AddressFormatException { + byte[] bytes = Base58.decodeChecked(base58); + if (bytes.length != 20) + throw new AddressFormatException.InvalidDataLength("Wrong number of bytes: " + bytes.length); + return bytes; + } + + public static boolean checkAddress(String base58) { + return Base58.checkAddress(base58); + } + } \ No newline at end of file diff --git a/src/test/java/io/xdag/core/BlockchainTest.java b/src/test/java/io/xdag/core/BlockchainTest.java index 2f1bb172..6fbf96bb 100644 --- a/src/test/java/io/xdag/core/BlockchainTest.java +++ b/src/test/java/io/xdag/core/BlockchainTest.java @@ -64,7 +64,7 @@ import io.xdag.db.rocksdb.OrphanBlockStoreImpl; import io.xdag.db.rocksdb.RocksdbFactory; import io.xdag.utils.BasicUtils; -import io.xdag.utils.ByteArrayToByte32; +import io.xdag.utils.BytesUtils; import io.xdag.utils.XdagTime; import io.xdag.Wallet; import java.io.IOException; @@ -235,10 +235,8 @@ public void testNew2NewTransactionBlock() { } //TODO 两种不同的交易模式的测试 // 3. make one transaction(100 XDAG) block(from No.1 mainblock to address block) - Address from = new Address(ByteArrayToByte32.arrayToByte32(Keys.toBytesAddress(poolKey)), XDAG_FIELD_INPUT,true); -// System.out.println(PubkeyAddressUtils.toBase58(from.getAddress().slice(8,20).toArray())); - Address to = new Address(ByteArrayToByte32.arrayToByte32(Keys.toBytesAddress(addrKey)), XDAG_FIELD_OUTPUT,true); -// System.out.println(PubkeyAddressUtils.toBase58(to.getAddress().slice(8,20).toArray())); + Address from = new Address(BytesUtils.arrayToByte32(Keys.toBytesAddress(poolKey)), XDAG_FIELD_INPUT,true); + Address to = new Address(BytesUtils.arrayToByte32(Keys.toBytesAddress(addrKey)), XDAG_FIELD_OUTPUT,true); long xdagTime = XdagTime.getEndOfEpoch(XdagTime.msToXdagtimestamp(generateTime)); Block txBlock = generateNewTransactionBlock(config, poolKey, xdagTime - 1, from, to, xdag2amount(100.00)); @@ -317,9 +315,7 @@ public void testOld2NewTransaction(){ //TODO 两种不同的交易模式的测试 // 3. make one transaction(100 XDAG) block(from No.1 mainblock to address block) Address from = new Address(addressBlock.getHashLow(), XDAG_FIELD_IN,false); -// System.out.println(PubkeyAddressUtils.toBase58(from.getAddress().slice(8,20).toArray())); - Address to = new Address(ByteArrayToByte32.arrayToByte32(Keys.toBytesAddress(addrKey)), XDAG_FIELD_OUTPUT,true); -// System.out.println(PubkeyAddressUtils.toBase58(to.getAddress().slice(8,20).toArray())); + Address to = new Address(BytesUtils.arrayToByte32(Keys.toBytesAddress(addrKey)), XDAG_FIELD_OUTPUT,true); long xdagTime = XdagTime.getEndOfEpoch(XdagTime.msToXdagtimestamp(generateTime)); Block txBlock = generateOldTransactionBlock(config, poolKey, xdagTime - 1, from, to, xdag2amount(100.00)); diff --git a/src/test/java/io/xdag/mine/miner/MinerConnectTest.java b/src/test/java/io/xdag/mine/miner/MinerConnectTest.java index c412563b..a562d287 100644 --- a/src/test/java/io/xdag/mine/miner/MinerConnectTest.java +++ b/src/test/java/io/xdag/mine/miner/MinerConnectTest.java @@ -49,7 +49,6 @@ import io.xdag.db.rocksdb.RocksdbFactory; import io.xdag.mine.MinerChannel; import io.xdag.mine.handler.MinerHandShakeHandler; -import io.xdag.utils.ByteArrayToByte32; import io.xdag.utils.BytesUtils; import io.xdag.Wallet; import java.io.IOException; @@ -89,10 +88,6 @@ public void setUp() throws Exception { config.getNodeSpec().setStoreDir(root.newFolder().getAbsolutePath()); config.getNodeSpec().setStoreBackupDir(root.newFolder().getAbsolutePath()); -// Native.init(config); -// if (Native.dnet_crypt_init() < 0) { -// throw new Exception("dnet crypt init failed"); -// } pwd = "password"; wallet = new Wallet(config); wallet.unlock(pwd); @@ -155,78 +150,6 @@ public void testMinerConnect() //5、读取数据 ByteBuf readInbound = embeddedChannel.readInbound(); assertEquals(1, readInbound.readInt()); - -// String fake = "0000000000000000510500000000000011100b07790100000000000000000000913c141ee4175a018a3412ba52f827d2fd67da7c0c581641e9f48a81e9dbd8f2486fac9f54560465e53a20f21940a335414f3949fc807f187fb57f51a48611220000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; -// address = new Block(new XdagBlock(Hex.decode(fake))); -// encoded = address.getXdagBlock().getData(); -// data = encoded.toArray(); -// -// buf.clear(); -// buf.writeBytes(data); -// buf1 = buf.duplicate(); -// embeddedChannel = new EmbeddedChannel(new MockMinerHandshakeHandler(channel, kernel)); -// //3、将数据写入 EmbeddedChannel -// writeInbound = embeddedChannel.writeInbound(buf1.retain()); -// assertTrue(writeInbound); -// //4、标记 Channel 为已完成状态 -// finish = embeddedChannel.finish(); -// assertTrue(finish); -// -// //5、读取数据 -// readInbound = embeddedChannel.readInbound(); -// assertEquals(0, readInbound.readInt()); -// -// //释放资源 -// buf.release(); -// } -// @Test -// public void testNewMinerConnect() -// throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException { -//// Native.crypt_start(); -// KeyPair key = Keys.createEcKeyPair(); -// byte[] address = Keys.toBytesAddress(key); -// -//// byte[] data = Native.dfslib_encrypt_array(encoded.toArray(), 16, 0); -// -// ByteBuf buf = Unpooled.buffer(); -// buf.writeBytes(address); -// ByteBuf buf1 = buf.duplicate(); -// //2、创建EmbeddedChannel,并添加一个MinerHandshakeHandler -// EmbeddedChannel embeddedChannel = new EmbeddedChannel(new MockMinerHandshakeHandler(channel, kernel)); -// -// //3、将数据写入 EmbeddedChannel -// boolean writeInbound = embeddedChannel.writeInbound(buf1.retain()); -// assertTrue(writeInbound); -// //4、标记 Channel 为已完成状态 -// boolean finish = embeddedChannel.finish(); -// assertTrue(finish); -// -// //5、读取数据 -// ByteBuf readInbound = embeddedChannel.readInbound(); -// assertEquals(1, readInbound.readInt()); - -// String fake = "0000000000000000510500000000000011100b07790100000000000000000000913c141ee4175a018a3412ba52f827d2fd67da7c0c581641e9f48a81e9dbd8f2486fac9f54560465e53a20f21940a335414f3949fc807f187fb57f51a48611220000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; -// address = new Block(new XdagBlock(Hex.decode(fake))); -// encoded = address.getXdagBlock().getData(); -// data = Native.dfslib_encrypt_array(encoded.toArray(), 16, 0); - -// buf.clear(); -// buf.writeBytes(data); -// buf1 = buf.duplicate(); -// embeddedChannel = new EmbeddedChannel(new MockMinerHandshakeHandler(channel, kernel)); -// //3、将数据写入 EmbeddedChannel -// writeInbound = embeddedChannel.writeInbound(buf1.retain()); -// assertTrue(writeInbound); -// //4、标记 Channel 为已完成状态 -// finish = embeddedChannel.finish(); -// assertTrue(finish); -// -// //5、读取数据 -// readInbound = embeddedChannel.readInbound(); -// assertEquals(0, readInbound.readInt()); -// -// //释放资源 -// buf.release(); } } class MockMinerHandshakeHandler extends MinerHandShakeHandler { @@ -235,17 +158,6 @@ public MockMinerHandshakeHandler(MinerChannel channel, Kernel kernel) { super(channel, kernel); } - -// @Override - public boolean isDataIllegal(byte[] uncryptData) { - return false; - } - -// @Override -// public ImportResult tryToConnect(Block addressBlock) { -// return blockchain.tryToConnect(addressBlock); -// } - @Override public boolean initMiner(Bytes32 hash) { return true; @@ -255,29 +167,16 @@ public boolean initMiner(Bytes32 hash) { protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) { if (in.readableBytes() >= 20) { ByteBuf byteBuf = Unpooled.buffer(); - byte[] address = new byte[20]; in.readBytes(address); -// long sectorNo = 0; - - /* 解密数据 */ -// byte[] uncryptData = Native.dfslib_uncrypt_array(address, 16, sectorNo); -// if (isDataIllegal(uncryptData.clone())) { -// ctx.channel().closeFuture(); -// } else { System.arraycopy(BytesUtils.longToBytes(0, true), 0, address, 0, 8); -// if (importResult.getErrorInfo() != null) { -// byteBuf = Unpooled.buffer(); -// byteBuf.writeInt(0); -// out.add(byteBuf.retain()); -// } - if (!initMiner(ByteArrayToByte32.arrayToByte32(address))) { + + if (!initMiner(BytesUtils.arrayToByte32(address))) { ctx.close(); } byteBuf.writeInt(1); out.add(byteBuf.retain()); } } -// } } diff --git a/src/test/java/io/xdag/rpc/Web3XdagModuleTest.java b/src/test/java/io/xdag/rpc/Web3XdagModuleTest.java index 0aa3ee37..1923779e 100644 --- a/src/test/java/io/xdag/rpc/Web3XdagModuleTest.java +++ b/src/test/java/io/xdag/rpc/Web3XdagModuleTest.java @@ -36,8 +36,8 @@ import io.xdag.db.rocksdb.DatabaseName; import io.xdag.db.rocksdb.OrphanBlockStoreImpl; import io.xdag.db.rocksdb.RocksdbFactory; -import io.xdag.rpc.modules.web3.Web3XdagModule; -import io.xdag.rpc.modules.web3.Web3XdagModuleImpl; +import io.xdag.rpc.modules.xdag.Web3XdagModule; +import io.xdag.rpc.modules.xdag.Web3XdagModuleImpl; import io.xdag.rpc.modules.xdag.XdagModule; import io.xdag.Wallet; import java.io.IOException; diff --git a/src/test/java/io/xdag/utils/PubkeyAddressUtilsTest.java b/src/test/java/io/xdag/utils/PubkeyAddressUtilsTest.java index 28c1f2ea..6cf9e789 100644 --- a/src/test/java/io/xdag/utils/PubkeyAddressUtilsTest.java +++ b/src/test/java/io/xdag/utils/PubkeyAddressUtilsTest.java @@ -42,29 +42,29 @@ public void pulkeyAddressTest() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException { KeyPair key = Keys.createEcKeyPair(); byte[] hash160 = Keys.toBytesAddress(key); - String base58 = PubkeyAddressUtils.toBase58(hash160); - assertArrayEquals(PubkeyAddressUtils.fromBase58(base58), hash160); + String base58 = WalletUtils.toBase58(hash160); + assertArrayEquals(WalletUtils.fromBase58(base58), hash160); } @Test(expected = AddressFormatException.class) public void testAddressFormatException() { //the correct base58 = "7pWm5FZaNVV61wb4vQapqVixPaLC7Dh2C" String base58 = "7pWm5FZaNVV61wb4vQapqVixPaLC7Dh2a"; - PubkeyAddressUtils.fromBase58(base58); + WalletUtils.fromBase58(base58); } @Test public void testCheckAddress() { - assertTrue(PubkeyAddressUtils.checkAddress("7pWm5FZaNVV61wb4vQapqVixPaLC7Dh2C")); - assertFalse(PubkeyAddressUtils.checkAddress("7pWm5FZaNVV61wb4vQapqVixPaLC7Dh2a")); + assertTrue(WalletUtils.checkAddress("7pWm5FZaNVV61wb4vQapqVixPaLC7Dh2C")); + assertFalse(WalletUtils.checkAddress("7pWm5FZaNVV61wb4vQapqVixPaLC7Dh2a")); } @Test public void testToByte32(){ String addressStr = "7pWm5FZaNVV61wb4vQapqVixPaLC7Dh2C"; - byte[] addressbyte = PubkeyAddressUtils.fromBase58(addressStr); - MutableBytes32 address= ByteArrayToByte32.arrayToByte32(addressbyte); - String res = PubkeyAddressUtils.toBase58(ByteArrayToByte32.byte32ToArray(address)); + byte[] addressbyte = WalletUtils.fromBase58(addressStr); + MutableBytes32 address= BytesUtils.arrayToByte32(addressbyte); + String res = WalletUtils.toBase58(BytesUtils.byte32ToArray(address)); Assert.assertEquals(addressStr, res); } }