prioritized = new ConcurrentLinkedQueue<>();
+ private ChannelHandlerContext ctx;
private ScheduledFuture> timerTask;
- public MessageQueue(Channel channel) {
- this.channel = channel;
+ private final AtomicBoolean isClosed = new AtomicBoolean(false);
+
+ public MessageQueue(Config config) {
+ this.config = config;
}
- public void activate(ChannelHandlerContext ctx) {
+ public synchronized void activate(ChannelHandlerContext ctx) {
this.ctx = ctx;
- isRunning = true;
timerTask = timer.scheduleAtFixedRate(
() -> {
try {
@@ -74,58 +78,53 @@ public void activate(ChannelHandlerContext ctx) {
TimeUnit.MILLISECONDS);
}
+ public synchronized void deactivate() {
+ this.timerTask.cancel(false);
+ }
- private void nudgeQueue() {
- int n = Math.min(5, size());
- if (n == 0) {
- return;
- }
- // write out n messages
- for (int i = 0; i < n; i++) {
- // Now send the next message
- // log.debug("Sent to Wire with the message,msg:"+msg.getCommand());
- Message respondMsg = respondQueue.poll();
- Message requestMsg = requestQueue.poll();
- if (respondMsg != null) {
- ctx.write(respondMsg).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
- }
- if (requestMsg != null) {
- ctx.write(requestMsg).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
- }
+ public boolean isIdle() {
+ return size() == 0;
+ }
+
+ public void disconnect(ReasonCode code) {
+ log.debug("Actively closing the connection: reason = {}", code);
+ // avoid repeating close requests
+ if (isClosed.compareAndSet(false, true)) {
+ ctx.writeAndFlush(new DisconnectMessage(code)).addListener((ChannelFutureListener) future -> ctx.close());
}
- ctx.flush();
}
- public void sendMessage(Message msg) {
- if (channel.isDisconnected()) {
- log.warn("{}: attempt to send [{}] message after disconnect", channel, msg.getCommand().name());
- return;
+ public boolean sendMessage(Message msg) {
+ if (size() >= config.getNodeSpec().getNetMaxMessageQueueSize()) {
+ disconnect(ReasonCode.MESSAGE_QUEUE_FULL);
+ return false;
}
- if (msg.getAnswerMessage() != null) {
- requestQueue.add(msg);
+ if (config.getNodeSpec().getNetPrioritizedMessages().contains(msg.getCode())) {
+ prioritized.add(msg);
} else {
- respondQueue.add(msg);
+ queue.add(msg);
}
+ return true;
}
- public void disconnect() {
- ctx.close();
+ public int size() {
+ return queue.size() + prioritized.size();
}
- public void close() {
- isRunning = false;
- if (timerTask != null) {
- timerTask.cancel(false);
+ private void nudgeQueue() {
+ int n = Math.min(5, size());
+ if (n == 0) {
+ return;
}
- }
-
- public boolean isRunning() {
- return isRunning;
- }
+ // write out n messages
+ for (int i = 0; i < n; i++) {
+ Message msg = !prioritized.isEmpty() ? prioritized.poll() : queue.poll();
- public int size() {
- return requestQueue.size() + respondQueue.size();
+ log.trace("Wiring message: {}", msg);
+ ctx.write(msg).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
+ }
+ ctx.flush();
}
}
diff --git a/src/main/java/io/xdag/config/spec/PoolSpec.java b/src/main/java/io/xdag/net/message/ReasonCode.java
similarity index 52%
rename from src/main/java/io/xdag/config/spec/PoolSpec.java
rename to src/main/java/io/xdag/net/message/ReasonCode.java
index 93a1b755e..28af01999 100644
--- a/src/main/java/io/xdag/config/spec/PoolSpec.java
+++ b/src/main/java/io/xdag/net/message/ReasonCode.java
@@ -21,68 +21,78 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+package io.xdag.net.message;
-package io.xdag.config.spec;
-
-/**
- * The Mining Pool Specifications
- */
-public interface PoolSpec {
-
- String getPoolIp();
-
- int getPoolPort();
-
- String getPoolTag();
-
- int getGlobalMinerLimit();
-
- int getGlobalMinerChannelLimit();
-
- int getMaxConnectPerIp();
+public enum ReasonCode {
/**
- * 拥有相同地址块的矿工最多允许同时在线的数量 g_connections_per_miner_limit
+ * [0x00] Bad network.
*/
- int getMaxMinerPerAccount();
-
- int getMaxShareCountPerChannel();
-
- int getConnectionTimeout();
+ BAD_NETWORK(0x00),
+ /**
+ * [0x01] Incompatible protocol.
+ */
+ BAD_NETWORK_VERSION(0x01),
/**
- * 矿池自己的收益占比
+ * [0x02] Too many active peers.
*/
- double getPoolRation();
+ TOO_MANY_PEERS(0x02),
/**
- * 出块矿工收益占比
+ * [0x03] Invalid handshake message.
*/
- double getRewardRation();
+ INVALID_HANDSHAKE(0x03),
/**
- * 基金会收益占比
+ * [0x04] Duplicated peerId.
*/
- double getFundRation();
+ DUPLICATED_PEER_ID(0x04),
/**
- * 参与奖励的占比
+ * [0x05] The message queue is full.
*/
- double getDirectRation();
+ MESSAGE_QUEUE_FULL(0x05),
/**
- * 奖励支付的周期
+ * [0x06] Another validator peer tries to connect using the same IP.
*/
- int getAwardEpoch();
+ VALIDATOR_IP_LIMITED(0x06),
/**
- * 等待超过10个epoch默认启动挖矿
+ * [0x07] The peer tries to re-handshake.
*/
- int getWaitEpoch();
+ HANDSHAKE_EXISTS(0x07),
/**
- * 基金会地址
+ * [0x08] The manifests malicious behavior.
*/
- String getFundAddress();
+ BAD_PEER(0x08);
+
+ private int code;
+
+ private static final ReasonCode[] intToCode = new ReasonCode[256];
+
+ static {
+ for (ReasonCode mc : ReasonCode.values()) {
+ intToCode[mc.code] = mc;
+ }
+ }
+
+ public static ReasonCode of(int code) {
+ return intToCode[0xff & code];
+ }
+
+ ReasonCode(int code) {
+ this.code = code;
+ }
+
+ public int getCode() {
+ return code;
+ }
+
+ public byte toByte() {
+ return (byte) code;
+ }
}
diff --git a/src/main/java/io/xdag/net/message/XdagMessageCodes.java b/src/main/java/io/xdag/net/message/XdagMessageCodes.java
deleted file mode 100644
index e1b8a0f41..000000000
--- a/src/main/java/io/xdag/net/message/XdagMessageCodes.java
+++ /dev/null
@@ -1,123 +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.message;
-
-import static io.xdag.net.XdagVersion.V03;
-
-import com.google.common.collect.Maps;
-import io.xdag.net.XdagVersion;
-import java.util.Map;
-
-/**
- * xdag block.h
- *
- *
- * enum xdag_message_type {
- * XDAG_MESSAGE_BLOCKS_REQUEST,
- * XDAG_MESSAGE_BLOCKS_REPLY,
- * XDAG_MESSAGE_SUMS_REQUEST,
- * XDAG_MESSAGE_SUMS_REPLY,
- * XDAG_MESSAGE_BLOCKEXT_REQUEST,
- * XDAG_MESSAGE_BLOCKEXT_REPLY,
- * XDAG_MESSAGE_BLOCK_REQUEST
- * };
- */
-public enum XdagMessageCodes {
- // add new block type here
- BLOCKS_REQUEST(0x00),
- BLOCKS_REPLY(0x01),
- SUMS_REQUEST(0x02),
- SUMS_REPLY(0x03),
- BLOCKEXT_REQUEST(0x04),
- BLOCKEXT_REPLY(0x05),
- BLOCK_REQUEST(0x06),
-
- // add new block type here
- Receive_Block(0x07),
- TASK_SHARE(0x08),
- NEW_TASK(0x09),
- NEW_BALANCE(0x0A),
- NEW_BLOCK(0x0B),
- WORKER_NAME(0x0C),
- SYNC_BLOCK(0x0D),
- SYNCBLOCK_REQUEST(0x0E);
-
- private static final Map> intToTypeMap = Maps.newHashMap();
- private static final Map versionToValuesMap = Maps.newHashMap();
-
- static {
- versionToValuesMap.put(
- V03,
- new XdagMessageCodes[]{
- BLOCKS_REQUEST,
- BLOCKS_REPLY,
- SUMS_REQUEST,
- SUMS_REPLY,
- BLOCKEXT_REQUEST,
- BLOCKEXT_REPLY,
- BLOCK_REQUEST,
- Receive_Block,
- TASK_SHARE,
- NEW_TASK,
- NEW_BALANCE,
- NEW_BLOCK,
- WORKER_NAME,
- SYNC_BLOCK,
- SYNCBLOCK_REQUEST
- });
-
- for (XdagVersion v : XdagVersion.values()) {
- Map map = Maps.newHashMap();
- intToTypeMap.put(v, map);
- for (XdagMessageCodes code : values(v)) {
- map.put(code.cmd, code);
- }
- }
- }
-
- private final int cmd;
-
- XdagMessageCodes(int cmd) {
- this.cmd = cmd;
- }
-
- public static XdagMessageCodes[] values(XdagVersion v) {
- return versionToValuesMap.get(v);
- }
-
- public static XdagMessageCodes fromByte(byte i, XdagVersion v) {
- Map map = intToTypeMap.get(v);
- return map.get((int) i);
- }
-
- public static boolean inRange(byte code, XdagVersion v) {
- XdagMessageCodes[] codes = values(v);
- return code >= codes[0].asByte() && code <= codes[codes.length - 1].asByte();
- }
-
- public byte asByte() {
- return (byte) (cmd);
- }
-}
diff --git a/src/main/java/io/xdag/net/handler/XdagHandlerFactory.java b/src/main/java/io/xdag/net/message/consensus/BlockExtReplyMessage.java
similarity index 79%
rename from src/main/java/io/xdag/net/handler/XdagHandlerFactory.java
rename to src/main/java/io/xdag/net/message/consensus/BlockExtReplyMessage.java
index 7d2fb8212..f7a2071ba 100644
--- a/src/main/java/io/xdag/net/handler/XdagHandlerFactory.java
+++ b/src/main/java/io/xdag/net/message/consensus/BlockExtReplyMessage.java
@@ -21,13 +21,16 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+package io.xdag.net.message.consensus;
-package io.xdag.net.handler;
+import io.xdag.net.message.Message;
+import io.xdag.net.message.MessageCode;
-import io.xdag.net.XdagVersion;
+public class BlockExtReplyMessage extends Message {
-public interface XdagHandlerFactory {
-
- XdagHandler create(XdagVersion version);
+ public BlockExtReplyMessage(byte[] body) {
+ super(MessageCode.BLOCKEXT_REPLY, null);
+ this.body = body;
+ }
}
diff --git a/src/main/java/io/xdag/config/PoolConfig.java b/src/main/java/io/xdag/net/message/consensus/BlockExtRequestMessage.java
similarity index 81%
rename from src/main/java/io/xdag/config/PoolConfig.java
rename to src/main/java/io/xdag/net/message/consensus/BlockExtRequestMessage.java
index 184a4d406..3f4dc14f0 100644
--- a/src/main/java/io/xdag/config/PoolConfig.java
+++ b/src/main/java/io/xdag/net/message/consensus/BlockExtRequestMessage.java
@@ -21,17 +21,12 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
-package io.xdag.config;
+package io.xdag.net.message.consensus;
+import io.xdag.net.message.MessageCode;
-import lombok.Builder;
-import lombok.Data;
-
-@Data
-@Builder
-public class PoolConfig {
- double poolRation;
- double minerRewardRation;
- double fundRation;
- double directRation;
+public class BlockExtRequestMessage extends XdagMessage {
+ public BlockExtRequestMessage(byte[] body) {
+ super(MessageCode.BLOCKEXT_REQUEST, BlocksReplyMessage.class, body);
+ }
}
diff --git a/src/main/java/io/xdag/net/message/consensus/BlockRequestMessage.java b/src/main/java/io/xdag/net/message/consensus/BlockRequestMessage.java
new file mode 100644
index 000000000..bbba6223e
--- /dev/null
+++ b/src/main/java/io/xdag/net/message/consensus/BlockRequestMessage.java
@@ -0,0 +1,44 @@
+/*
+ * 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.message.consensus;
+
+
+
+import org.apache.tuweni.bytes.Bytes32;
+import org.apache.tuweni.bytes.MutableBytes;
+
+import io.xdag.core.XdagStats;
+import io.xdag.net.NetDB;
+import io.xdag.net.message.MessageCode;
+
+public class BlockRequestMessage extends XdagMessage {
+
+ public BlockRequestMessage(MutableBytes hash, XdagStats xdagStats, NetDB localNetdb) {
+ super(MessageCode.BLOCK_REQUEST, null, 0, 0, Bytes32.wrap(hash), xdagStats, localNetdb);
+ }
+
+ public BlockRequestMessage(byte[] body) {
+ super(MessageCode.BLOCK_REQUEST, null, body);
+ }
+}
diff --git a/src/main/java/io/xdag/net/message/consensus/BlocksReplyMessage.java b/src/main/java/io/xdag/net/message/consensus/BlocksReplyMessage.java
new file mode 100644
index 000000000..a81f17bf2
--- /dev/null
+++ b/src/main/java/io/xdag/net/message/consensus/BlocksReplyMessage.java
@@ -0,0 +1,40 @@
+/*
+ * 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.message.consensus;
+
+import io.xdag.core.XdagStats;
+import io.xdag.net.NetDB;
+import io.xdag.net.message.MessageCode;
+
+public class BlocksReplyMessage extends XdagMessage {
+
+ public BlocksReplyMessage(long starttime, long endtime, long random, XdagStats xdagStats, NetDB localNetdb) {
+ super(MessageCode.BLOCKS_REPLY, null, starttime, endtime, random, xdagStats, localNetdb);
+ }
+
+ public BlocksReplyMessage(byte[] body) {
+ super(MessageCode.BLOCKS_REPLY, null, body);
+ }
+
+}
diff --git a/src/main/java/io/xdag/net/libp2p/peer/NodeId.java b/src/main/java/io/xdag/net/message/consensus/BlocksRequestMessage.java
similarity index 67%
rename from src/main/java/io/xdag/net/libp2p/peer/NodeId.java
rename to src/main/java/io/xdag/net/message/consensus/BlocksRequestMessage.java
index 25b02c08f..ac190956c 100644
--- a/src/main/java/io/xdag/net/libp2p/peer/NodeId.java
+++ b/src/main/java/io/xdag/net/message/consensus/BlocksRequestMessage.java
@@ -21,33 +21,20 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+package io.xdag.net.message.consensus;
-package io.xdag.net.libp2p.peer;
+import org.apache.commons.lang3.RandomUtils;
+import io.xdag.core.XdagStats;
+import io.xdag.net.NetDB;
+import io.xdag.net.message.MessageCode;
-import org.apache.tuweni.bytes.Bytes;
-
-public abstract class NodeId {
-
- public abstract Bytes toBytes();
-
- public abstract String toBase58();
-
- @Override
- public final int hashCode() {
- return toBytes().hashCode();
- }
-
- @Override
- public final boolean equals(final Object obj) {
- if (!(obj instanceof NodeId)) {
- return false;
- }
- return toBytes().equals(((NodeId) obj).toBytes());
+public class BlocksRequestMessage extends XdagMessage {
+ public BlocksRequestMessage(long starttime, long endtime, XdagStats xdagStats, NetDB localNetdb) {
+ super(MessageCode.BLOCKEXT_REQUEST, null, starttime, endtime, RandomUtils.nextLong(), xdagStats, localNetdb);
}
- @Override
- public final String toString() {
- return toBase58();
+ public BlocksRequestMessage(byte[] body) {
+ super(MessageCode.BLOCKEXT_REQUEST, null, body);
}
}
\ No newline at end of file
diff --git a/src/main/java/io/xdag/mine/message/NewTaskMessage.java b/src/main/java/io/xdag/net/message/consensus/NewBlockMessage.java
similarity index 52%
rename from src/main/java/io/xdag/mine/message/NewTaskMessage.java
rename to src/main/java/io/xdag/net/message/consensus/NewBlockMessage.java
index 427fa2458..f382d0ca0 100644
--- a/src/main/java/io/xdag/mine/message/NewTaskMessage.java
+++ b/src/main/java/io/xdag/net/message/consensus/NewBlockMessage.java
@@ -21,50 +21,58 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+package io.xdag.net.message.consensus;
-package io.xdag.mine.message;
+import static io.xdag.config.Constants.DNET_PKT_XDAG;
-import static io.xdag.net.message.XdagMessageCodes.NEW_TASK;
+import org.apache.tuweni.bytes.Bytes;
+import org.apache.tuweni.bytes.MutableBytes;
-import io.xdag.core.XdagField;
+import io.xdag.core.Block;
+import io.xdag.core.SimpleEncoder;
+import io.xdag.core.XdagBlock;
import io.xdag.net.message.Message;
-import io.xdag.net.message.XdagMessageCodes;
+import io.xdag.net.message.MessageCode;
+import io.xdag.utils.BytesUtils;
+import io.xdag.utils.SimpleDecoder;
+import lombok.Getter;
+import lombok.Setter;
-import org.apache.commons.lang3.builder.ToStringBuilder;
-import org.apache.commons.lang3.builder.ToStringStyle;
-import org.apache.tuweni.bytes.Bytes;
-import org.apache.tuweni.bytes.MutableBytes;
+@Getter
+@Setter
+public class NewBlockMessage extends Message {
-public class NewTaskMessage extends Message {
+ private XdagBlock xdagBlock;
+ private Block block;
+ private int ttl;
- private final XdagField[] xdagFields = new XdagField[2];
+ public NewBlockMessage(byte[] body) {
+ super(MessageCode.NEW_BLOCK, null);
- public NewTaskMessage(MutableBytes bytes) {
- super(bytes);
- xdagFields[0] = new XdagField(bytes.mutableSlice(0, 32));
- xdagFields[1] = new XdagField(bytes.mutableSlice(32, 32));
- }
+ SimpleDecoder dec = new SimpleDecoder(body);
- @Override
- public Bytes getEncoded() {
- MutableBytes data = MutableBytes.create(64);
- data.set(0, xdagFields[0].getData());
- data.set(32, xdagFields[1].getData());
- return data;
+ this.body = dec.readBytes();
+ this.xdagBlock = new XdagBlock(this.body);
+ this.block = new Block(this.xdagBlock);
+ this.ttl = dec.readInt();
}
- @Override
- public Class> getAnswerMessage() {
- return null;
- }
+ public NewBlockMessage(Block block, int ttl) {
+ super(MessageCode.NEW_BLOCK, null);
+
+ this.block = block;
+ this.ttl = ttl;
- @Override
- public XdagMessageCodes getCommand() {
- return NEW_TASK;
+ SimpleEncoder enc = encode();
+ this.body = enc.toBytes();
}
- @Override
- public String toString() {
- return new ToStringBuilder(this, ToStringStyle.JSON_STYLE).toString();
+ private SimpleEncoder encode() {
+ SimpleEncoder enc = new SimpleEncoder();
+ enc.writeBytes(this.block.toBytes());
+ enc.writeInt(ttl);
+ return enc;
}
+
+
}
diff --git a/src/main/java/io/xdag/mine/message/WorkerNameMessage.java b/src/main/java/io/xdag/net/message/consensus/SumReplyMessage.java
similarity index 54%
rename from src/main/java/io/xdag/mine/message/WorkerNameMessage.java
rename to src/main/java/io/xdag/net/message/consensus/SumReplyMessage.java
index 97dceb537..2ae5ea80b 100644
--- a/src/main/java/io/xdag/mine/message/WorkerNameMessage.java
+++ b/src/main/java/io/xdag/net/message/consensus/SumReplyMessage.java
@@ -21,45 +21,46 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
-package io.xdag.mine.message;
+package io.xdag.net.message.consensus;
-import static io.xdag.net.message.XdagMessageCodes.WORKER_NAME;
+import java.math.BigInteger;
-import io.xdag.core.XdagField;
-import io.xdag.net.message.Message;
-import io.xdag.net.message.XdagMessageCodes;
-
-import org.apache.commons.lang3.builder.ToStringBuilder;
-import org.apache.commons.lang3.builder.ToStringStyle;
-import org.apache.tuweni.bytes.Bytes;
+import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.bytes.MutableBytes;
-public class WorkerNameMessage extends Message {
+import io.xdag.core.SimpleEncoder;
+import io.xdag.core.XdagStats;
+import io.xdag.net.NetDB;
+import io.xdag.net.message.MessageCode;
+import io.xdag.utils.BytesUtils;
+import io.xdag.utils.Numeric;
+import io.xdag.utils.SimpleDecoder;
+import lombok.Getter;
+import lombok.Setter;
- private final XdagField xdagField;
+@Getter
+@Setter
+public class SumReplyMessage extends XdagMessage {
- public WorkerNameMessage(MutableBytes encoded) {
- super(encoded);
- this.xdagField = new XdagField(encoded);
- }
+ MutableBytes sum;
- @Override
- public Bytes getEncoded() {
- return xdagField.getData();
+ public SumReplyMessage(long endtime, long random, XdagStats xdagStats, MutableBytes sum, NetDB localNetdb) {
+ super(MessageCode.SUMS_REPLY, null, 1, endtime, random, xdagStats, localNetdb);
+ this.sum = sum;
}
- @Override
- public Class> getAnswerMessage() {
- return null;
- }
+ public SumReplyMessage(byte[] body) {
+ super(MessageCode.SUMS_REPLY, null, body);
- @Override
- public XdagMessageCodes getCommand() {
- return WORKER_NAME;
+ SimpleDecoder dec = super.decode();
+ this.sum = MutableBytes.wrap(dec.readBytes());
}
@Override
- public String toString() {
- return new ToStringBuilder(this, ToStringStyle.JSON_STYLE).toString();
+ 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
new file mode 100644
index 000000000..1b42fda10
--- /dev/null
+++ b/src/main/java/io/xdag/net/message/consensus/SumRequestMessage.java
@@ -0,0 +1,40 @@
+/*
+ * 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.message.consensus;
+
+import org.apache.commons.lang3.RandomUtils;
+
+import io.xdag.core.XdagStats;
+import io.xdag.net.NetDB;
+import io.xdag.net.message.MessageCode;
+
+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);
+ }
+
+ public SumRequestMessage(byte[] body) {
+ super(MessageCode.SUMS_REQUEST, SumReplyMessage.class, body);
+ }
+}
diff --git a/src/main/java/io/xdag/net/message/consensus/SyncBlockMessage.java b/src/main/java/io/xdag/net/message/consensus/SyncBlockMessage.java
new file mode 100644
index 000000000..bd75c9e26
--- /dev/null
+++ b/src/main/java/io/xdag/net/message/consensus/SyncBlockMessage.java
@@ -0,0 +1,77 @@
+/*
+ * 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.message.consensus;
+
+import static io.xdag.config.Constants.DNET_PKT_XDAG;
+
+import org.apache.tuweni.bytes.Bytes;
+import org.apache.tuweni.bytes.MutableBytes;
+
+import io.xdag.core.Block;
+import io.xdag.core.SimpleEncoder;
+import io.xdag.core.XdagBlock;
+import io.xdag.net.message.Message;
+import io.xdag.net.message.MessageCode;
+import io.xdag.utils.BytesUtils;
+import io.xdag.utils.SimpleDecoder;
+import lombok.Getter;
+import lombok.Setter;
+
+@Getter
+@Setter
+public class SyncBlockMessage extends Message {
+
+ private XdagBlock xdagBlock;
+ private Block block;
+ private int ttl;
+
+ public SyncBlockMessage(byte[] body) {
+ super(MessageCode.SYNC_BLOCK, null);
+
+ SimpleDecoder dec = new SimpleDecoder(body);
+
+ this.body = dec.readBytes();
+ this.xdagBlock = new XdagBlock(this.body);
+ this.block = new Block(this.xdagBlock);
+ this.ttl = dec.readInt();
+ }
+
+ public SyncBlockMessage(Block block, int ttl) {
+ super(MessageCode.SYNC_BLOCK, null);
+
+ this.block = block;
+ this.ttl = ttl;
+
+ SimpleEncoder enc = encode();
+ this.body = enc.toBytes();
+ }
+
+ private SimpleEncoder encode() {
+ SimpleEncoder enc = new SimpleEncoder();
+ enc.writeBytes(this.block.toBytes());
+ enc.writeInt(ttl);
+ return enc;
+ }
+
+}
diff --git a/src/main/java/io/xdag/mine/manager/AwardManager.java b/src/main/java/io/xdag/net/message/consensus/SyncBlockRequestMessage.java
similarity index 72%
rename from src/main/java/io/xdag/mine/manager/AwardManager.java
rename to src/main/java/io/xdag/net/message/consensus/SyncBlockRequestMessage.java
index 01e6a81c7..9d02d3436 100644
--- a/src/main/java/io/xdag/mine/manager/AwardManager.java
+++ b/src/main/java/io/xdag/net/message/consensus/SyncBlockRequestMessage.java
@@ -21,24 +21,19 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+package io.xdag.net.message.consensus;
-package io.xdag.mine.manager;
-
-import io.xdag.config.PoolConfig;
-import io.xdag.consensus.Task;
import org.apache.tuweni.bytes.Bytes32;
+import org.apache.tuweni.bytes.MutableBytes;
-public interface AwardManager {
-
- void onNewTask(Task task);
-
- void start();
-
- void stop();
+import io.xdag.core.XdagStats;
+import io.xdag.net.NetDB;
+import io.xdag.net.message.MessageCode;
- void addAwardBlock(Bytes32 share, Bytes32 hash, long generateTime);
+public class SyncBlockRequestMessage extends XdagMessage {
- void updatePoolConfig(double poolFeeRation,double poolRewardRation,double poolDirectRation, double poolFundRation);
+ public SyncBlockRequestMessage(MutableBytes hash, XdagStats xdagStats, NetDB localNetdb) {
+ super(MessageCode.SYNCBLOCK_REQUEST, SyncBlockMessage.class, 0, 0, Bytes32.wrap(hash), xdagStats, localNetdb);
+ }
- PoolConfig getPoolConfig();
}
diff --git a/src/main/java/io/xdag/net/message/consensus/XdagMessage.java b/src/main/java/io/xdag/net/message/consensus/XdagMessage.java
new file mode 100644
index 000000000..d783ed120
--- /dev/null
+++ b/src/main/java/io/xdag/net/message/consensus/XdagMessage.java
@@ -0,0 +1,134 @@
+/*
+ * 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.message.consensus;
+
+import java.math.BigInteger;
+
+import org.apache.tuweni.bytes.Bytes;
+import org.apache.tuweni.bytes.Bytes32;
+
+import io.xdag.core.SimpleEncoder;
+import io.xdag.core.XdagStats;
+import io.xdag.net.NetDB;
+import io.xdag.net.message.Message;
+import io.xdag.net.message.MessageCode;
+import io.xdag.utils.BytesUtils;
+import io.xdag.utils.Numeric;
+import io.xdag.utils.SimpleDecoder;
+import lombok.Getter;
+import lombok.Setter;
+
+@Getter
+@Setter
+public abstract class XdagMessage extends Message {
+
+ protected long starttime;
+
+ protected long endtime;
+
+ protected long random;
+
+ protected Bytes32 hash;
+
+ protected XdagStats xdagStats;
+
+ protected NetDB remoteNetdb;
+
+ protected NetDB localNetdb;
+
+ public XdagMessage(MessageCode code, Class> responseMessageClass, byte[] body) {
+ super(code, responseMessageClass);
+ this.body = body;
+ decode();
+ }
+
+ public XdagMessage(MessageCode code, Class> responseMessageClass, long starttime, long endtime, long random, XdagStats xdagStats, NetDB localNetdb) {
+ super(code, responseMessageClass);
+
+ this.starttime = starttime;
+ this.endtime = endtime;
+ this.random = random;
+ this.xdagStats = xdagStats;
+ this.localNetdb = localNetdb;
+
+ this.hash = Bytes32.ZERO;
+ SimpleEncoder enc = encode();
+ this.body = enc.toBytes();
+ }
+
+ public XdagMessage(MessageCode code, Class> responseMessageClass, long starttime, long endtime, Bytes32 hash, XdagStats xdagStats,
+ NetDB localNetdb) {
+ super(code, responseMessageClass);
+
+ this.starttime = starttime;
+ this.endtime = endtime;
+ this.hash = hash;
+ this.xdagStats = xdagStats;
+ this.localNetdb = localNetdb;
+
+ SimpleEncoder enc = encode();
+ this.body = enc.toBytes();
+ }
+
+ protected SimpleEncoder encode() {
+ SimpleEncoder enc = new SimpleEncoder();
+
+ enc.writeLong(starttime);
+ enc.writeLong(endtime);
+ enc.writeLong(random);
+ enc.writeBytes(hash.toArray());
+
+ enc.writeBytes(BytesUtils.bigIntegerToBytes(xdagStats.maxdifficulty, 16, false));
+
+ enc.writeLong(xdagStats.totalnblocks);
+ enc.writeLong(xdagStats.totalnmain);
+ enc.writeInt(xdagStats.totalnhosts);
+ enc.writeLong(xdagStats.maintime);
+
+ enc.writeBytes(localNetdb.getEncoded());
+ return enc;
+ }
+
+ protected SimpleDecoder decode() {
+ SimpleDecoder dec = new SimpleDecoder(this.body);
+
+ this.starttime = dec.readLong();
+ this.endtime = dec.readLong();
+ this.random = dec.readLong();
+ this.hash = Bytes32.wrap(dec.readBytes());
+
+ BigInteger maxdifficulty = Numeric.toBigInt(dec.readBytes());
+ long totalnblocks = dec.readLong();
+ long totalnmains = dec.readLong();
+ int totalnhosts = dec.readInt();
+ long maintime = dec.readLong();
+
+ xdagStats = new XdagStats(maxdifficulty, totalnblocks, totalnmains, totalnhosts, maintime);
+
+ byte[] netdb = dec.readBytes();
+ localNetdb = new NetDB(netdb);
+ return dec;
+ }
+
+}
diff --git a/src/main/java/io/xdag/net/message/impl/BlockExtRequestMessage.java b/src/main/java/io/xdag/net/message/impl/BlockExtRequestMessage.java
deleted file mode 100644
index 64520d41a..000000000
--- a/src/main/java/io/xdag/net/message/impl/BlockExtRequestMessage.java
+++ /dev/null
@@ -1,63 +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.message.impl;
-
-import io.xdag.net.message.Message;
-import io.xdag.net.message.XdagMessageCodes;
-
-import org.apache.commons.lang3.builder.ToStringBuilder;
-import org.apache.commons.lang3.builder.ToStringStyle;
-import org.apache.tuweni.bytes.Bytes;
-import org.apache.tuweni.bytes.MutableBytes;
-
-public class BlockExtRequestMessage extends Message {
-
- public BlockExtRequestMessage(MutableBytes bytes) {
- super(bytes);
- // TODO Auto-generated constructor stub
- }
-
- @Override
- public Class> getAnswerMessage() {
- // TODO Auto-generated method stub
- return BlocksReplyMessage.class;
- }
-
- @Override
- public Bytes getEncoded() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this, ToStringStyle.JSON_STYLE).toString();
- }
-
- @Override
- public XdagMessageCodes getCommand() {
- return XdagMessageCodes.BLOCKEXT_REQUEST;
- }
-}
diff --git a/src/main/java/io/xdag/net/message/impl/BlockRequestMessage.java b/src/main/java/io/xdag/net/message/impl/BlockRequestMessage.java
deleted file mode 100644
index 672f63972..000000000
--- a/src/main/java/io/xdag/net/message/impl/BlockRequestMessage.java
+++ /dev/null
@@ -1,158 +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.message.impl;
-
-import static io.xdag.config.Constants.DNET_PKT_XDAG;
-import static io.xdag.core.XdagBlock.XDAG_BLOCK_SIZE;
-import static io.xdag.core.XdagField.FieldType.XDAG_FIELD_NONCE;
-
-import io.xdag.core.XdagStats;
-import io.xdag.net.message.AbstractMessage;
-import io.xdag.net.message.NetDB;
-import io.xdag.net.message.XdagMessageCodes;
-import io.xdag.utils.BytesUtils;
-import java.math.BigInteger;
-import java.nio.ByteOrder;
-import lombok.EqualsAndHashCode;
-import org.apache.tuweni.bytes.Bytes;
-import org.apache.tuweni.bytes.Bytes32;
-import org.apache.tuweni.bytes.MutableBytes;
-import org.apache.tuweni.bytes.MutableBytes32;
-
-@EqualsAndHashCode(callSuper = false)
-public class BlockRequestMessage extends AbstractMessage {
-
- public BlockRequestMessage(MutableBytes hash, XdagStats xdagStats, NetDB currentDB) {
- super(XdagMessageCodes.BLOCK_REQUEST, 0, 0, Bytes32.wrap(hash), xdagStats, currentDB);
- }
-
- public BlockRequestMessage(MutableBytes hash) {
- super(hash);
- }
-
- @Override
- public Class> getAnswerMessage() {
- return null;
- }
-
- @Override
- public Bytes getEncoded() {
- // TODO Auto-generated method stub
- return encoded;
- }
-
- @Override
- public String toString() {
- if (!parsed) {
- parse();
- }
- return "["
- + this.getCommand().name()
- + " starttime="
- + starttime
- + " endtime="
- + this.endtime
- + " hash="
- + hash.toHexString()
- + " netstatus="
- + xdagStats;
- }
-
- @Override
- public XdagMessageCodes getCommand() {
- return XdagMessageCodes.BLOCK_REQUEST;
- }
-
- @Override
- public void encode() {
- parsed = true;
- encoded = MutableBytes.create(512);
- int ttl = 1;
- long transportheader = (ttl << 8) | DNET_PKT_XDAG | (XDAG_BLOCK_SIZE << 16);
- long type = (codes.asByte() << 4) | XDAG_FIELD_NONCE.asByte();
-
- BigInteger diff = xdagStats.getDifficulty();
- BigInteger maxDiff = xdagStats.getMaxdifficulty();
- long nmain = xdagStats.getNmain();
- long totalMainNumber = Math.max(xdagStats.getTotalnmain(), nmain);
- long nblocks = xdagStats.getNblocks();
- long totalBlockNumber = xdagStats.getTotalnblocks();
-
- MutableBytes mutableBytes = MutableBytes.create(112);
- long nhosts = currentDB.getIpList().size();
- long totalHosts = currentDB.getIpList().size();
-
- mutableBytes.set(0, Bytes.wrap(BytesUtils.longToBytes(nhosts, true)));
- mutableBytes.set(8, Bytes.wrap(BytesUtils.longToBytes(totalHosts, true)));
- mutableBytes.set(16, Bytes.wrap(currentDB.getEncoded()));
-
-// // TODO:后续根据ip替换
-// String tmp = "04000000040000003ef4780100000000" + "7f000001611e7f000001b8227f0000015f767f000001d49d";
-// // net 相关
-// byte[] tmpbyte = Hex.decode(tmp);
-
- // field 0 and field1
- MutableBytes32 first = MutableBytes32.create();
- first.set(0, Bytes.wrap(BytesUtils.longToBytes(transportheader, true)));
- first.set(8, Bytes.wrap(BytesUtils.longToBytes(type, true)));
- first.set(16, Bytes.wrap(BytesUtils.longToBytes(starttime, true)));
- first.set(24, Bytes.wrap(BytesUtils.longToBytes(endtime, true)));
-
- encoded.set(0, first);
- encoded.set(32, hash.reverse());
-
- // field2 diff and maxdiff
- encoded.set(64, Bytes.wrap(BytesUtils.bigIntegerToBytes(diff, 16, true)));
- encoded.set(80, Bytes.wrap(BytesUtils.bigIntegerToBytes(maxDiff, 16, true)));
-
- // field3 nblock totalblock main totalmain
- encoded.set(96, Bytes.wrap(BytesUtils.longToBytes(nblocks, true)));
- encoded.set(104, Bytes.wrap(BytesUtils.longToBytes(totalBlockNumber, true)));
- encoded.set(112, Bytes.wrap(BytesUtils.longToBytes(nmain, true)));
- encoded.set(120, Bytes.wrap(BytesUtils.longToBytes(totalMainNumber, true)));
- encoded.set(128, Bytes.wrap(mutableBytes));
- updateCrc();
- }
-
- @Override
- public void parse() {
- if (parsed) {
- return;
- }
-
- this.starttime = encoded.getLong(16, ByteOrder.LITTLE_ENDIAN);
- this.endtime = encoded.getLong(24, ByteOrder.LITTLE_ENDIAN);
- BigInteger maxdifficulty = encoded.slice(80, 16).toUnsignedBigInteger(ByteOrder.LITTLE_ENDIAN);
- long totalnblocks = encoded.getLong(104, ByteOrder.LITTLE_ENDIAN);
- long totalnmains = encoded.getLong(120, ByteOrder.LITTLE_ENDIAN);
- int totalnhosts = encoded.getInt(132, ByteOrder.LITTLE_ENDIAN);
- long maintime = encoded.getLong(136, ByteOrder.LITTLE_ENDIAN);
- xdagStats = new XdagStats(maxdifficulty, totalnblocks, totalnmains, totalnhosts, maintime);
- MutableBytes32 hash = MutableBytes32.create();
- hash.set(0, encoded.slice(32, 24));
- this.hash = hash.copy();
- parsed = true;
- }
-}
diff --git a/src/main/java/io/xdag/net/message/impl/BlocksReplyMessage.java b/src/main/java/io/xdag/net/message/impl/BlocksReplyMessage.java
deleted file mode 100644
index 3040c20c1..000000000
--- a/src/main/java/io/xdag/net/message/impl/BlocksReplyMessage.java
+++ /dev/null
@@ -1,78 +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.message.impl;
-
-import static io.xdag.net.message.XdagMessageCodes.BLOCKS_REPLY;
-
-import io.xdag.core.XdagStats;
-import io.xdag.net.message.AbstractMessage;
-import io.xdag.net.message.NetDB;
-import io.xdag.net.message.XdagMessageCodes;
-import lombok.EqualsAndHashCode;
-import org.apache.tuweni.bytes.Bytes;
-import org.apache.tuweni.bytes.MutableBytes;
-
-@EqualsAndHashCode(callSuper = false)
-public class BlocksReplyMessage extends AbstractMessage {
-
- public BlocksReplyMessage(long starttime, long endtime, long random, XdagStats xdagStats, NetDB currentDB) {
- super(BLOCKS_REPLY, starttime, endtime, random, xdagStats, currentDB);
- updateCrc();
- }
-
- public BlocksReplyMessage(MutableBytes encoded) {
- super(encoded);
- }
-
- @Override
- public Bytes getEncoded() {
- return encoded;
- }
-
- @Override
- public Class> getAnswerMessage() {
- return null;
- }
-
- @Override
- public XdagMessageCodes getCommand() {
- return XdagMessageCodes.BLOCKS_REPLY;
- }
-
- @Override
- public String toString() {
- if (!parsed) {
- parse();
- }
- return "["
- + this.getCommand().name()
- + " starttime="
- + getStarttime()
- + " endtime="
- + getEndtime()
- + " netstatus"
- + getXdagStats();
- }
-}
diff --git a/src/main/java/io/xdag/net/message/impl/BlocksRequestMessage.java b/src/main/java/io/xdag/net/message/impl/BlocksRequestMessage.java
deleted file mode 100644
index 893dd4c05..000000000
--- a/src/main/java/io/xdag/net/message/impl/BlocksRequestMessage.java
+++ /dev/null
@@ -1,81 +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.message.impl;
-
-import static io.xdag.net.message.XdagMessageCodes.BLOCKS_REQUEST;
-
-import io.xdag.core.XdagStats;
-import io.xdag.net.message.AbstractMessage;
-import io.xdag.net.message.NetDB;
-import io.xdag.net.message.XdagMessageCodes;
-import lombok.EqualsAndHashCode;
-import org.apache.commons.lang3.RandomUtils;
-import org.apache.tuweni.bytes.Bytes;
-import org.apache.tuweni.bytes.MutableBytes;
-
-@EqualsAndHashCode(callSuper = false)
-public class BlocksRequestMessage extends AbstractMessage {
-
- public BlocksRequestMessage(MutableBytes bytes) {
- super(bytes);
- }
-
- public BlocksRequestMessage(long starttime, long endtime, XdagStats xdagStats, NetDB currentDB) {
- super(BLOCKS_REQUEST, starttime, endtime, RandomUtils.nextLong(), xdagStats, currentDB);
- updateCrc();
- }
-
- @Override
- public Bytes getEncoded() {
- if (encoded == null) {
- encode();
- }
- return encoded;
- }
-
- @Override
- public Class getAnswerMessage() {
- return BlocksReplyMessage.class;
- }
-
- @Override
- public XdagMessageCodes getCommand() {
- return XdagMessageCodes.BLOCKS_REQUEST;
- }
-
- @Override
- public String toString() {
- if (!parsed) {
- parse();
- }
- return "["
- + this.getCommand().name()
- + " starttime="
- + this.starttime
- + " endtime="
- + this.endtime
- + "]";
- }
-}
diff --git a/src/main/java/io/xdag/net/message/impl/NewBlockMessage.java b/src/main/java/io/xdag/net/message/impl/NewBlockMessage.java
deleted file mode 100644
index 41c7708ff..000000000
--- a/src/main/java/io/xdag/net/message/impl/NewBlockMessage.java
+++ /dev/null
@@ -1,123 +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.message.impl;
-
-import static io.xdag.config.Constants.DNET_PKT_XDAG;
-
-import io.xdag.core.Block;
-import io.xdag.core.XdagBlock;
-import io.xdag.net.message.Message;
-import io.xdag.net.message.XdagMessageCodes;
-import io.xdag.utils.BytesUtils;
-import java.util.zip.CRC32;
-import org.apache.tuweni.bytes.Bytes;
-import org.apache.tuweni.bytes.MutableBytes;
-
-public class NewBlockMessage extends Message {
-
- private XdagBlock xdagBlock;
- private Block block;
- private int ttl;
-
- /**
- * 不处理crc
- */
- public NewBlockMessage(MutableBytes bytes) {
- super(bytes);
- }
-
- /**
- * 处理crc 创建新的用于发送Block的message
- */
- public NewBlockMessage(Block block, int ttl) {
- this.block = block;
- this.ttl = ttl;
- this.parsed = true;
- encode();
- }
-
- /**
- * 不处理crc
- */
- public NewBlockMessage(XdagBlock xdagBlock, int ttl) {
- super(xdagBlock.getData().mutableCopy());
- this.xdagBlock = xdagBlock;
- this.ttl = ttl;
- }
-
- public Block getBlock() {
- parse();
- return block;
- }
-
- private void parse() {
- if (parsed) {
- return;
- }
- block = new Block(xdagBlock);
- parsed = true;
- }
-
- private void encode() {
- this.encoded = this.block.getXdagBlock().getData().mutableCopy();
- long transportheader = ((long) ttl << 8) | DNET_PKT_XDAG | (512 << 16);
- this.encoded.set(0, Bytes.wrap(BytesUtils.longToBytes(transportheader, true)));
- updateCrc();
- }
-
- public void updateCrc() {
- CRC32 crc32 = new CRC32();
- crc32.update(encoded.toArray(), 0, 512);
- this.encoded.set(4, Bytes.wrap(BytesUtils.intToBytes((int) crc32.getValue(), true)));
- }
-
- public int getTtl() {
- return ttl;
- }
-
- public void setTtl(int ttl) {
- this.ttl = ttl;
- }
-
- @Override
- public Bytes getEncoded() {
- return encoded;
- }
-
- @Override
- public Class> getAnswerMessage() {
- return null;
- }
-
- @Override
- public XdagMessageCodes getCommand() {
- return XdagMessageCodes.NEW_BLOCK;
- }
-
- @Override
- public String toString() {
- return "NewBlock Message:" + encoded.toHexString();
- }
-}
diff --git a/src/main/java/io/xdag/net/message/impl/SumReplyMessage.java b/src/main/java/io/xdag/net/message/impl/SumReplyMessage.java
deleted file mode 100644
index 33df5b9f4..000000000
--- a/src/main/java/io/xdag/net/message/impl/SumReplyMessage.java
+++ /dev/null
@@ -1,116 +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.message.impl;
-
-import static io.xdag.net.message.XdagMessageCodes.SUMS_REPLY;
-
-import io.xdag.core.XdagStats;
-import io.xdag.net.message.AbstractMessage;
-import io.xdag.net.message.NetDB;
-import io.xdag.net.message.XdagMessageCodes;
-import io.xdag.utils.BytesUtils;
-import java.math.BigInteger;
-import java.nio.ByteOrder;
-import org.apache.tuweni.bytes.Bytes;
-import org.apache.tuweni.bytes.MutableBytes;
-
-public class SumReplyMessage extends AbstractMessage {
-
- MutableBytes sums;
-
- public SumReplyMessage(long endtime, long random, XdagStats xdagStats, MutableBytes sums, NetDB currentDB) {
- super(SUMS_REPLY, 1, endtime, random, xdagStats, currentDB);
- this.sums = sums;
- encoded.set(32, Bytes.wrap(BytesUtils.longToBytes(random, true)));
- encoded.set(256, Bytes.wrap(sums));
- updateCrc();
- }
-
- public SumReplyMessage(MutableBytes encoded) {
- super(encoded);
- }
-
- @Override
- public Bytes getEncoded() {
- return encoded;
- }
-
- @Override
- public Class> getAnswerMessage() {
- return null;
- }
-
- @Override
- public XdagMessageCodes getCommand() {
- return XdagMessageCodes.SUMS_REPLY;
- }
-
- @Override
- public String toString() {
- if (!parsed) {
- parse();
- }
- return "["
- + this.getCommand().name()
- + " starttime="
- + starttime
- + " endtime="
- + this.endtime
- + " netstatus="
- + xdagStats;
- }
-
- public Bytes getSum() {
- parse();
- return sums;
- }
-
- @Override
- public void parse() {
- if (parsed) {
- return;
- }
-
- this.starttime = encoded.getLong(16, ByteOrder.LITTLE_ENDIAN);
- this.endtime = encoded.getLong(24, ByteOrder.LITTLE_ENDIAN);
- this.random = encoded.getLong(32, ByteOrder.LITTLE_ENDIAN);
- BigInteger maxdifficulty = encoded.slice(80, 16).toUnsignedBigInteger(ByteOrder.LITTLE_ENDIAN);
- long totalnblocks = encoded.getLong(104, ByteOrder.LITTLE_ENDIAN);
- long totalnmains = encoded.getLong(120, ByteOrder.LITTLE_ENDIAN);
- int totalnhosts = encoded.getInt(132, ByteOrder.LITTLE_ENDIAN);
- long maintime = encoded.getLong(136, ByteOrder.LITTLE_ENDIAN);
- xdagStats = new XdagStats(maxdifficulty, totalnblocks, totalnmains, totalnhosts, maintime);
-
- // test netdb
- int length = 6;
- // 80 是sizeof(xdag_stats)
- MutableBytes netdb = MutableBytes.create(length * 32 - 80);
- netdb.set(0, encoded.slice(144, length * 32 - 80));
- netDB = new NetDB(netdb.toArray());
- sums = MutableBytes.create(256);
- sums.set(0, encoded.slice(256, 256));
- parsed = true;
- }
-}
diff --git a/src/main/java/io/xdag/net/message/impl/SumRequestMessage.java b/src/main/java/io/xdag/net/message/impl/SumRequestMessage.java
deleted file mode 100644
index e805052d4..000000000
--- a/src/main/java/io/xdag/net/message/impl/SumRequestMessage.java
+++ /dev/null
@@ -1,79 +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.message.impl;
-
-import static io.xdag.net.message.XdagMessageCodes.SUMS_REQUEST;
-
-import io.xdag.core.XdagStats;
-import io.xdag.net.message.AbstractMessage;
-import io.xdag.net.message.NetDB;
-import io.xdag.net.message.XdagMessageCodes;
-import lombok.EqualsAndHashCode;
-import org.apache.commons.lang3.RandomUtils;
-import org.apache.tuweni.bytes.Bytes;
-import org.apache.tuweni.bytes.MutableBytes;
-
-@EqualsAndHashCode(callSuper = false)
-public class SumRequestMessage extends AbstractMessage {
-
- public SumRequestMessage(long starttime, long endtime, XdagStats xdagStats, NetDB currentDB) {
- super(SUMS_REQUEST, starttime, endtime, RandomUtils.nextLong(), xdagStats, currentDB);
- updateCrc();
- }
-
- public SumRequestMessage(MutableBytes bytes) {
- super(bytes);
- }
-
- @Override
- public Bytes getEncoded() {
- return encoded;
- }
-
- @Override
- public Class> getAnswerMessage() {
- return SumReplyMessage.class;
- }
-
- @Override
- public XdagMessageCodes getCommand() {
- return XdagMessageCodes.SUMS_REQUEST;
- }
-
- @Override
- public String toString() {
- if (!parsed) {
- parse();
- }
- return "["
- + this.getCommand().name()
- + " starttime="
- + starttime
- + " endtime="
- + this.endtime
- + " netstatus="
- + xdagStats;
- }
-}
diff --git a/src/main/java/io/xdag/net/message/impl/SyncBlockMessage.java b/src/main/java/io/xdag/net/message/impl/SyncBlockMessage.java
deleted file mode 100644
index 0fdde1939..000000000
--- a/src/main/java/io/xdag/net/message/impl/SyncBlockMessage.java
+++ /dev/null
@@ -1,126 +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.message.impl;
-
-import io.xdag.core.Block;
-import io.xdag.core.XdagBlock;
-import static io.xdag.config.Constants.DNET_PKT_XDAG;
-import io.xdag.net.message.Message;
-import io.xdag.net.message.XdagMessageCodes;
-import io.xdag.utils.BytesUtils;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.tuweni.bytes.Bytes;
-import org.apache.tuweni.bytes.MutableBytes;
-
-import java.util.zip.CRC32;
-
-@Slf4j
-public class SyncBlockMessage extends Message {
- private XdagBlock xdagBlock;
- private Block block;
- private int ttl;
-
-
- /**
- * 不处理crc
- */
- public SyncBlockMessage(MutableBytes bytes) {
- super(bytes);
- }
-
- /**
- * 处理crc 创建新的用于发送Block的message
- */
- public SyncBlockMessage(Block block, int ttl) {
- this.block = block;
- this.ttl = ttl;
- this.parsed = true;
- encode();
- }
-
- /**
- * 不处理crc
- */
- public SyncBlockMessage(XdagBlock xdagBlock, int ttl) {
- super(xdagBlock.getData().mutableCopy());
- this.xdagBlock = xdagBlock;
- this.ttl = ttl;
- }
-
- public Block getBlock() {
- parse();
- return block;
- }
-
- private void parse() {
- if (parsed) {
- return;
- }
- block = new Block(xdagBlock);
- parsed = true;
- }
-
- private void encode() {
- this.encoded = this.block.getXdagBlock().getData().mutableCopy();
- // (1L << 31):Used to distinguish between newBlockMessage and syncBlockMessage.
- long transportheader = ((long) ttl << 8) | DNET_PKT_XDAG | (512 << 16) | (1L << 31);
- this.encoded.set(0, Bytes.wrap(BytesUtils.longToBytes(transportheader, true)));
-
- updateCrc();
- }
-
- public void updateCrc() {
- CRC32 crc32 = new CRC32();
- crc32.update(encoded.toArray(), 0, 512);
- this.encoded.set(4, Bytes.wrap(BytesUtils.intToBytes((int) crc32.getValue(), true)));
- }
-
- public int getTtl() {
- return ttl;
- }
-
- public void setTtl(int ttl) {
- this.ttl = ttl;
- }
-
- @Override
- public Bytes getEncoded() {
- return encoded;
- }
-
- @Override
- public Class> getAnswerMessage() {
- return null;
- }
-
- @Override
- public XdagMessageCodes getCommand() {
- return XdagMessageCodes.SYNC_BLOCK;
- }
-
- @Override
- public String toString() {
- return "NewBlock Message:" + encoded.toHexString();
- }
-}
diff --git a/src/main/java/io/xdag/net/message/impl/SyncBlockRequestMessage.java b/src/main/java/io/xdag/net/message/impl/SyncBlockRequestMessage.java
deleted file mode 100644
index 938b49424..000000000
--- a/src/main/java/io/xdag/net/message/impl/SyncBlockRequestMessage.java
+++ /dev/null
@@ -1,155 +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.message.impl;
-
-import io.xdag.core.XdagStats;
-import io.xdag.net.message.AbstractMessage;
-import io.xdag.net.message.NetDB;
-import io.xdag.net.message.XdagMessageCodes;
-import io.xdag.utils.BytesUtils;
-import org.apache.tuweni.bytes.Bytes;
-import org.apache.tuweni.bytes.Bytes32;
-import org.apache.tuweni.bytes.MutableBytes;
-import org.apache.tuweni.bytes.MutableBytes32;
-
-import java.math.BigInteger;
-import java.nio.ByteOrder;
-
-import static io.xdag.config.Constants.DNET_PKT_XDAG;
-import static io.xdag.core.XdagBlock.XDAG_BLOCK_SIZE;
-import static io.xdag.core.XdagField.FieldType.XDAG_FIELD_NONCE;
-
-public class SyncBlockRequestMessage extends AbstractMessage {
- public SyncBlockRequestMessage(MutableBytes hash, XdagStats xdagStats, NetDB currentDB) {
- super(XdagMessageCodes.SYNCBLOCK_REQUEST, 0, 0, Bytes32.wrap(hash), xdagStats,currentDB);
- }
-
- public SyncBlockRequestMessage(MutableBytes hash) {
- super(hash);
- }
-
- @Override
- public Class> getAnswerMessage() {
- return null;
- }
-
- @Override
- public Bytes getEncoded() {
- // TODO Auto-generated method stub
- return encoded;
- }
-
- @Override
- public String toString() {
- if (!parsed) {
- parse();
- }
- return "["
- + this.getCommand().name()
- + " starttime="
- + starttime
- + " endtime="
- + this.endtime
- + " hash="
- + hash.toHexString()
- + " netstatus="
- + xdagStats;
- }
-
- @Override
- public XdagMessageCodes getCommand() {
- return XdagMessageCodes.SYNCBLOCK_REQUEST;
- }
-
- @Override
- public void encode() {
- parsed = true;
- encoded = MutableBytes.create(512);
- int ttl = 1;
- long transportheader = (ttl << 8) | DNET_PKT_XDAG | (XDAG_BLOCK_SIZE << 16);
- long type = (codes.asByte() << 4) | XDAG_FIELD_NONCE.asByte();
-
- BigInteger diff = xdagStats.getDifficulty();
- BigInteger maxDiff = xdagStats.getMaxdifficulty();
- long nmain = xdagStats.getNmain();
- long totalMainNumber = Math.max(xdagStats.getTotalnmain(), nmain);
- long nblocks = xdagStats.getNblocks();
- long totalBlockNumber = xdagStats.getTotalnblocks();
-
- MutableBytes mutableBytes = MutableBytes.create(112);
- long nhosts = currentDB.getIpList().size();
- long totalHosts = currentDB.getIpList().size();
-
- mutableBytes.set(0, Bytes.wrap(BytesUtils.longToBytes(nhosts, true)));
- mutableBytes.set(8, Bytes.wrap(BytesUtils.longToBytes(totalHosts, true)));
- mutableBytes.set(16, Bytes.wrap(currentDB.getEncoded()));
-
-// // TODO:后续根据ip替换
-// String tmp = "04000000040000003ef4780100000000" + "7f000001611e7f000001b8227f0000015f767f000001d49d";
-// // net 相关
-// byte[] tmpbyte = Hex.decode(tmp);
-
- // field 0 and field1
- MutableBytes32 first = MutableBytes32.create();
- first.set(0, Bytes.wrap(BytesUtils.longToBytes(transportheader, true)));
- first.set(8, Bytes.wrap(BytesUtils.longToBytes(type, true)));
- first.set(16, Bytes.wrap(BytesUtils.longToBytes(starttime, true)));
- first.set(24, Bytes.wrap(BytesUtils.longToBytes(endtime, true)));
-
- encoded.set(0, first);
- encoded.set(32, hash.reverse());
-
- // field2 diff and maxdiff
- encoded.set(64, Bytes.wrap(BytesUtils.bigIntegerToBytes(diff, 16, true)));
- encoded.set(80, Bytes.wrap(BytesUtils.bigIntegerToBytes(maxDiff, 16, true)));
-
- // field3 nblock totalblock main totalmain
- encoded.set(96, Bytes.wrap(BytesUtils.longToBytes(nblocks, true)));
- encoded.set(104, Bytes.wrap(BytesUtils.longToBytes(totalBlockNumber, true)));
- encoded.set(112, Bytes.wrap(BytesUtils.longToBytes(nmain, true)));
- encoded.set(120, Bytes.wrap(BytesUtils.longToBytes(totalMainNumber, true)));
- encoded.set(128, Bytes.wrap(mutableBytes));
- updateCrc();
- }
-
- @Override
- public void parse() {
- if (parsed) {
- return;
- }
-
- this.starttime = encoded.getLong(16, ByteOrder.LITTLE_ENDIAN);
- this.endtime = encoded.getLong(24, ByteOrder.LITTLE_ENDIAN);
- BigInteger maxdifficulty = encoded.slice(80, 16).toUnsignedBigInteger(ByteOrder.LITTLE_ENDIAN);
- long totalnblocks = encoded.getLong(104, ByteOrder.LITTLE_ENDIAN);
- long totalnmains = encoded.getLong(120, ByteOrder.LITTLE_ENDIAN);
- int totalnhosts = encoded.getInt(132, ByteOrder.LITTLE_ENDIAN);
- long maintime = encoded.getLong(136, ByteOrder.LITTLE_ENDIAN);
- xdagStats = new XdagStats(maxdifficulty, totalnblocks, totalnmains, totalnhosts, maintime);
- MutableBytes32 hash = MutableBytes32.create();
- hash.set(0, encoded.slice(32, 24));
- this.hash = hash.copy();
- parsed = true;
- }
-}
diff --git a/src/main/java/io/xdag/net/message/impl/Xdag03MessageFactory.java b/src/main/java/io/xdag/net/message/impl/Xdag03MessageFactory.java
deleted file mode 100644
index b81922ea3..000000000
--- a/src/main/java/io/xdag/net/message/impl/Xdag03MessageFactory.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.message.impl;
-
-import static io.xdag.net.XdagVersion.V03;
-
-import io.xdag.net.message.Message;
-import io.xdag.net.message.MessageFactory;
-import io.xdag.net.message.XdagMessageCodes;
-import org.apache.tuweni.bytes.MutableBytes;
-
-public class Xdag03MessageFactory implements MessageFactory {
-
- @Override
- public Message create(byte code, MutableBytes encoded) {
- XdagMessageCodes receivedCommand = XdagMessageCodes.fromByte(code, V03);
-
- return switch (receivedCommand) {
- case BLOCKS_REQUEST -> new BlocksRequestMessage(encoded);
- case BLOCKS_REPLY -> new BlocksReplyMessage(encoded);
- case SUMS_REQUEST -> new SumRequestMessage(encoded);
- case SUMS_REPLY -> new SumReplyMessage(encoded);
- case BLOCKEXT_REQUEST -> new BlockExtRequestMessage(encoded);
- case BLOCKEXT_REPLY -> new BlockExtReplyMessage(encoded);
- case BLOCK_REQUEST -> new BlockRequestMessage(encoded);
- case NEW_BLOCK -> new NewBlockMessage(encoded);
- case SYNC_BLOCK -> new SyncBlockMessage(encoded);
- case SYNCBLOCK_REQUEST -> new SyncBlockRequestMessage(encoded);
- default -> throw new IllegalArgumentException("No such message code" + code);
- };
- }
-
-}
diff --git a/src/main/java/io/xdag/mine/message/TaskShareMessage.java b/src/main/java/io/xdag/net/message/p2p/DisconnectMessage.java
similarity index 58%
rename from src/main/java/io/xdag/mine/message/TaskShareMessage.java
rename to src/main/java/io/xdag/net/message/p2p/DisconnectMessage.java
index 530d9ec3e..923573627 100644
--- a/src/main/java/io/xdag/mine/message/TaskShareMessage.java
+++ b/src/main/java/io/xdag/net/message/p2p/DisconnectMessage.java
@@ -21,46 +21,41 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+package io.xdag.net.message.p2p;
-package io.xdag.mine.message;
-
-import static io.xdag.net.message.XdagMessageCodes.TASK_SHARE;
-
-import io.xdag.core.XdagField;
+import io.xdag.core.SimpleEncoder;
import io.xdag.net.message.Message;
-import io.xdag.net.message.XdagMessageCodes;
+import io.xdag.net.message.MessageCode;
+import io.xdag.net.message.ReasonCode;
+import io.xdag.utils.SimpleDecoder;
+import lombok.Getter;
-import org.apache.commons.lang3.builder.ToStringBuilder;
-import org.apache.commons.lang3.builder.ToStringStyle;
-import org.apache.tuweni.bytes.Bytes;
-import org.apache.tuweni.bytes.MutableBytes;
+@Getter
+public class DisconnectMessage extends Message {
-public class TaskShareMessage extends Message {
+ private final ReasonCode reason;
- private final XdagField xdagField;
+ public DisconnectMessage(ReasonCode reason) {
+ super(MessageCode.DISCONNECT, null);
- public TaskShareMessage(MutableBytes encoded) {
- super(encoded);
- this.xdagField = new XdagField(encoded);
- }
+ this.reason = reason;
- @Override
- public Bytes getEncoded() {
- return xdagField.getData();
+ SimpleEncoder enc = new SimpleEncoder();
+ enc.writeByte(reason.toByte());
+ this.body = enc.toBytes();
}
- @Override
- public Class> getAnswerMessage() {
- return null;
- }
+ public DisconnectMessage(byte[] body) {
+ super(MessageCode.DISCONNECT, null);
- @Override
- public XdagMessageCodes getCommand() {
- return TASK_SHARE;
+ SimpleDecoder dec = new SimpleDecoder(body);
+ this.reason = ReasonCode.of(dec.readByte());
+
+ this.body = body;
}
@Override
public String toString() {
- return new ToStringBuilder(this, ToStringStyle.JSON_STYLE).toString();
+ return "DisconnectMessage [reason=" + reason + "]";
}
-}
+}
\ No newline at end of file
diff --git a/src/main/java/io/xdag/net/message/p2p/HandshakeMessage.java b/src/main/java/io/xdag/net/message/p2p/HandshakeMessage.java
new file mode 100644
index 000000000..2c6b2ec07
--- /dev/null
+++ b/src/main/java/io/xdag/net/message/p2p/HandshakeMessage.java
@@ -0,0 +1,169 @@
+/*
+ * 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.message.p2p;
+
+import static io.xdag.utils.WalletUtils.toBase58;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.tuweni.bytes.Bytes;
+import org.apache.tuweni.bytes.Bytes32;
+import org.hyperledger.besu.crypto.KeyPair;
+import org.hyperledger.besu.crypto.SECPPublicKey;
+import org.hyperledger.besu.crypto.SECPSignature;
+
+import io.xdag.Network;
+import io.xdag.config.Config;
+import io.xdag.core.SimpleEncoder;
+import io.xdag.crypto.Hash;
+import io.xdag.crypto.Keys;
+import io.xdag.crypto.Sign;
+import io.xdag.net.Peer;
+import io.xdag.net.message.Message;
+import io.xdag.net.message.MessageCode;
+import io.xdag.utils.SimpleDecoder;
+import lombok.Getter;
+import lombok.Setter;
+
+@Getter
+@Setter
+public abstract class HandshakeMessage extends Message {
+
+ protected final Network network;
+ protected final short networkVersion;
+
+ protected final String peerId;
+ protected final int port;
+
+ protected final String clientId;
+ protected final String[] capabilities;
+
+ protected final long latestBlockNumber;
+
+ protected final byte[] secret;
+ protected final long timestamp;
+ protected final SECPSignature signature;
+
+ protected SECPPublicKey publicKey;
+
+ public HandshakeMessage(MessageCode code, Class> responseMessageClass,
+ Network network, short networkVersion, String peerId, int port,
+ String clientId, String[] capabilities, long latestBlockNumber,
+ byte[] secret, KeyPair coinbase) {
+ super(code, responseMessageClass);
+
+ this.network = network;
+ this.networkVersion = networkVersion;
+ this.peerId = peerId;
+ this.port = port;
+ this.clientId = clientId;
+ this.capabilities = capabilities;
+ this.latestBlockNumber = latestBlockNumber;
+ this.secret = secret;
+ this.timestamp = System.currentTimeMillis();
+ this.publicKey = coinbase.getPublicKey();
+
+ SimpleEncoder enc = encodeBasicInfo();
+ Bytes32 hash = Hash.sha256(Bytes.wrap(enc.toBytes()));
+ this.signature = Sign.SECP256K1.sign(hash, coinbase);
+
+ enc.writeBytes(signature.encodedBytes().toArray());
+
+ this.body = enc.toBytes();
+ }
+
+ public HandshakeMessage(MessageCode code, Class> responseMessageClass, byte[] body) {
+ super(code, responseMessageClass);
+
+ SimpleDecoder dec = new SimpleDecoder(body);
+ this.network = Network.of(dec.readByte());
+ this.networkVersion = dec.readShort();
+ this.peerId = dec.readString();
+ this.port = dec.readInt();
+ this.clientId = dec.readString();
+ List capabilities = new ArrayList<>();
+ for (int i = 0, size = dec.readInt(); i < size; i++) {
+ capabilities.add(dec.readString());
+ }
+ this.capabilities = capabilities.toArray(new String[0]);
+ this.latestBlockNumber = dec.readLong();
+ this.secret = dec.readBytes();
+ this.timestamp = dec.readLong();
+ this.signature = Sign.SECP256K1.decodeSignature(Bytes.wrap(dec.readBytes()));
+ this.body = body;
+ }
+
+ protected SimpleEncoder encodeBasicInfo() {
+ SimpleEncoder enc = new SimpleEncoder();
+
+ enc.writeByte(network.id());
+ enc.writeShort(networkVersion);
+ enc.writeString(peerId);
+ enc.writeInt(port);
+ enc.writeString(clientId);
+ enc.writeInt(capabilities.length);
+ for (String capability : capabilities) {
+ enc.writeString(capability);
+ }
+ enc.writeLong(latestBlockNumber);
+ enc.writeBytes(secret);
+ enc.writeLong(timestamp);
+
+ return enc;
+ }
+
+ public boolean validate(Config config) {
+ SimpleEncoder enc = encodeBasicInfo();
+ Bytes32 hash = Hash.sha256(Bytes.wrap(enc.toBytes()));
+ if(publicKey == null && signature !=null) {
+ publicKey = Sign.SECP256K1.recoverPublicKeyFromSignature(hash, signature).get();
+ }
+ if (network == config.getNodeSpec().getNetwork()
+ && networkVersion == config.getNodeSpec().getNetworkVersion()
+ && peerId != null && peerId.length() <= 64
+ && port > 0 && port <= 65535
+ && clientId != null && clientId.length() < 128
+ && latestBlockNumber >= 0
+ && secret != null && secret.length == InitMessage.SECRET_LENGTH
+ && Math.abs(System.currentTimeMillis() - timestamp) <= config.getNodeSpec().getNetHandshakeExpiry()
+ && signature != null
+ && peerId.equals(toBase58(Keys.toBytesAddress(publicKey)))) {
+
+ return Sign.SECP256K1.verify(hash, signature, publicKey);
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * 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/message/p2p/HelloMessage.java b/src/main/java/io/xdag/net/message/p2p/HelloMessage.java
new file mode 100644
index 000000000..7e4e696f8
--- /dev/null
+++ b/src/main/java/io/xdag/net/message/p2p/HelloMessage.java
@@ -0,0 +1,61 @@
+/*
+ * 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.message.p2p;
+
+import java.util.Arrays;
+
+import org.hyperledger.besu.crypto.KeyPair;
+
+import io.xdag.Network;
+import io.xdag.net.message.MessageCode;
+import io.xdag.utils.BytesUtils;
+
+public class HelloMessage extends HandshakeMessage {
+
+ public HelloMessage(Network network, short networkVersion, String peerId, int port,
+ String clientId, String[] capabilities, long latestBlockNumber,
+ byte[] secret, KeyPair coinbase) {
+ super(MessageCode.HANDSHAKE_HELLO, WorldMessage.class, network, networkVersion, peerId, port, clientId,
+ capabilities, latestBlockNumber, secret, coinbase);
+ }
+
+ public HelloMessage(byte[] encoded) {
+ super(MessageCode.HANDSHAKE_HELLO, WorldMessage.class, encoded);
+ }
+
+ @Override
+ public String toString() {
+ return "HelloMessage{" +
+ "peer=" + network +
+ ", networkVersion=" + networkVersion +
+ ", peerId='" + peerId + '\'' +
+ ", port=" + port +
+ ", clientId='" + clientId + '\'' +
+ ", capabilities=" + Arrays.toString(capabilities) +
+ ", latestBlockNumber=" + latestBlockNumber +
+ ", secret=" + BytesUtils.toHexString(secret) +
+ ", timestamp=" + timestamp +
+ '}';
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/io/xdag/net/message/p2p/InitMessage.java b/src/main/java/io/xdag/net/message/p2p/InitMessage.java
new file mode 100644
index 000000000..0ee3d3a79
--- /dev/null
+++ b/src/main/java/io/xdag/net/message/p2p/InitMessage.java
@@ -0,0 +1,75 @@
+/*
+ * 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.message.p2p;
+
+import io.xdag.core.SimpleEncoder;
+import io.xdag.net.message.Message;
+import io.xdag.net.message.MessageCode;
+import io.xdag.utils.BytesUtils;
+import io.xdag.utils.SimpleDecoder;
+import lombok.Getter;
+
+@Getter
+public class InitMessage extends Message {
+
+ public static final int SECRET_LENGTH = 32;
+
+ private final byte[] secret;
+ private final long timestamp;
+
+ public InitMessage(byte[] secret, long timestamp) {
+ super(MessageCode.HANDSHAKE_INIT, null);
+
+ this.secret = secret;
+ this.timestamp = timestamp;
+
+ SimpleEncoder enc = new SimpleEncoder();
+ enc.writeBytes(secret);
+ enc.writeLong(timestamp);
+
+ this.body = enc.toBytes();
+ }
+
+ public InitMessage(byte[] body) {
+ super(MessageCode.HANDSHAKE_INIT, null);
+
+ SimpleDecoder dec = new SimpleDecoder(body);
+ this.secret = dec.readBytes();
+ this.timestamp = dec.readLong();
+
+ this.body = body;
+ }
+
+ public boolean validate() {
+ return secret != null && secret.length == SECRET_LENGTH && timestamp > 0;
+ }
+
+ @Override
+ public String toString() {
+ return "InitMessage{" +
+ "secret=" + BytesUtils.toHexString(secret) +
+ ", timestamp=" + timestamp +
+ '}';
+ }
+}
diff --git a/src/main/java/io/xdag/net/message/impl/BlockExtReplyMessage.java b/src/main/java/io/xdag/net/message/p2p/PingMessage.java
similarity index 60%
rename from src/main/java/io/xdag/net/message/impl/BlockExtReplyMessage.java
rename to src/main/java/io/xdag/net/message/p2p/PingMessage.java
index 00c4ea9a5..b9686f58a 100644
--- a/src/main/java/io/xdag/net/message/impl/BlockExtReplyMessage.java
+++ b/src/main/java/io/xdag/net/message/p2p/PingMessage.java
@@ -1,61 +1,58 @@
-/*
- * 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.message.impl;
-
-import io.xdag.net.message.Message;
-import io.xdag.net.message.XdagMessageCodes;
-
-import org.apache.commons.lang3.builder.ToStringBuilder;
-import org.apache.commons.lang3.builder.ToStringStyle;
-import org.apache.tuweni.bytes.Bytes;
-import org.apache.tuweni.bytes.MutableBytes;
-
-public class BlockExtReplyMessage extends Message {
-
- public BlockExtReplyMessage(MutableBytes bytes) {
- super(bytes);
- }
-
- @Override
- public Class> getAnswerMessage() {
- return null;
- }
-
- @Override
- public Bytes getEncoded() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this, ToStringStyle.JSON_STYLE).toString();
- }
-
- @Override
- public XdagMessageCodes getCommand() {
- return XdagMessageCodes.BLOCKEXT_REPLY;
- }
-}
+/*
+ * 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.message.p2p;
+
+import io.xdag.core.SimpleEncoder;
+import io.xdag.net.message.Message;
+import io.xdag.net.message.MessageCode;
+import io.xdag.utils.SimpleDecoder;
+
+public class PingMessage extends Message {
+
+ private final long timestamp;
+
+ public PingMessage() {
+ super(MessageCode.PING, PongMessage.class);
+
+ this.timestamp = System.currentTimeMillis();
+
+ SimpleEncoder enc = new SimpleEncoder();
+ enc.writeLong(timestamp);
+ this.body = enc.toBytes();
+ }
+
+ public PingMessage(byte[] body) {
+ super(MessageCode.PING, PongMessage.class);
+
+ SimpleDecoder dec = new SimpleDecoder(body);
+ this.timestamp = dec.readLong();
+
+ this.body = body;
+ }
+
+ @Override
+ public String toString() {
+ return "PingMessage [timestamp=" + timestamp + "]";
+ }
+}
diff --git a/src/main/java/io/xdag/mine/manager/MinerManager.java b/src/main/java/io/xdag/net/message/p2p/PongMessage.java
similarity index 60%
rename from src/main/java/io/xdag/mine/manager/MinerManager.java
rename to src/main/java/io/xdag/net/message/p2p/PongMessage.java
index 39129e8ca..ca87e38f0 100644
--- a/src/main/java/io/xdag/mine/manager/MinerManager.java
+++ b/src/main/java/io/xdag/net/message/p2p/PongMessage.java
@@ -21,39 +21,38 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
+package io.xdag.net.message.p2p;
-package io.xdag.mine.manager;
-
-import io.xdag.consensus.PoW;
-import io.xdag.consensus.Task;
-import io.xdag.mine.MinerChannel;
-import io.xdag.mine.miner.Miner;
+import io.xdag.core.SimpleEncoder;
import io.xdag.net.message.Message;
-import java.net.InetSocketAddress;
-import java.util.Map;
-import org.apache.tuweni.bytes.Bytes;
-
-public interface MinerManager {
-
- Map getActivateMiners();
-
- void onNewShare(MinerChannel channel, Message msg);
+import io.xdag.net.message.MessageCode;
+import io.xdag.utils.SimpleDecoder;
- void setPoW(PoW pow);
+public class PongMessage extends Message {
- void start();
+ private final long timestamp;
- void addActivateChannel(MinerChannel channel);
+ public PongMessage() {
+ super(MessageCode.PONG, null);
- void stop();
+ this.timestamp = System.currentTimeMillis();
- MinerChannel getChannelByHost(InetSocketAddress host);
+ SimpleEncoder enc = new SimpleEncoder();
+ enc.writeLong(timestamp);
+ this.body = enc.toBytes();
+ }
- Map getActivateMinerChannels();
+ public PongMessage(byte[] body) {
+ super(MessageCode.PONG, null);
- void removeUnactivateChannel(MinerChannel channel);
+ SimpleDecoder dec = new SimpleDecoder(body);
+ this.timestamp = dec.readLong();
- void updateTask(Task task);
+ this.body = body;
+ }
- void addActiveMiner(Miner miner);
+ @Override
+ public String toString() {
+ return "PongMessage [timestamp=" + timestamp + "]";
+ }
}
diff --git a/src/main/java/io/xdag/net/message/p2p/WorldMessage.java b/src/main/java/io/xdag/net/message/p2p/WorldMessage.java
new file mode 100644
index 000000000..1211445b4
--- /dev/null
+++ b/src/main/java/io/xdag/net/message/p2p/WorldMessage.java
@@ -0,0 +1,61 @@
+/*
+ * 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.message.p2p;
+
+import java.util.Arrays;
+
+import org.apache.tuweni.bytes.Bytes;
+import org.hyperledger.besu.crypto.KeyPair;
+
+import io.xdag.Network;
+import io.xdag.net.message.MessageCode;
+
+public class WorldMessage extends HandshakeMessage {
+
+ public WorldMessage(Network network, short networkVersion, String peerId, int port,
+ String clientId, String[] capabilities, long latestBlockNumber,
+ byte[] secret, KeyPair coinbase) {
+ super(MessageCode.HANDSHAKE_WORLD, null, network, networkVersion, peerId, port, clientId,
+ capabilities, latestBlockNumber, secret, coinbase);
+ }
+
+ public WorldMessage(byte[] encoded) {
+ super(MessageCode.HANDSHAKE_WORLD, null, encoded);
+ }
+
+ @Override
+ public String toString() {
+ return "WorldMessage{" +
+ "network=" + network +
+ ", networkVersion=" + networkVersion +
+ ", peerId='" + peerId + '\'' +
+ ", port=" + port +
+ ", clientId='" + clientId + '\'' +
+ ", capabilities=" + Arrays.toString(capabilities) +
+ ", latestBlockNumber=" + latestBlockNumber +
+ ", secret=" + Bytes.wrap(secret).toHexString() +
+ ", timestamp=" + timestamp +
+ '}';
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/io/xdag/net/node/Node.java b/src/main/java/io/xdag/net/node/Node.java
index 60332ccdc..447dfbf38 100644
--- a/src/main/java/io/xdag/net/node/Node.java
+++ b/src/main/java/io/xdag/net/node/Node.java
@@ -24,57 +24,46 @@
package io.xdag.net.node;
-import io.xdag.utils.BytesUtils;
-import java.net.InetAddress;
import java.net.InetSocketAddress;
import lombok.Getter;
-import org.apache.commons.codec.binary.Hex;
-import org.apache.commons.lang3.RandomUtils;
+@Getter
public class Node {
- @Getter
- private final String host;
+ private final InetSocketAddress address;
- @Getter
- private final int port;
- @Getter
- private final NodeStat stat = new NodeStat();
- @Getter
- private byte[] id;
+ public Node(InetSocketAddress address) {
+ this.address = address;
+ }
- public Node(String host, int port) {
- this.host = host;
- this.port = port;
- this.id = BytesUtils.longToBytes(RandomUtils.nextLong(), true);
+ public Node(String ip, int port) {
+ this(new InetSocketAddress(ip, port));
}
- public Node(byte[] id, String host, int port) {
- this.id = id;
- this.host = host;
- this.port = port;
+ public String getIp() {
+ return address.getAddress().getHostAddress();
}
- public Node(InetAddress address, int port) {
- this.host = address.getHostAddress();
- this.port = port;
+ public int getPort() {
+ return address.getPort();
}
- public String getHexId() {
- return Hex.encodeHexString(id);
+ public InetSocketAddress toAddress() {
+ return this.address;
}
- public InetSocketAddress getAddress() {
- return new InetSocketAddress(this.getHost(), this.getPort());
+ @Override
+ public int hashCode() {
+ return address.hashCode();
}
@Override
public boolean equals(Object o) {
- return o instanceof Node && getAddress().equals(((Node) o).getAddress());
+ return o instanceof Node && address.equals(((Node) o).toAddress());
}
@Override
- public int hashCode() {
- return getAddress().hashCode();
+ public String toString() {
+ return getIp() + ":" + getPort();
}
}
diff --git a/src/main/java/io/xdag/net/node/NodeManager.java b/src/main/java/io/xdag/net/node/NodeManager.java
index 6d97c1d3c..18ff7d418 100644
--- a/src/main/java/io/xdag/net/node/NodeManager.java
+++ b/src/main/java/io/xdag/net/node/NodeManager.java
@@ -24,28 +24,20 @@
package io.xdag.net.node;
-import static io.xdag.net.libp2p.Libp2pUtils.discoveryPeerToDailId;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import io.xdag.Kernel;
import io.xdag.config.Config;
import io.xdag.net.Channel;
-import io.xdag.net.XdagClient;
-import io.xdag.net.handler.XdagChannelInitializer;
-import io.xdag.net.libp2p.Libp2pNetwork;
-import io.xdag.net.libp2p.discovery.DiscoveryPeer;
-import io.xdag.net.manager.NetDBManager;
-import io.xdag.net.manager.XdagChannelManager;
-import io.xdag.net.message.NetDB;
+import io.xdag.net.PeerClient;
+import io.xdag.net.XdagChannelInitializer;
+import io.xdag.net.NetDBManager;
+import io.xdag.net.ChannelManager;
+import io.xdag.net.NetDB;
import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.Deque;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ScheduledExecutorService;
@@ -77,17 +69,13 @@ public class NodeManager {
*/
private final ScheduledExecutorService exec;
private final Kernel kernel;
- private final XdagClient client;
- private final XdagChannelManager channelMgr;
+ private final PeerClient client;
+ private final ChannelManager channelMgr;
private final NetDBManager netDBManager;
private final Config config;
- private final Libp2pNetwork libp2pNetwork;
- private final Node myself;
private volatile boolean isRunning;
private ScheduledFuture> connectFuture;
private ScheduledFuture> fetchFuture;
- private ScheduledFuture> connectlibp2PFuture;
- private Set hadConnected;
public NodeManager(Kernel kernel) {
this.kernel = kernel;
@@ -96,9 +84,6 @@ public NodeManager(Kernel kernel) {
this.exec = new ScheduledThreadPoolExecutor(1, factory);
this.config = kernel.getConfig();
this.netDBManager = kernel.getNetDBMgr();
- libp2pNetwork = kernel.getLibp2pNetwork();
- myself = new Node(kernel.getConfig().getNodeSpec().getNodeIp(),
- kernel.getConfig().getNodeSpec().getLibp2pPort());
}
/**
@@ -114,8 +99,6 @@ public synchronized void start() {
// every 100 seconds, delayed by 5 seconds (public IP lookup)
fetchFuture = exec.scheduleAtFixedRate(this::doFetch, 5, 100, TimeUnit.SECONDS);
- connectlibp2PFuture = exec.scheduleAtFixedRate(this::doConnectlibp2p, 10, 10, TimeUnit.SECONDS);
- hadConnected = new HashSet<>();
isRunning = true;
log.debug("Node manager started");
}
@@ -125,7 +108,6 @@ public synchronized void stop() {
if (isRunning) {
connectFuture.cancel(true);
fetchFuture.cancel(false);
- connectlibp2PFuture.cancel(true);
isRunning = false;
exec.shutdown();
log.debug("Node manager stop...");
@@ -137,7 +119,7 @@ public int queueSize() {
}
public void addNodes(Collection nodes) {
- if (nodes == null || nodes.size() == 0) {
+ if (nodes == null || nodes.isEmpty()) {
return;
}
for (Node node : nodes) {
@@ -160,7 +142,7 @@ public void addNode(Node node) {
* from net update seed nodes
*/
protected void doFetch() {
- log.debug("Do fetch");
+ log.debug("Do fetch node size:{}", deque.size());
if (config.getNodeSpec().enableRefresh()) {
netDBManager.refresh();
}
@@ -168,8 +150,6 @@ protected void doFetch() {
addNodes(getSeedNodes(netDBManager.getWhiteDB()));
// 从netdb获取新节点
addNodes(getSeedNodes(netDBManager.getNetDB()));
-
- log.debug("node size:" + deque.size());
}
public Set getSeedNodes(NetDB netDB) {
@@ -181,7 +161,6 @@ public Set getSeedNodes(NetDB netDB) {
}
public void doConnect() {
-
Set activeAddress = channelMgr.getActiveAddresses();
Node node;
while ((node = deque.pollFirst()) != null && channelMgr.size() < config.getNodeSpec().getMaxConnections()) {
@@ -189,12 +168,11 @@ public void doConnect() {
long now = System.currentTimeMillis();
if (!client.getNode().equals(node)
- && !(Objects.equals(node.getHost(), client.getNode().getHost())
- && node.getPort() == client.getNode().getPort())
+ && !node.equals(client.getNode())
&& !activeAddress.contains(node.getAddress())
&& (lastCon == null || lastCon + RECONNECT_WAIT < now)) {
XdagChannelInitializer initializer = new XdagChannelInitializer(kernel, false, node);
- client.connect(node.getHost(), node.getPort(), initializer);
+ client.connect(node, initializer);
lastConnect.put(node, now);
break;
}
@@ -203,40 +181,12 @@ public void doConnect() {
}
public void doConnect(String ip, int port) {
+ Set activeAddresses = channelMgr.getActiveAddresses();
Node remotenode = new Node(ip, port);
- if (!client.getNode().equals(remotenode) && !channelMgr.containsNode(remotenode)) {
+ if (!client.getNode().equals(remotenode) && !activeAddresses.contains(remotenode.toAddress())) {
XdagChannelInitializer initializer = new XdagChannelInitializer(kernel, false, remotenode);
- client.connect(ip, port, initializer);
- }
- }
-
- //todo:发现之后的节点只能自动连接一次
- public void doConnectlibp2p() {
- Set activeAddress = channelMgr.getActiveAddresses();
- List discoveryPeerList =
- libp2pNetwork.getDiscV5Service().streamKnownPeers().toList();
- for (DiscoveryPeer p : discoveryPeerList) {
- Node node = new Node(p.getNodeAddress().getHostName(), p.getNodeAddress().getPort());
- if (!myself.equals(node) && !activeAddress.contains(p.getNodeAddress()) && !hadConnected.contains(node)) {
- kernel.getLibp2pNetwork().dail(discoveryPeerToDailId(p));
- hadConnected.add(node);
- }
- }
- }
-
- public Map getActiveNode() {
- Map nodes = new HashMap<>();
- List activeAddress = channelMgr.getActiveChannels();
- for (Channel address : activeAddress) {
- Node node = address.getNode();
- Long time = lastConnect.getIfPresent(node);
- if (time == null) {
- // 尝试在channel管理器中查询
- time = channelMgr.getChannelLastConnect().getIfPresent(node.getAddress());
- }
- nodes.put(node, time);
+ client.connect(new Node(ip, port), initializer);
}
- return nodes;
}
}
diff --git a/src/main/java/io/xdag/rpc/Web3Impl.java b/src/main/java/io/xdag/rpc/Web3Impl.java
index 49aa0bf4a..65979d892 100644
--- a/src/main/java/io/xdag/rpc/Web3Impl.java
+++ b/src/main/java/io/xdag/rpc/Web3Impl.java
@@ -140,15 +140,6 @@ public Object xdag_netConnectionList() throws Exception {
return web3XdagModule.xdag_netConnectionList();
}
- @Override
- public Object xdag_updatePoolConfig(ConfigDTO configDTO,String passphrase) throws Exception {
- return web3XdagModule.xdag_updatePoolConfig(configDTO,passphrase);
- }
-
- @Override
- public Object xdag_getPoolWorkers() throws Exception {
- return web3XdagModule.xdag_getPoolWorkers();
- }
@Override
public String xdag_getMaxXferBalance() throws Exception {
return web3XdagModule.xdag_getMaxXferBalance();
diff --git a/src/main/java/io/xdag/rpc/dto/NetConnDTO.java b/src/main/java/io/xdag/rpc/dto/NetConnDTO.java
index d670468c8..a3e56f7e8 100644
--- a/src/main/java/io/xdag/rpc/dto/NetConnDTO.java
+++ b/src/main/java/io/xdag/rpc/dto/NetConnDTO.java
@@ -23,7 +23,6 @@
*/
package io.xdag.rpc.dto;
-import java.net.InetSocketAddress;
import lombok.Builder;
import lombok.Data;
@@ -31,9 +30,6 @@
@Builder
public class NetConnDTO {
- InetSocketAddress nodeAddress;
- long connectTime;
- long inBound;
- long outBound;
+ String info;
}
diff --git a/src/main/java/io/xdag/rpc/modules/xdag/Web3XdagModule.java b/src/main/java/io/xdag/rpc/modules/xdag/Web3XdagModule.java
index ba80deaca..eb0611644 100644
--- a/src/main/java/io/xdag/rpc/modules/xdag/Web3XdagModule.java
+++ b/src/main/java/io/xdag/rpc/modules/xdag/Web3XdagModule.java
@@ -118,9 +118,5 @@ default BlockResultDTO xdag_getBlockByHash(String blockHash, int page, int pageS
Object xdag_netConnectionList() throws Exception;
- Object xdag_updatePoolConfig(ConfigDTO args, String passphrase) throws Exception;
-
- Object xdag_getPoolWorkers() throws Exception;
-
String xdag_getMaxXferBalance() throws Exception;
}
diff --git a/src/main/java/io/xdag/rpc/modules/xdag/Web3XdagModuleImpl.java b/src/main/java/io/xdag/rpc/modules/xdag/Web3XdagModuleImpl.java
index a631b6415..5d4eb0516 100644
--- a/src/main/java/io/xdag/rpc/modules/xdag/Web3XdagModuleImpl.java
+++ b/src/main/java/io/xdag/rpc/modules/xdag/Web3XdagModuleImpl.java
@@ -32,15 +32,10 @@
import io.xdag.config.MainnetConfig;
import io.xdag.config.TestnetConfig;
import io.xdag.config.spec.NodeSpec;
-import io.xdag.config.spec.PoolSpec;
import io.xdag.core.*;
-import io.xdag.mine.MinerChannel;
-import io.xdag.mine.miner.Miner;
-import io.xdag.mine.miner.MinerCalculate;
-import io.xdag.net.node.Node;
+import io.xdag.net.Channel;
import io.xdag.rpc.dto.ConfigDTO;
import io.xdag.rpc.dto.NetConnDTO;
-import io.xdag.rpc.dto.PoolWorkerDTO;
import io.xdag.rpc.dto.StatusDTO;
import io.xdag.utils.BasicUtils;
import lombok.extern.slf4j.Slf4j;
@@ -48,13 +43,11 @@
import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.bytes.MutableBytes32;
-import java.net.InetSocketAddress;
-import java.util.Collection;
import java.util.List;
-import java.util.Map;
import java.util.Objects;
import static io.xdag.config.Constants.CLIENT_VERSION;
+import static io.xdag.crypto.Keys.toBytesAddress;
import static io.xdag.rpc.utils.TypeConverter.toQuantityJsonHex;
import static io.xdag.utils.BasicUtils.*;
import static io.xdag.utils.WalletUtils.*;
@@ -117,7 +110,7 @@ public Object xdag_syncing() {
@Override
public String xdag_coinbase() {
- return toBase58(hash2byte(kernel.getPoolMiner().getAddressHash().mutableCopy()));
+ return toBase58(toBytesAddress(kernel.getCoinbase()));
}
@Override
@@ -185,22 +178,22 @@ public Object xdag_netType() {
@Override
public Object xdag_poolConfig() {
- PoolSpec poolSpec = kernel.getConfig().getPoolSpec();
+// PoolSpec poolSpec = kernel.getConfig().getPoolSpec();
NodeSpec nodeSpec = kernel.getConfig().getNodeSpec();
ConfigDTO.ConfigDTOBuilder configDTOBuilder = ConfigDTO.builder();
- configDTOBuilder.poolIp(poolSpec.getPoolIp());
- configDTOBuilder.poolPort(poolSpec.getPoolPort());
+// configDTOBuilder.poolIp(poolSpec.getPoolIp());
+// configDTOBuilder.poolPort(poolSpec.getPoolPort());
configDTOBuilder.nodeIp(nodeSpec.getNodeIp());
configDTOBuilder.nodePort(nodeSpec.getNodePort());
- configDTOBuilder.globalMinerLimit(poolSpec.getGlobalMinerLimit());
- configDTOBuilder.maxConnectMinerPerIp(poolSpec.getMaxConnectPerIp());
- configDTOBuilder.maxMinerPerAccount(poolSpec.getMaxMinerPerAccount());
+// configDTOBuilder.globalMinerLimit(poolSpec.getGlobalMinerLimit());
+// configDTOBuilder.maxConnectMinerPerIp(poolSpec.getMaxConnectPerIp());
+// configDTOBuilder.maxMinerPerAccount(poolSpec.getMaxMinerPerAccount());
- configDTOBuilder.poolFundRation(Double.toString(kernel.getAwardManager().getPoolConfig().getFundRation() * 100));
- configDTOBuilder.poolFeeRation(Double.toString(kernel.getAwardManager().getPoolConfig().getPoolRation() * 100));
- configDTOBuilder.poolDirectRation(Double.toString(kernel.getAwardManager().getPoolConfig().getDirectRation() * 100));
- configDTOBuilder.poolRewardRation(Double.toString(kernel.getAwardManager().getPoolConfig().getMinerRewardRation() * 100));
+// configDTOBuilder.poolFundRation(Double.toString(kernel.getAwardManager().getPoolConfig().getFundRation() * 100));
+// configDTOBuilder.poolFeeRation(Double.toString(kernel.getAwardManager().getPoolConfig().getPoolRation() * 100));
+// configDTOBuilder.poolDirectRation(Double.toString(kernel.getAwardManager().getPoolConfig().getDirectRation() * 100));
+// configDTOBuilder.poolRewardRation(Double.toString(kernel.getAwardManager().getPoolConfig().getMinerRewardRation() * 100));
return configDTOBuilder.build();
}
@@ -208,13 +201,9 @@ public Object xdag_poolConfig() {
public Object xdag_netConnectionList() {
List netConnDTOList = Lists.newArrayList();
NetConnDTO.NetConnDTOBuilder netConnDTOBuilder = NetConnDTO.builder();
- Map map = kernel.getNodeMgr().getActiveNode();
- for (Map.Entry entry : map.entrySet()) {
- Node node = entry.getKey();
- netConnDTOBuilder.connectTime(map.get(node) == null ? 0 : map.get(node)) // use default "0"
- .inBound(node.getStat().Inbound.get())
- .outBound(node.getStat().Outbound.get())
- .nodeAddress(node.getAddress());
+ List channelList = kernel.getChannelMgr().getActiveChannels();
+ for (Channel channel : channelList) {
+ netConnDTOBuilder.info(channel.toString());
netConnDTOList.add(netConnDTOBuilder.build());
}
@@ -229,69 +218,32 @@ static class SyncingResult {
}
- @Override
- public Object xdag_updatePoolConfig(ConfigDTO configDTO, String passphrase) {
- try {
- //unlock
- if (checkPassword(passphrase)) {
- double poolFeeRation = configDTO.getPoolFeeRation() != null ?
- Double.parseDouble(configDTO.getPoolFeeRation()) : kernel.getConfig().getPoolSpec().getPoolRation();
- double poolRewardRation = configDTO.getPoolRewardRation() != null ?
- Double.parseDouble(configDTO.getPoolRewardRation()) : kernel.getConfig().getPoolSpec().getRewardRation();
- double poolDirectRation = configDTO.getPoolDirectRation() != null ?
- Double.parseDouble(configDTO.getPoolDirectRation()) : kernel.getConfig().getPoolSpec().getDirectRation();
- double poolFundRation = configDTO.getPoolFundRation() != null ?
- Double.parseDouble(configDTO.getPoolFundRation()) : kernel.getConfig().getPoolSpec().getFundRation();
- kernel.getAwardManager().updatePoolConfig(poolFeeRation, poolRewardRation, poolDirectRation, poolFundRation);
- }
- } catch (NumberFormatException e) {
- return "Error";
- }
- return "Success";
- }
-
- @Override
- public Object xdag_getPoolWorkers() {
- List poolWorkerDTOList = Lists.newArrayList();
- PoolWorkerDTO.PoolWorkerDTOBuilder poolWorkerDTOBuilder = PoolWorkerDTO.builder();
- Collection miners = kernel.getMinerManager().getActivateMiners().values();
- PoolWorkerDTO poolWorker = getPoolWorkerDTO(poolWorkerDTOBuilder, kernel.getPoolMiner());
- poolWorker.setStatus("fee");
- poolWorkerDTOList.add(poolWorker);
- for (Miner miner : miners) {
- poolWorkerDTOList.add(getPoolWorkerDTO(poolWorkerDTOBuilder,miner));
- }
- return poolWorkerDTOList;
- }
+// @Override
+// public Object xdag_updatePoolConfig(ConfigDTO configDTO, String passphrase) {
+// try {
+// //unlock
+// if (checkPassword(passphrase)) {
+// double poolFeeRation = configDTO.getPoolFeeRation() != null ?
+// Double.parseDouble(configDTO.getPoolFeeRation()) : kernel.getConfig().getPoolSpec().getPoolRation();
+// double poolRewardRation = configDTO.getPoolRewardRation() != null ?
+// Double.parseDouble(configDTO.getPoolRewardRation()) : kernel.getConfig().getPoolSpec().getRewardRation();
+// double poolDirectRation = configDTO.getPoolDirectRation() != null ?
+// Double.parseDouble(configDTO.getPoolDirectRation()) : kernel.getConfig().getPoolSpec().getDirectRation();
+// double poolFundRation = configDTO.getPoolFundRation() != null ?
+// Double.parseDouble(configDTO.getPoolFundRation()) : kernel.getConfig().getPoolSpec().getFundRation();
+// kernel.getAwardManager().updatePoolConfig(poolFeeRation, poolRewardRation, poolDirectRation, poolFundRation);
+// }
+// } catch (NumberFormatException e) {
+// return "Error";
+// }
+// return "Success";
+// }
@Override
public String xdag_getMaxXferBalance() {
return xdagModule.getMaxXferBalance();
}
- private PoolWorkerDTO getPoolWorkerDTO(PoolWorkerDTO.PoolWorkerDTOBuilder poolWorkerDTOBuilder,Miner miner){
- poolWorkerDTOBuilder.address(toBase58(miner.getAddressHashByte()))
- .status(miner.getMinerStates().toString())
- .unpaidShares(MinerCalculate.calculateUnpaidShares(miner))
- .hashrate(BasicUtils.xdag_log_difficulty2hashrate(miner.getMeanLogDiff()))
- .workers(getWorkers(miner));
- return poolWorkerDTOBuilder.build();
- }
- private List getWorkers(Miner miner) {
- List workersList = Lists.newArrayList();
- PoolWorkerDTO.Worker.WorkerBuilder workerBuilder = PoolWorkerDTO.Worker.builder();
- Map channels = miner.getChannels();
- for (Map.Entry channel : channels.entrySet()) {
- workerBuilder.address(channel.getKey()).inBound(channel.getValue().getInBound().get())
- .outBound(channel.getValue().getOutBound().get())
- .unpaidShares(MinerCalculate.calculateUnpaidShares(channel.getValue()))
- .name(channel.getValue().getWorkerName())
- .hashrate(BasicUtils.xdag_log_difficulty2hashrate(channel.getValue().getMeanLogDiff()));
- workersList.add(workerBuilder.build());
- }
- return workersList;
- }
-
private boolean checkPassword(String passphrase) {
Wallet wallet = new Wallet(kernel.getConfig());
return wallet.unlock(passphrase);
diff --git a/src/main/java/io/xdag/utils/exception/UnreachableException.java b/src/main/java/io/xdag/utils/exception/UnreachableException.java
new file mode 100644
index 000000000..ce86d2c3a
--- /dev/null
+++ b/src/main/java/io/xdag/utils/exception/UnreachableException.java
@@ -0,0 +1,50 @@
+/*
+ * 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.exception;
+
+public class UnreachableException extends RuntimeException {
+
+ private static final long serialVersionUID = 1L;
+
+ public UnreachableException() {
+ super("Should never reach here");
+ }
+
+ public UnreachableException(String message, Throwable cause, boolean enableSuppression,
+ boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
+
+ public UnreachableException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public UnreachableException(String message) {
+ super(message);
+ }
+
+ public UnreachableException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/src/main/resources/dnet_keys.bin b/src/main/resources/dnet_keys.bin
deleted file mode 100644
index 979093ba2..000000000
Binary files a/src/main/resources/dnet_keys.bin and /dev/null differ
diff --git a/src/main/resources/rpc_modules.conf b/src/main/resources/rpc_modules.conf
index 1252ee906..206c470ef 100644
--- a/src/main/resources/rpc_modules.conf
+++ b/src/main/resources/rpc_modules.conf
@@ -6,7 +6,7 @@ rpc {
enabled = true
bind_address = localhost
hosts = []
- port = 4444
+ port = 10001
# A value greater than zero sets the socket value in milliseconds. Node attempts to gently close all
# TCP/IP connections with proper half close semantics, so a linger timeout should not be required and
# thus the default is -1.
@@ -15,7 +15,7 @@ rpc {
ws {
enabled = true
bind_address = localhost
- port = 4445
+ port = 10002
}
}
}
diff --git a/src/main/resources/xdag-devnet.conf b/src/main/resources/xdag-devnet.conf
index 475f1c8e5..f18cac546 100644
--- a/src/main/resources/xdag-devnet.conf
+++ b/src/main/resources/xdag-devnet.conf
@@ -3,45 +3,22 @@ admin.telnet.ip = 127.0.0.1
admin.telnet.port = 6001
admin.telnet.password = root
-# Pool Config
-pool.ip = 127.0.0.1
-pool.port = 7001
-pool.tag = XdagJ
-
-# Pool-Reward Config
-pool.poolRation = 5
-pool.rewardRation = 5
-pool.fundRation = 5
-pool.directRation = 5
-pool.fundAddress = FQglVQtb60vQv2DOWEUL7yh3smtj7g1s
-
# Node config
node.ip = 127.0.0.1
node.port = 8001
+node.tag = xdagj-node-1
node.maxInboundConnectionsPerIp = 8
node.whiteIPs = ["127.0.0.1:8001","127.0.0.1:8002"]
node.generate.block.enable = true
# Node transaction history config
-node.transaction.history.enable = true
-
-# Node libp2p Config
-node.libp2p.port = 9001
-node.libp2p.isbootnode = true
-node.libp2p.privkey = 0x0802122074ca7d1380b2c407be6878669ebb5c7a2ee751bb18198f1a0f214bcb93b894b5
-node.libp2p.bootnode = ["enr:-Iu4QPY6bYDC0PaafEwhgg_6yTcx0GAGbSARYqehJKEkyOmxX6SNZMyMMdkmDw9bAvYN9m2LrqIsPSd-bUqff0tsHYABgmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQJ2EWgMpl6PtyFKMbbOb82Ob-al9NeE3GYB3-K7n4yWwoN0Y3CCJxGDdWRwgicR"]
+node.transaction.history.enable = false
# Node RPC Config
-rpc.enabled = true
+rpc.enabled = false
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
diff --git a/src/main/resources/xdag-mainnet.conf b/src/main/resources/xdag-mainnet.conf
index 3a2e75293..508e8d8f3 100644
--- a/src/main/resources/xdag-mainnet.conf
+++ b/src/main/resources/xdag-mainnet.conf
@@ -8,13 +8,6 @@ pool.ip = 127.0.0.1
pool.port = 7001
pool.tag = XdagJ
-# Pool-Reward Config
-pool.poolRation = 5
-pool.rewardRation = 5
-pool.fundRation = 5
-pool.directRation = 5
-pool.fundAddress = FQglVQtb60vQv2DOWEUL7yh3smtj7g1s
-
# Node config
node.ip = 127.0.0.1
node.port = 8001
@@ -26,12 +19,6 @@ node.generate.block.enable = true
node.transaction.history.enable = true
node.transaction.history.pageSizeLimit = 500
-# Node libp2p Config
-node.libp2p.port = 9001
-node.libp2p.isbootnode = true
-node.libp2p.privkey = 0x0802122074ca7d1380b2c407be6878669ebb5c7a2ee751bb18198f1a0f214bcb93b894b5
-node.libp2p.bootnode = ["enr:-Iu4QPY6bYDC0PaafEwhgg_6yTcx0GAGbSARYqehJKEkyOmxX6SNZMyMMdkmDw9bAvYN9m2LrqIsPSd-bUqff0tsHYABgmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQJ2EWgMpl6PtyFKMbbOb82Ob-al9NeE3GYB3-K7n4yWwoN0Y3CCJxGDdWRwgicR"]
-
# Node RPC Config
rpc.enabled = true
rpc.http.host = 127.0.0.1
diff --git a/src/main/resources/xdag-testnet.conf b/src/main/resources/xdag-testnet.conf
index 58fd9a45f..e3fb48854 100644
--- a/src/main/resources/xdag-testnet.conf
+++ b/src/main/resources/xdag-testnet.conf
@@ -8,13 +8,6 @@ pool.ip = 127.0.0.1
pool.port = 7001
pool.tag = XdagJ
-# Pool-Reward Config
-pool.poolRation = 5
-pool.rewardRation = 5
-pool.fundRation = 5
-pool.directRation = 5
-pool.fundAddress = FQglVQtb60vQv2DOWEUL7yh3smtj7g1s
-
# Node config
node.ip = 127.0.0.1
node.port = 8001
@@ -25,23 +18,11 @@ node.generate.block.enable = true
# Node transaction history config
node.transaction.history.enable = true
-# Node libp2p Config
-node.libp2p.port = 9001
-node.libp2p.isbootnode = true
-node.libp2p.privkey = 0x0802122074ca7d1380b2c407be6878669ebb5c7a2ee751bb18198f1a0f214bcb93b894b5
-node.libp2p.bootnode = ["enr:-Iu4QPY6bYDC0PaafEwhgg_6yTcx0GAGbSARYqehJKEkyOmxX6SNZMyMMdkmDw9bAvYN9m2LrqIsPSd-bUqff0tsHYABgmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQJ2EWgMpl6PtyFKMbbOb82Ob-al9NeE3GYB3-K7n4yWwoN0Y3CCJxGDdWRwgicR"]
-
# Node RPC Config
rpc.enabled = true
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
diff --git a/src/test/java/io/xdag/cli/CommandsTest.java b/src/test/java/io/xdag/cli/CommandsTest.java
index 3bab25a17..9abbab0a3 100644
--- a/src/test/java/io/xdag/cli/CommandsTest.java
+++ b/src/test/java/io/xdag/cli/CommandsTest.java
@@ -28,17 +28,14 @@
import static junit.framework.TestCase.assertEquals;
import java.math.BigInteger;
-import java.net.InetSocketAddress;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.List;
-import java.util.Map;
import java.util.TimeZone;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
-import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.units.bigints.UInt64;
import org.hyperledger.besu.crypto.KeyPair;
@@ -47,7 +44,6 @@
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
import io.xdag.Kernel;
import io.xdag.Wallet;
@@ -70,11 +66,8 @@
import io.xdag.crypto.Sign;
import io.xdag.db.AddressStore;
import io.xdag.db.BlockStore;
-import io.xdag.mine.MinerChannel;
-import io.xdag.mine.manager.MinerManager;
-import io.xdag.mine.miner.Miner;
-import io.xdag.net.manager.NetDBManager;
-import io.xdag.net.message.NetDB;
+import io.xdag.net.NetDBManager;
+import io.xdag.net.NetDB;
import io.xdag.utils.BasicUtils;
import io.xdag.utils.BytesUtils;
import io.xdag.utils.XdagTime;
@@ -303,23 +296,6 @@ public void testKeygen()
assertEquals("Key 1 generated and set as default,now key size is:2", str);
}
- @Test
- public void testMiners() {
- Miner mockPoolMiner = new Miner(BytesUtils.arrayToByte32(Keys.toBytesAddress(keyPair_1.getPublicKey())));
- Miner mockMiner2 = new Miner(BytesUtils.arrayToByte32(Keys.toBytesAddress(keyPair_2.getPublicKey())));
- Map mockActivateMiners = Maps.newHashMap();
- mockActivateMiners.put(mockPoolMiner.getAddressHash(), mockPoolMiner);
- mockActivateMiners.put(mockMiner2.getAddressHash(), mockMiner2);
-
- MinerManager mockMinerManager = Mockito.mock(MinerManager.class);
- Mockito.when(kernel.getPoolMiner()).thenReturn(mockPoolMiner);
- Mockito.when(kernel.getMinerManager()).thenReturn(mockMinerManager);
- Mockito.when(mockMinerManager.getActivateMiners()).thenReturn(mockActivateMiners);
-
- String str = commands.miners();
- assertEquals("fee:PbwjuQP3y9F3ZnbbWUvue4zpgkQv3DHas\n", str);
- }
-
@Test
public void testState() {
Mockito.when(kernel.getXdagState()).thenReturn(XdagState.INIT);
@@ -327,25 +303,6 @@ public void testState() {
assertEquals("Pool Initializing....", str);
}
- @Test
- public void testDisConnectMinerChannel() {
- Map mockMinerChannels = Maps.newHashMap();
- MinerChannel mc = Mockito.mock(MinerChannel.class);
- InetSocketAddress host = new InetSocketAddress("127.0.0.1", 10001);
-
- MinerManager mockMinerManager = Mockito.mock(MinerManager.class);
- Mockito.when(mockMinerManager.getActivateMinerChannels()).thenReturn(mockMinerChannels);
- Mockito.when(kernel.getMinerManager()).thenReturn(mockMinerManager);
- Mockito.when(mockMinerManager.getChannelByHost(host)).thenReturn(mc);
-
- String str = commands.disConnectMinerChannel("127.0.0.1:10001");
- assertEquals("disconnect a channel:127.0.0.1:10001", str);
- str = commands.disConnectMinerChannel("127.0.0.1:10002");
- assertEquals("Can't find the corresponding channel, please check", str);
- str = commands.disConnectMinerChannel("all");
- assertEquals("disconnect all channels...", str);
- }
-
@Test
public void testBalanceMaxXfer() {
String str = commands.balanceMaxXfer();
diff --git a/src/test/java/io/xdag/consensus/SyncTest.java b/src/test/java/io/xdag/consensus/SyncTest.java
index b4e93d2f8..2bc170bb4 100644
--- a/src/test/java/io/xdag/consensus/SyncTest.java
+++ b/src/test/java/io/xdag/consensus/SyncTest.java
@@ -325,7 +325,7 @@ public Kernel createKernel(TemporaryFolder root, boolean isNewVersion, int forkH
KeyPair key = KeyPair.create(SampleKeys.SRIVATE_KEY, Sign.CURVE, Sign.CURVE_NAME);
wallet.setAccounts(Collections.singletonList(key));
- Kernel kernel = new Kernel(config);
+ Kernel kernel = new Kernel(config, key);
DatabaseFactory dbFactory = new RocksdbFactory(config);
BlockStore blockStore = new BlockStoreImpl(
diff --git a/src/test/java/io/xdag/core/BlockchainTest.java b/src/test/java/io/xdag/core/BlockchainTest.java
index 3d1188590..df71c14b1 100644
--- a/src/test/java/io/xdag/core/BlockchainTest.java
+++ b/src/test/java/io/xdag/core/BlockchainTest.java
@@ -101,7 +101,7 @@ public void setUp() throws Exception {
wallet.setAccounts(Collections.singletonList(key));
wallet.flush();
- kernel = new Kernel(config);
+ kernel = new Kernel(config, key);
dbFactory = new RocksdbFactory(config);
BlockStore blockStore = new BlockStoreImpl(
diff --git a/src/test/java/io/xdag/core/ExtraBlockTest.java b/src/test/java/io/xdag/core/ExtraBlockTest.java
index ac5067098..bfe836c1f 100644
--- a/src/test/java/io/xdag/core/ExtraBlockTest.java
+++ b/src/test/java/io/xdag/core/ExtraBlockTest.java
@@ -86,7 +86,7 @@ public void setUp() throws Exception {
wallet.setAccounts(Collections.singletonList(key));
wallet.flush();
- kernel = new Kernel(config);
+ kernel = new Kernel(config, key);
dbFactory = new RocksdbFactory(config);
BlockStore blockStore = new BlockStoreImpl(
@@ -236,7 +236,7 @@ public void startCheckMain(long period) {
public void checkOrphan() {
long nblk = this.getXdagStats().nnoref / 11;
while (nblk-- > 0) {
- Block linkBlock = createNewBlock(null, null, false, kernel.getConfig().getPoolSpec().getPoolTag());
+ Block linkBlock = createNewBlock(null, null, false, kernel.getConfig().getNodeSpec().getNodeTag());
linkBlock.signOut(kernel.getWallet().getDefKey());
ImportResult result = this.tryToConnect(linkBlock);
assertTrue(result == IMPORTED_BEST || result == IMPORTED_NOT_BEST);
diff --git a/src/test/java/io/xdag/core/RandomXSyncTest.java b/src/test/java/io/xdag/core/RandomXSyncTest.java
index 003db690d..c42bca425 100644
--- a/src/test/java/io/xdag/core/RandomXSyncTest.java
+++ b/src/test/java/io/xdag/core/RandomXSyncTest.java
@@ -35,7 +35,7 @@
import io.xdag.db.BlockStore;
import io.xdag.db.OrphanBlockStore;
import io.xdag.db.rocksdb.*;
-import io.xdag.mine.randomx.RandomX;
+import io.xdag.crypto.RandomX;
import io.xdag.utils.XdagTime;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
@@ -192,7 +192,7 @@ public Kernel createKernel(TemporaryFolder root) throws Exception {
KeyPair key = KeyPair.create(SampleKeys.SRIVATE_KEY, Sign.CURVE, Sign.CURVE_NAME);
wallet.setAccounts(Collections.singletonList(key));
- Kernel kernel = new Kernel(config);
+ Kernel kernel = new Kernel(config, key);
DatabaseFactory dbFactory = new RocksdbFactory(config);
BlockStore blockStore = new BlockStoreImpl(
diff --git a/src/test/java/io/xdag/core/RewardTest.java b/src/test/java/io/xdag/core/RewardTest.java
index b23fa203e..2f23a4327 100644
--- a/src/test/java/io/xdag/core/RewardTest.java
+++ b/src/test/java/io/xdag/core/RewardTest.java
@@ -35,7 +35,7 @@
import io.xdag.db.BlockStore;
import io.xdag.db.OrphanBlockStore;
import io.xdag.db.rocksdb.*;
-import io.xdag.mine.randomx.RandomX;
+import io.xdag.crypto.RandomX;
import io.xdag.utils.XdagTime;
import org.apache.tuweni.bytes.Bytes32;
import org.hyperledger.besu.crypto.KeyPair;
@@ -84,7 +84,7 @@ public void setUp() throws Exception {
wallet.setAccounts(Collections.singletonList(key));
wallet.flush();
- kernel = new Kernel(config);
+ kernel = new Kernel(config, key);
dbFactory = new RocksdbFactory(config);
BlockStore blockStore = new BlockStoreImpl(
diff --git a/src/test/java/io/xdag/crypto/DnetKeysTest.java b/src/test/java/io/xdag/crypto/DnetKeysTest.java
deleted file mode 100644
index 683a4cb3e..000000000
--- a/src/test/java/io/xdag/crypto/DnetKeysTest.java
+++ /dev/null
@@ -1,82 +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.crypto;
-
-import static org.junit.Assert.assertEquals;
-
-import io.xdag.config.Config;
-import io.xdag.config.DevnetConfig;
-import java.io.File;
-import java.io.FileInputStream;
-import java.util.Objects;
-import org.apache.commons.io.IOUtils;
-import org.junit.Before;
-import org.junit.Test;
-
-public class DnetKeysTest {
-
- public final String cWord = "cdeee61f60df6185f5b90a95b00f4fe70dd2675df2150d777778780025f6947a3581f329cfd393ab042080e5e7f1bd75cd5877477550bebee9e7d09b92766b9c9a266793a646ee9fe0a6f1b66f36b88bd386ff302abe8492b8b63d2806db22bcc2cf420e7a5087374827fdb9cddae4d6581b11d60640a029dce9ff5050b46a9a991f6621ef9c3c1ff7c57800175f95f9c703f0c00ac123c88400bdc0c7d9060630b2919e49e3531e993fbb87b644a8013ded2ee60020c457b97270169e0de67a0279ad8de6230d5b455d95fd4997b3c2e65d681a8a7cc4c11d25bb159894556556c876f633619d21347a1c6458753033c5432670a6810e79b46bb549f48f733d7864e4c2cd7eac5a180b6823028658f4cce95c009578e86f4cb04bbf915a695138487784cc36922e676fa9ccad9dcaf2275e4a7255965fad83c49c4d6401119b70015e9baee5b68eed0cfb99a7214d150feac1c7ad81d7dca5d314c4fffeef9a090afed569f87a1d32512aa35d0ef6133f0e9eb1d3746bf5c16931bdf85fe85292eb934bff3dd6a506bae61d54bfac90e2b07bab4ad1dba15e2478a6ccfd5fd6e096c4be6ec47a117a99d9e051621d83f2def5ae90a6a437867a6225fd53570a4d3f0511730f2e2c3306c6d0b055bad55804f61f3ff2d4a38f00d31251187534903c2227183c787e3f42bc592b36f84ebe7a406b03d497765c15b9d2646244b8";
- public final String cPwd = "08d599aafccb4e64a97d31cc2e8204ac";
- public byte[] dnetKeys;
- public Config config;
-
- @Before
- public void setUp() throws Exception {
- config = new DevnetConfig();
- config.initKeys();
- String absolutePath = Objects.requireNonNull(DnetKeysTest.class.getClassLoader().getResource("dnet_keys.bin")).getPath();
- File keyFile = new File(absolutePath);
-
- dnetKeys = new byte[3072];
-
- IOUtils.read(new FileInputStream(keyFile), dnetKeys);
-
- byte[] prvKey = new byte[1024];
- byte[] pubKey = new byte[1024];
- byte[] encodedWord = new byte[512];
- byte[] word = new byte[512];
-
- System.arraycopy(dnetKeys, 0, prvKey, 0, 1024);
- System.arraycopy(dnetKeys, 1024, pubKey, 0, 1024);
- System.arraycopy(dnetKeys, 2048, encodedWord, 0, 512);
- System.arraycopy(dnetKeys, 2560, word, 0, 512);
- }
-
- @Test
- public void testInitKeys() {
-
- for (int i = 0; i < 3072; i++) {
- if (i < 1024) {
- assertEquals(dnetKeys[i], config.getNodeSpec().getXKeys().prv[i]);
- } else if (i < 2048) {
- assertEquals(dnetKeys[i], config.getNodeSpec().getXKeys().pub[i - 1024]);
- } else if (i < 2560) {
- assertEquals(dnetKeys[i], config.getNodeSpec().getXKeys().sect0_encoded[i - 2048]);
- } else {
- assertEquals(dnetKeys[i], config.getNodeSpec().getXKeys().sect0[i - 2560]);
- }
- }
- }
-}
diff --git a/src/test/java/io/xdag/crypto/Libp2pCryptoTest.java b/src/test/java/io/xdag/crypto/Libp2pCryptoTest.java
deleted file mode 100644
index f9f49ab34..000000000
--- a/src/test/java/io/xdag/crypto/Libp2pCryptoTest.java
+++ /dev/null
@@ -1,60 +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.crypto;
-
-import static org.junit.Assert.assertArrayEquals;
-
-import io.libp2p.core.crypto.PrivKey;
-import io.libp2p.core.crypto.PubKey;
-import io.libp2p.crypto.keys.Secp256k1Kt;
-import io.xdag.utils.Numeric;
-import org.apache.tuweni.bytes.Bytes;
-import org.junit.Before;
-import org.junit.Test;
-
-public class Libp2pCryptoTest {
-
- private PrivKey libp2pPrivKey;
- private PubKey libp2pPubKey;
-
- @Before
- public void setUp() {
- libp2pPrivKey = Secp256k1Kt
- .unmarshalSecp256k1PrivateKey(Numeric.hexStringToByteArray(SampleKeys.PRIVATE_KEY_STRING));
- libp2pPubKey = Secp256k1Kt
- .unmarshalSecp256k1PublicKey(Numeric.hexStringToByteArray(SampleKeys.PUBLIC_KEY_COMPRESS_STRING));
- }
-
- @Test
- public void testUnmarshalSecp256k1PrivateKey() {
- Bytes libp2pBytes = Bytes.wrap(libp2pPrivKey.raw()).slice(1, 33 -1);
- assertArrayEquals(libp2pBytes.toArray(), SampleKeys.KEY_PAIR.getPrivateKey().getEncoded());
- }
-
- @Test
- public void testUnmarshalSecp256k1PublicKey() {
- assertArrayEquals(libp2pPubKey.raw(), SampleKeys.KEY_PAIR.getPublicKey().asEcPoint(Sign.CURVE).getEncoded(true));
- }
-}
\ No newline at end of file
diff --git a/src/test/java/io/xdag/db/SnapshotStoreTest.java b/src/test/java/io/xdag/db/SnapshotStoreTest.java
index 85974519e..44c057d73 100644
--- a/src/test/java/io/xdag/db/SnapshotStoreTest.java
+++ b/src/test/java/io/xdag/db/SnapshotStoreTest.java
@@ -34,7 +34,7 @@
import io.xdag.crypto.SampleKeys;
import io.xdag.crypto.Sign;
import io.xdag.db.rocksdb.*;
-import io.xdag.mine.randomx.RandomX;
+import io.xdag.crypto.RandomX;
import io.xdag.utils.BasicUtils;
import io.xdag.utils.BytesUtils;
import io.xdag.utils.XdagTime;
@@ -122,7 +122,7 @@ public void setUp() throws Exception {
wallet.setAccounts(Collections.singletonList(key));
wallet.flush();
- kernel = new Kernel(config);
+ kernel = new Kernel(config, key);
dbFactory = new RocksdbFactory(config);
BlockStore blockStore = new BlockStoreImpl(
diff --git a/src/test/java/io/xdag/mine/miner/MinerConnectTest.java b/src/test/java/io/xdag/mine/miner/MinerConnectTest.java
deleted file mode 100644
index 243ef245d..000000000
--- a/src/test/java/io/xdag/mine/miner/MinerConnectTest.java
+++ /dev/null
@@ -1,177 +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.mine.miner;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.embedded.EmbeddedChannel;
-import io.xdag.Kernel;
-import io.xdag.Wallet;
-import io.xdag.config.Config;
-import io.xdag.config.DevnetConfig;
-import io.xdag.core.BlockchainImpl;
-import io.xdag.crypto.Keys;
-import io.xdag.crypto.SampleKeys;
-import io.xdag.crypto.Sign;
-import io.xdag.db.AddressStore;
-import io.xdag.db.BlockStore;
-import io.xdag.db.OrphanBlockStore;
-import io.xdag.db.rocksdb.*;
-import io.xdag.mine.MinerChannel;
-import io.xdag.mine.handler.MinerHandShakeHandler;
-import io.xdag.utils.BytesUtils;
-import org.apache.tuweni.bytes.Bytes32;
-import org.hyperledger.besu.crypto.KeyPair;
-import org.hyperledger.besu.crypto.SECPPrivateKey;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-
-import java.io.IOException;
-import java.math.BigInteger;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.util.Collections;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-public class MinerConnectTest {
-
- @Rule
- public TemporaryFolder root = new TemporaryFolder();
-
- Config config = new DevnetConfig();
- Wallet wallet;
- String pwd;
- Kernel kernel;
- DatabaseFactory dbFactory;
- AddressStore addressStore;
- MinerChannel channel;
- BlockchainImpl blockchain;
- BigInteger private_1 = new BigInteger("c85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4", 16);
- SECPPrivateKey secretkey_1 = SECPPrivateKey.create(private_1, Sign.CURVE_NAME);
- @Before
- public void setUp() throws Exception {
- KeyPair addrKey = KeyPair.create(secretkey_1, Sign.CURVE, Sign.CURVE_NAME);
- config.getNodeSpec().setStoreDir(root.newFolder().getAbsolutePath());
- config.getNodeSpec().setStoreBackupDir(root.newFolder().getAbsolutePath());
-
- pwd = "password";
- wallet = new Wallet(config);
- wallet.unlock(pwd);
- KeyPair key = KeyPair.create(SampleKeys.SRIVATE_KEY, Sign.CURVE, Sign.CURVE_NAME);
- wallet.setAccounts(Collections.singletonList(key));
- wallet.flush();
-
- kernel = new Kernel(config);
- dbFactory = new RocksdbFactory(config);
-
- BlockStore blockStore = new BlockStoreImpl(
- dbFactory.getDB(DatabaseName.INDEX),
- dbFactory.getDB(DatabaseName.TIME),
- dbFactory.getDB(DatabaseName.BLOCK),
- dbFactory.getDB(DatabaseName.TXHISTORY));
-
- blockStore.reset();
-
- AddressStore addressStore = new AddressStoreImpl(dbFactory.getDB(DatabaseName.ADDRESS));
-
- addressStore.reset();
-
- OrphanBlockStore orphanBlockStore = new OrphanBlockStoreImpl(dbFactory.getDB(DatabaseName.ORPHANIND));
- orphanBlockStore.reset();
-
- kernel.setBlockStore(blockStore);
- kernel.setOrphanBlockStore(orphanBlockStore);
- kernel.setWallet(wallet);
-
- blockchain = new BlockchainImpl(kernel);
-
- channel = new MinerChannel(kernel, false);
- }
-
- @After
- public void tearDown() throws IOException {
- wallet.delete();
- }
-
- @Test
- public void testMinerConnect()
- throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
-// Native.crypt_start();
- KeyPair key = Keys.createEcKeyPair();
- byte[] address = Keys.toBytesAddress(key);
- 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());
- }
-}
- class MockMinerHandshakeHandler extends MinerHandShakeHandler {
-
- public MockMinerHandshakeHandler(MinerChannel channel, Kernel kernel) {
- super(channel, kernel);
- }
-
- @Override
- public boolean initMiner(Bytes32 hash) {
- return true;
- }
-
- @Override
- protected void decode(ChannelHandlerContext ctx, ByteBuf in, List