links = block.getLinks();
+ for (Address link:links) {
+ if(link.getType() == XdagField.FieldType.XDAG_FIELD_IN || link.getType() == XdagField.FieldType.XDAG_FIELD_INPUT){
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public boolean filterOurLinkBlock(Bytes32 blockHashLow){
+ Block block = blockStore.getBlockByHash(blockHashLow,true);
+ if(!filterLinkBlock(block)){
+ return block.isOurs();
+ }else {
+ return true;
+ }
+ }
+
+}
diff --git a/src/main/java/io/xdag/core/ImportResult.java b/src/main/java/io/xdag/core/ImportResult.java
index c4b667ed0..3f816be85 100644
--- a/src/main/java/io/xdag/core/ImportResult.java
+++ b/src/main/java/io/xdag/core/ImportResult.java
@@ -26,6 +26,8 @@
import org.apache.tuweni.bytes.MutableBytes32;
+import lombok.Getter;
+
public enum ImportResult {
ERROR,
EXIST,
@@ -39,6 +41,7 @@ public enum ImportResult {
MutableBytes32 hashLow;
+ @Getter
String errorInfo;
public MutableBytes32 getHashlow() {
@@ -49,15 +52,8 @@ public void setHashlow(MutableBytes32 hashLow) {
this.hashLow = hashLow;
}
- public String getErrorInfo() {
- return errorInfo;
- }
-
public void setErrorInfo(String errorInfo) {
this.errorInfo = errorInfo;
}
- public boolean isNormal() {
- return this == IMPORTED_NOT_BEST || this == IMPORTED_BEST || this == EXIST || this == IMPORTED_EXTRA || this == IN_MEM;
- }
}
diff --git a/src/main/java/io/xdag/core/PreBlockInfo.java b/src/main/java/io/xdag/core/PreBlockInfo.java
index bbb250557..e58c3914b 100644
--- a/src/main/java/io/xdag/core/PreBlockInfo.java
+++ b/src/main/java/io/xdag/core/PreBlockInfo.java
@@ -42,7 +42,7 @@ public class PreBlockInfo {
private byte[] remark;
private byte[] hash;
private byte[] hashlow;
- private UInt64 amount;
+ private XAmount amount;
private long timestamp;
// snapshot
diff --git a/src/main/java/io/xdag/core/SnapshotInfo.java b/src/main/java/io/xdag/core/SnapshotInfo.java
index f72a5a2af..b2197df3f 100644
--- a/src/main/java/io/xdag/core/SnapshotInfo.java
+++ b/src/main/java/io/xdag/core/SnapshotInfo.java
@@ -24,9 +24,12 @@
package io.xdag.core;
import java.util.Arrays;
-import lombok.Data;
-@Data
+import lombok.Getter;
+import lombok.Setter;
+
+@Getter
+@Setter
public class SnapshotInfo {
protected boolean type; // true PUBKEY false BLOCK_DATA
diff --git a/src/main/java/io/xdag/core/SnapshotUnit.java b/src/main/java/io/xdag/core/SnapshotUnit.java
deleted file mode 100644
index c9d154e1b..000000000
--- a/src/main/java/io/xdag/core/SnapshotUnit.java
+++ /dev/null
@@ -1,122 +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.core;
-
-import static io.xdag.utils.BasicUtils.hash2Address;
-
-import java.math.BigInteger;
-import lombok.Data;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.tuweni.bytes.Bytes;
-import org.apache.tuweni.bytes.Bytes32;
-import org.apache.tuweni.units.bigints.UInt64;
-
-@Data
-@Slf4j
-public class SnapshotUnit {
-
- protected byte[] pubkey;
- protected SnapshotBalanceData balanceData;
- // data means block data
- protected byte[] data;
- protected boolean hasPubkey = false;
- protected int type;
- protected int keyIndex = -1;
- protected byte[] hash;
-
- public SnapshotUnit() {
-
- }
-
- public SnapshotUnit(byte[] pubkey, SnapshotBalanceData balanceData, byte[] data, byte[] hash) {
- if (pubkey == null && data != null) {
- this.type = 0; //BI_DATA_BALANCE;
- } else if (pubkey != null && balanceData != null) {
- this.type = 1; //Type.BI_PUBKEY_BALANCE;
- } else {
- this.type = 2; //Type.BI_PUBKEY;
- }
- this.pubkey = pubkey;
- this.balanceData = balanceData;
- this.data = data;
- this.hash = hash;
- }
-
- public SnapshotUnit(byte[] pubkey, SnapshotBalanceData balanceData, byte[] data, byte[] hash, int keyIndex) {
- if (pubkey == null && data != null) {
- this.type = 0; //BI_DATA_BALANCE;
- } else if (pubkey != null && balanceData != null) {
- this.type = 1; //Type.BI_PUBKEY_BALANCE;
- } else {
- this.type = 2; //Type.BI_PUBKEY;
- }
- this.pubkey = pubkey;
- this.balanceData = balanceData;
- this.data = data;
- this.hash = hash;
- this.keyIndex = keyIndex;
- }
-
- public static BlockInfo trasferToBlockInfo(SnapshotUnit snapshotUnit) {
- BlockInfo blockInfo = new BlockInfo();
- blockInfo.setDifficulty(BigInteger.ZERO);
- blockInfo.setFlags(snapshotUnit.getBalanceData().flags);
- if (snapshotUnit.type == 2) {
- blockInfo.setAmount(XAmount.ZERO);
- blockInfo.setTimestamp(0);
- } else {
- UInt64 u64v = UInt64.valueOf(snapshotUnit.getBalanceData().getAmount());
- blockInfo.setAmount(XAmount.ofXAmount(u64v.toLong()));
- blockInfo.setTimestamp(snapshotUnit.getBalanceData().getTime());
- }
- blockInfo.setHash(snapshotUnit.getHash());
- byte[] hashLow = new byte[32];
- System.arraycopy(snapshotUnit.getHash(), 8, hashLow, 8, 24);
- blockInfo.setHashlow(hashLow);
- blockInfo.setSnapshot(true);
- if (snapshotUnit.type == 0) {
- blockInfo.setSnapshotInfo(new SnapshotInfo(false, snapshotUnit.getData()));
- } else {
- blockInfo.setSnapshotInfo(new SnapshotInfo(true, snapshotUnit.getPubkey()));
- }
- return blockInfo;
- }
-
- public boolean hasPubkey() {
- return hasPubkey;
- }
-
- public boolean hasData() {
- return data != null;
- }
-
- @Override
- public String toString() {
- return "SnapshotUnit{" +
- "pubkey=" + (pubkey == null ? null : Bytes.wrap(pubkey)) +
- ", balanceData=" + balanceData +
- ", hash=" + hash2Address(Bytes32.wrap(hash)) +
- '}';
- }
-}
diff --git a/src/main/java/io/xdag/core/TxHistory.java b/src/main/java/io/xdag/core/TxHistory.java
index 5a86ca631..d28a1a87e 100644
--- a/src/main/java/io/xdag/core/TxHistory.java
+++ b/src/main/java/io/xdag/core/TxHistory.java
@@ -23,13 +23,13 @@
*/
package io.xdag.core;
+import lombok.Getter;
+import lombok.Setter;
+
import static io.xdag.utils.BasicUtils.hash2Address;
import static io.xdag.utils.BasicUtils.hash2byte;
import static io.xdag.utils.WalletUtils.toBase58;
-import lombok.Getter;
-import lombok.Setter;
-
@Getter
@Setter
public class TxHistory {
diff --git a/src/main/java/io/xdag/core/XdagBlock.java b/src/main/java/io/xdag/core/XdagBlock.java
index 7724e7418..5f1aee1d5 100644
--- a/src/main/java/io/xdag/core/XdagBlock.java
+++ b/src/main/java/io/xdag/core/XdagBlock.java
@@ -30,6 +30,8 @@
import org.apache.tuweni.bytes.MutableBytes;
import org.apache.tuweni.bytes.MutableBytes32;
+import lombok.Getter;
+
public class XdagBlock {
public static final int XDAG_BLOCK_FIELDS = 16;
@@ -39,6 +41,11 @@ public class XdagBlock {
* data 以添加签名
*/
private MutableBytes data;
+ /**
+ * -- GETTER --
+ * 获取区块sums*
+ */
+ @Getter
private long sum;
private XdagField[] fields;
@@ -101,10 +108,4 @@ public MutableBytes getData() {
return data;
}
- /**
- * 获取区块sums*
- */
- public long getSum() {
- return sum;
- }
}
diff --git a/src/main/java/io/xdag/core/XdagField.java b/src/main/java/io/xdag/core/XdagField.java
index 19c3ba091..f3a016190 100644
--- a/src/main/java/io/xdag/core/XdagField.java
+++ b/src/main/java/io/xdag/core/XdagField.java
@@ -24,13 +24,14 @@
package io.xdag.core;
-import java.nio.ByteOrder;
-import java.util.HashMap;
-import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import org.apache.tuweni.bytes.MutableBytes;
+import java.nio.ByteOrder;
+import java.util.HashMap;
+import java.util.Map;
+
public class XdagField implements Cloneable {
@Getter
@@ -92,8 +93,8 @@ public enum FieldType {
/***
*new tx type
*/
- XDAG_FIELD_INPUT(0x0C),
- XDAG_FIELD_OUTPUT(0x0D),
+ XDAG_FIELD_INPUT(0x0C),//12
+ XDAG_FIELD_OUTPUT(0x0D),//13
XDAG_FIELD_RESERVE5(0x0E),
XDAG_FIELD_RESERVE6(0x0F);
diff --git a/src/main/java/io/xdag/core/XdagStats.java b/src/main/java/io/xdag/core/XdagStats.java
index 12891b89a..843c73cab 100644
--- a/src/main/java/io/xdag/core/XdagStats.java
+++ b/src/main/java/io/xdag/core/XdagStats.java
@@ -97,10 +97,6 @@ public void update(XdagStats remoteXdagStats) {
}
}
- public BigInteger getMaxdifficulty() {
- return maxdifficulty;
- }
-
public void updateMaxDiff(BigInteger maxdifficulty) {
if (this.getMaxdifficulty().compareTo(maxdifficulty) < 0) {
this.maxdifficulty = maxdifficulty;
diff --git a/src/main/java/io/xdag/crypto/Base58.java b/src/main/java/io/xdag/crypto/Base58.java
index 83f1c045d..b115b4f82 100644
--- a/src/main/java/io/xdag/crypto/Base58.java
+++ b/src/main/java/io/xdag/crypto/Base58.java
@@ -81,7 +81,7 @@ public static String encodeChecked(byte[] payload) {
public static byte[] decode(String input) throws AddressFormatException {
- if (input.length() == 0) {
+ if (input.isEmpty()) {
return new byte[0];
}
// Convert the base58-encoded ASCII chars to a base58 byte sequence (base58 digits).
@@ -146,15 +146,6 @@ public static boolean checkAddress(String input) {
return Arrays.equals(checksum, actualChecksum);
}
- public static boolean checkBytes24(byte[] data) {
- if (data.length != 24) return false;
- byte[] data20 = Arrays.copyOfRange(data, 0, data.length - 4);
- byte[] checksum = Arrays.copyOfRange(data, data.length - 4, data.length);
- byte[] actualChecksum = Arrays.copyOfRange(Hash.hashTwice(data20), 0, 4);
- return Arrays.equals(checksum, actualChecksum);
- }
-
-
private static byte divmod(byte[] number, int firstDigit, int base, int divisor) {
// this is just long division which accounts for the base of the input digits
int remainder = 0;
diff --git a/src/main/java/io/xdag/crypto/Bip32ECKeyPair.java b/src/main/java/io/xdag/crypto/Bip32ECKeyPair.java
index ba2496b21..1da1c80d1 100644
--- a/src/main/java/io/xdag/crypto/Bip32ECKeyPair.java
+++ b/src/main/java/io/xdag/crypto/Bip32ECKeyPair.java
@@ -51,9 +51,13 @@ public class Bip32ECKeyPair {
public static final int HARDENED_BIT = 0x80000000;
private final boolean parentHasPrivate;
+ @Getter
private final int childNumber;
+ @Getter
private final int depth;
+ @Getter
private final byte[] chainCode;
+ @Getter
private final int parentFingerprint;
private final KeyPair keyPair;
@@ -156,22 +160,6 @@ private int getFingerprint() {
return id[3] & 0xFF | (id[2] & 0xFF) << 8 | (id[1] & 0xFF) << 16 | (id[0] & 0xFF) << 24;
}
- public int getDepth() {
- return depth;
- }
-
- public int getParentFingerprint() {
- return parentFingerprint;
- }
-
- public byte[] getChainCode() {
- return chainCode;
- }
-
- public int getChildNumber() {
- return childNumber;
- }
-
private byte[] getIdentifier() {
return sha256hash160(Bytes.wrap(getPublicKeyPoint().getEncoded(true)));
}
diff --git a/src/main/java/io/xdag/crypto/Keys.java b/src/main/java/io/xdag/crypto/Keys.java
index 04e9c2900..02bb7f8ae 100644
--- a/src/main/java/io/xdag/crypto/Keys.java
+++ b/src/main/java/io/xdag/crypto/Keys.java
@@ -24,8 +24,6 @@
package io.xdag.crypto;
-import static io.xdag.crypto.SecureRandomUtils.secureRandom;
-
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
@@ -37,6 +35,7 @@
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.hyperledger.besu.crypto.KeyPair;
import org.hyperledger.besu.crypto.SECPPublicKey;
+import org.hyperledger.besu.crypto.SecureRandomProvider;
import org.hyperledger.besu.crypto.SignatureAlgorithm;
/**
@@ -48,9 +47,6 @@ public class Keys {
public static final String PROVIDER = BouncyCastleProvider.PROVIDER_NAME;
public static final String CURVE_NAME = "secp256k1";
- public static final int PUBLIC_KEY_SIZE = 64;
- static final int PUBLIC_KEY_LENGTH_IN_HEX = PUBLIC_KEY_SIZE << 1;
-
static {
if (Security.getProvider(PROVIDER) == null) {
Security.addProvider(new BouncyCastleProvider());
@@ -70,7 +66,7 @@ private Keys() {
static KeyPair createSecp256k1KeyPair()
throws NoSuchProviderException, NoSuchAlgorithmException,
InvalidAlgorithmParameterException {
- return createSecp256k1KeyPair(secureRandom());
+ return createSecp256k1KeyPair(SecureRandomProvider.publicSecureRandom());
}
static KeyPair createSecp256k1KeyPair(SecureRandom random)
diff --git a/src/main/java/io/xdag/crypto/LinuxSecureRandom.java b/src/main/java/io/xdag/crypto/LinuxSecureRandom.java
deleted file mode 100644
index 28e716fd4..000000000
--- a/src/main/java/io/xdag/crypto/LinuxSecureRandom.java
+++ /dev/null
@@ -1,118 +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 java.io.DataInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.security.Provider;
-import java.security.SecureRandomSpi;
-import java.security.Security;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Implementation from BitcoinJ
- * implementation
- *
- * A SecureRandom implementation that is able to override the standard JVM provided
- * implementation, and which simply serves random numbers by reading /dev/urandom. That is, it
- * delegates to the kernel on UNIX systems and is unusable on other platforms. Attempts to manually
- * set the seed are ignored. There is no difference between seed bytes and non-seed bytes, they are
- * all from the same source.
- */
-public class LinuxSecureRandom extends SecureRandomSpi {
-
- private static final FileInputStream urandom;
- private static final Logger log = LoggerFactory.getLogger(LinuxSecureRandom.class);
-
- static {
- try {
- File file = new File("/dev/urandom");
- // This stream is deliberately leaked.
- urandom = new FileInputStream(file);
- if (urandom.read() == -1) {
- throw new RuntimeException("/dev/urandom not readable?");
- }
- // Now override the default SecureRandom implementation with this one.
- int position = Security.insertProviderAt(new LinuxSecureRandomProvider(), 1);
-
- if (position != -1) {
- log.info("Secure randomness will be read from {} only.", file);
- } else {
- log.info("Randomness is already secure.");
- }
- } catch (FileNotFoundException e) {
- // Should never happen.
- log.error("/dev/urandom does not appear to exist or is not openable");
- throw new RuntimeException(e);
- } catch (IOException e) {
- log.error("/dev/urandom does not appear to be readable");
- throw new RuntimeException(e);
- }
- }
-
- private final DataInputStream dis;
-
- public LinuxSecureRandom() {
- // DataInputStream is not thread safe, so each random object has its own.
- dis = new DataInputStream(urandom);
- }
-
- @Override
- protected void engineSetSeed(byte[] bytes) {
- // Ignore.
- }
-
- @Override
- protected void engineNextBytes(byte[] bytes) {
- try {
- dis.readFully(bytes); // This will block until all the bytes can be read.
- } catch (IOException e) {
- throw new RuntimeException(e); // Fatal error. Do not attempt to recover from this.
- }
- }
-
- @Override
- protected byte[] engineGenerateSeed(int i) {
- byte[] bits = new byte[i];
- engineNextBytes(bits);
- return bits;
- }
-
- private static class LinuxSecureRandomProvider extends Provider {
-
- public LinuxSecureRandomProvider() {
- super(
- "LinuxSecureRandom",
- "1.0",
- "A Linux specific random number provider that uses /dev/urandom");
- put("SecureRandom.LinuxSecureRandom", LinuxSecureRandom.class.getName());
- }
- }
-}
diff --git a/src/main/java/io/xdag/mine/randomx/RandomX.java b/src/main/java/io/xdag/crypto/RandomX.java
similarity index 97%
rename from src/main/java/io/xdag/mine/randomx/RandomX.java
rename to src/main/java/io/xdag/crypto/RandomX.java
index eb2948559..840189cd5 100644
--- a/src/main/java/io/xdag/mine/randomx/RandomX.java
+++ b/src/main/java/io/xdag/crypto/RandomX.java
@@ -22,12 +22,30 @@
* THE SOFTWARE.
*/
-package io.xdag.mine.randomx;
+package io.xdag.crypto;
+
+import static io.xdag.config.RandomXConstants.RANDOMX_FORK_HEIGHT;
+import static io.xdag.config.RandomXConstants.RANDOMX_TESTNET_FORK_HEIGHT;
+import static io.xdag.config.RandomXConstants.SEEDHASH_EPOCH_BLOCKS;
+import static io.xdag.config.RandomXConstants.SEEDHASH_EPOCH_LAG;
+import static io.xdag.config.RandomXConstants.SEEDHASH_EPOCH_TESTNET_BLOCKS;
+import static io.xdag.config.RandomXConstants.SEEDHASH_EPOCH_TESTNET_LAG;
+import static io.xdag.config.RandomXConstants.XDAG_RANDOMX;
+import static io.xdag.utils.BytesUtils.bytesToPointer;
+import static io.xdag.utils.BytesUtils.equalBytes;
+
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+import org.apache.tuweni.bytes.Bytes;
+import org.apache.tuweni.bytes.Bytes32;
+import org.bouncycastle.util.Arrays;
+import org.bouncycastle.util.encoders.Hex;
import com.sun.jna.Memory;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
-import com.sun.jna.ptr.PointerByReference;
+
import io.xdag.config.Config;
import io.xdag.config.MainnetConfig;
import io.xdag.core.Block;
@@ -39,17 +57,6 @@
import io.xdag.utils.XdagTime;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
-import org.apache.tuweni.bytes.Bytes;
-import org.apache.tuweni.bytes.Bytes32;
-import org.bouncycastle.util.Arrays;
-import org.bouncycastle.util.encoders.Hex;
-
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-import static io.xdag.config.RandomXConstants.*;
-import static io.xdag.utils.BytesUtils.bytesToPointer;
-import static io.xdag.utils.BytesUtils.equalBytes;
@Slf4j
@@ -179,7 +186,7 @@ public void init() {
// 矿池初始化dataset
- public void randomXPoolInitDataset(PointerByReference rxCache, PointerByReference rxDataset) {
+ public void randomXPoolInitDataset(Pointer rxCache, Pointer rxDataset) {
RandomXJNA.INSTANCE.randomx_init_dataset(rxDataset, rxCache, new NativeLong(0), RandomXJNA.INSTANCE.randomx_dataset_item_count());
}
@@ -250,7 +257,7 @@ public byte[] randomXBlockHash(byte[] data, int dataSize, long blockTime) {
}
- public PointerByReference randomXUpdateVm(RandomXMemory randomXMemory, boolean isPoolVm) {
+ public Pointer randomXUpdateVm(RandomXMemory randomXMemory, boolean isPoolVm) {
if (isPoolVm) {
randomXMemory.poolVm = RandomXJNA.INSTANCE.randomx_create_vm(flags, randomXMemory.rxCache, randomXMemory.rxDataset);
return randomXMemory.poolVm;
diff --git a/src/main/java/io/xdag/mine/randomx/RandomXMemory.java b/src/main/java/io/xdag/crypto/RandomXMemory.java
similarity index 86%
rename from src/main/java/io/xdag/mine/randomx/RandomXMemory.java
rename to src/main/java/io/xdag/crypto/RandomXMemory.java
index 1b8b88a73..8887e9c69 100644
--- a/src/main/java/io/xdag/mine/randomx/RandomXMemory.java
+++ b/src/main/java/io/xdag/crypto/RandomXMemory.java
@@ -22,9 +22,10 @@
* THE SOFTWARE.
*/
-package io.xdag.mine.randomx;
+package io.xdag.crypto;
+
+import com.sun.jna.Pointer;
-import com.sun.jna.ptr.PointerByReference;
import lombok.Getter;
import lombok.Setter;
@@ -37,10 +38,10 @@ public class RandomXMemory {
protected long seedTime;
protected long switchTime;
protected int isSwitched;
- protected PointerByReference rxCache;
- protected PointerByReference rxDataset;
- protected PointerByReference poolVm;
- protected PointerByReference blockVm;
+ protected Pointer rxCache;
+ protected Pointer rxDataset;
+ protected Pointer poolVm;
+ protected Pointer blockVm;
public RandomXMemory() {
this.switchTime = -1;
diff --git a/src/main/java/io/xdag/crypto/SecureRandomUtils.java b/src/main/java/io/xdag/crypto/SecureRandomUtils.java
deleted file mode 100644
index 033186154..000000000
--- a/src/main/java/io/xdag/crypto/SecureRandomUtils.java
+++ /dev/null
@@ -1,58 +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 java.security.SecureRandom;
-
-public class SecureRandomUtils {
-
- private static final SecureRandom SECURE_RANDOM;
- // Taken from BitcoinJ implementation
- // https://github.com/bitcoinj/bitcoinj/blob/3cb1f6c6c589f84fe6e1fb56bf26d94cccc85429/core/src/main/java/org/bitcoinj/core/Utils.java#L573
- private static int isAndroid = -1;
-
- static {
- if (isAndroidRuntime()) {
- new LinuxSecureRandom();
- }
- SECURE_RANDOM = new SecureRandom();
- }
-
- private SecureRandomUtils() {
- }
-
- public static SecureRandom secureRandom() {
- return SECURE_RANDOM;
- }
-
- static boolean isAndroidRuntime() {
- if (isAndroid == -1) {
- final String runtime = System.getProperty("java.runtime.name");
- isAndroid = (runtime != null && runtime.equals("Android Runtime")) ? 1 : 0;
- }
- return isAndroid == 1;
- }
-
-}
diff --git a/src/main/java/io/xdag/crypto/Sign.java b/src/main/java/io/xdag/crypto/Sign.java
index 05dc4532a..525766efb 100644
--- a/src/main/java/io/xdag/crypto/Sign.java
+++ b/src/main/java/io/xdag/crypto/Sign.java
@@ -111,17 +111,6 @@ public static BigInteger publicFromPoint(byte[] bits) {
return new BigInteger(1, Arrays.copyOfRange(bits, 1, bits.length)); // remove prefix
}
- /**
- * Verify that the provided precondition holds true.
- *
- * @param assertionResult assertion value
- * @param errorMessage error message if precondition failure
- */
- public static void verifyPrecondition(boolean assertionResult, String errorMessage) {
- if (!assertionResult) {
- throw new RuntimeException(errorMessage);
- }
- }
public static SECPSignature toCanonical(SECPSignature signature) {
if(signature.getS().compareTo(HALF_CURVE_ORDER)>0){
return SECPSignature.create(signature.getR(), CURVE.getN().subtract(signature.getS()), (byte) 0, CURVE.getN());
diff --git a/src/main/java/io/xdag/db/OrphanBlockStore.java b/src/main/java/io/xdag/db/OrphanBlockStore.java
index 3664d2c5a..fd8f6f9ad 100644
--- a/src/main/java/io/xdag/db/OrphanBlockStore.java
+++ b/src/main/java/io/xdag/db/OrphanBlockStore.java
@@ -26,6 +26,8 @@
import io.xdag.core.Address;
import io.xdag.core.Block;
import java.util.List;
+
+import io.xdag.core.Filter;
import org.bouncycastle.util.encoders.Hex;
public interface OrphanBlockStore {
diff --git a/src/main/java/io/xdag/db/mysql/TransactionHistoryStoreImpl.java b/src/main/java/io/xdag/db/mysql/TransactionHistoryStoreImpl.java
index 524f0990b..230e275bc 100644
--- a/src/main/java/io/xdag/db/mysql/TransactionHistoryStoreImpl.java
+++ b/src/main/java/io/xdag/db/mysql/TransactionHistoryStoreImpl.java
@@ -40,6 +40,8 @@
import java.util.Date;
import java.util.List;
+import static io.xdag.config.Constants.MIN_GAS;
+import static io.xdag.core.XdagField.FieldType.XDAG_FIELD_INPUT;
import static io.xdag.utils.BasicUtils.hash2Address;
import static io.xdag.utils.BasicUtils.hash2byte;
import static io.xdag.utils.WalletUtils.checkAddress;
@@ -59,13 +61,18 @@ public class TransactionHistoryStoreImpl implements TransactionHistoryStore {
private static final String SQL_QUERY_TXHISTORY_COUNT_WITH_TIME = "select count(*) from t_transaction_history where faddress=? and ftime >=? and ftime <=?";
private static final int BLOCK_ADDRESS_FLAG = 0;
private static final int WALLET_ADDRESS_FLAG = 1;
-
private static final int DEFAULT_PAGE_SIZE = 100;
+ private static final int DEFAULT_CACHE_SIZE = 50000;
+ private final long TX_PAGE_SIZE_LIMIT;
private Connection connBatch = null;
private PreparedStatement pstmtBatch = null;
private int count = 0;
public static int totalPage = 1;
+ public TransactionHistoryStoreImpl(long txPageSizeLimit) {
+ this.TX_PAGE_SIZE_LIMIT = txPageSizeLimit;
+ }
+
@Override
public boolean saveTxHistory(TxHistory txHistory) {
Connection conn = null;
@@ -82,7 +89,8 @@ public boolean saveTxHistory(TxHistory txHistory) {
pstmt.setString(1, addr);
pstmt.setInt(2, address.getIsAddress() ? WALLET_ADDRESS_FLAG : BLOCK_ADDRESS_FLAG);
pstmt.setString(3, txHistory.getHash());
- pstmt.setBigDecimal(4, address.getAmount().toDecimal(9, XUnit.XDAG));
+ pstmt.setBigDecimal(4, address.getType().equals(XDAG_FIELD_INPUT) ? address.getAmount().subtract(MIN_GAS).toDecimal(9, XUnit.XDAG) :
+ address.getAmount().toDecimal(9, XUnit.XDAG));
pstmt.setInt(5, address.getType().asByte());
pstmt.setString(6, txHistory.getRemark() != null ? txHistory.getRemark().trim() : "");
pstmt.setTimestamp(7,
@@ -118,7 +126,8 @@ public boolean batchSaveTxHistory(TxHistory txHistory, int... cacheNum) {
pstmtBatch.setString(1, addr);
pstmtBatch.setInt(2, address.getIsAddress() ? WALLET_ADDRESS_FLAG : BLOCK_ADDRESS_FLAG);
pstmtBatch.setString(3, txHistory.getHash());
- pstmtBatch.setBigDecimal(4, address.getAmount().toDecimal(9, XUnit.XDAG));
+ pstmtBatch.setBigDecimal(4, address.getType().equals(XDAG_FIELD_INPUT) ? address.getAmount().subtract(MIN_GAS).toDecimal(9, XUnit.XDAG) :
+ address.getAmount().toDecimal(9, XUnit.XDAG));
pstmtBatch.setInt(5, address.getType().asByte());
pstmtBatch.setString(6, txHistory.getRemark() != null ? txHistory.getRemark().trim() : "");
pstmtBatch.setTimestamp(7,
@@ -126,7 +135,7 @@ public boolean batchSaveTxHistory(TxHistory txHistory, int... cacheNum) {
pstmtBatch.addBatch();
count++;
}
- if (count == (cacheNum.length == 0 ? 50000 : (cacheNum[0] + 1)) || txHistory == null) {
+ if (count == (cacheNum.length == 0 ? DEFAULT_CACHE_SIZE : (cacheNum[0] + 1)) || txHistory == null) {
if (pstmtBatch != null) {
pstmtBatch.executeBatch();
}
@@ -166,12 +175,13 @@ public List listTxHistoryByAddress(String address, int page, Object..
long start = new Date(0).getTime();
long end = System.currentTimeMillis();
switch (parameters.length) {
- case 0: break;
- case 1:
+ case 0 -> {
+ }
+ case 1 -> {
int pageSize = Integer.parseInt(parameters[0].toString());
- PAGE_SIZE = (pageSize > 0 && pageSize <= 500) ? pageSize : PAGE_SIZE;
- break;
- case 2:
+ PAGE_SIZE = (pageSize > 0 && pageSize <= TX_PAGE_SIZE_LIMIT) ? pageSize : PAGE_SIZE;
+ }
+ case 2 -> {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
start = sdf.parse(parameters[0].toString()).getTime();
@@ -180,8 +190,8 @@ public List listTxHistoryByAddress(String address, int page, Object..
start = Long.parseLong(parameters[0].toString());
end = Long.parseLong(parameters[1].toString());
}
- break;
- case 3:
+ }
+ case 3 -> {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
start = sdf.parse(parameters[0].toString()).getTime();
@@ -191,8 +201,10 @@ public List listTxHistoryByAddress(String address, int page, Object..
end = Long.parseLong(parameters[1].toString());
}
int page_size = Integer.parseInt(parameters[2].toString());
- PAGE_SIZE = (page_size > 0 && page_size <= 500) ? page_size : PAGE_SIZE;
- break;
+ PAGE_SIZE = (page_size > 0 && page_size <= TX_PAGE_SIZE_LIMIT) ? page_size : PAGE_SIZE;
+ }
+ default -> {
+ }
}
try {
conn = DruidUtils.getConnection();
diff --git a/src/main/java/io/xdag/db/rocksdb/OrphanBlockStoreImpl.java b/src/main/java/io/xdag/db/rocksdb/OrphanBlockStoreImpl.java
index 85b0ecf98..f1fb1bbc9 100644
--- a/src/main/java/io/xdag/db/rocksdb/OrphanBlockStoreImpl.java
+++ b/src/main/java/io/xdag/db/rocksdb/OrphanBlockStoreImpl.java
@@ -84,6 +84,13 @@ public List getOrphan(long num, long[] sendtime) {
addNum--;
res.add(new Address(Bytes32.wrap(an.getKey(), 1), XdagField.FieldType.XDAG_FIELD_OUT,false));
sendtime[1] = Math.max(sendtime[1],time);
+// Bytes32 blockHashLow = Bytes32.wrap(an.getKey(),1);
+// if(filter.filterOurLinkBlock(blockHashLow)){
+// addNum--;
+// //TODO:通过address 获取区块 遍历连接块是否都是output如果是 则为链接块 判断是否是自己的是才链接
+// res.add(new Address(blockHashLow, XdagField.FieldType.XDAG_FIELD_OUT,false));
+// sendtime[1] = Math.max(sendtime[1],time);
+// }
}
}
sendtime[1] = Math.min(sendtime[1]+1,sendtime[0]);
diff --git a/src/main/java/io/xdag/db/rocksdb/SnapshotStoreImpl.java b/src/main/java/io/xdag/db/rocksdb/SnapshotStoreImpl.java
index cc946236d..2abc638d7 100644
--- a/src/main/java/io/xdag/db/rocksdb/SnapshotStoreImpl.java
+++ b/src/main/java/io/xdag/db/rocksdb/SnapshotStoreImpl.java
@@ -39,6 +39,7 @@
import io.xdag.db.execption.SerializationException;
import io.xdag.utils.BasicUtils;
import io.xdag.utils.BytesUtils;
+import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
@@ -58,7 +59,6 @@
import static io.xdag.config.Constants.BI_OURS;
import static io.xdag.db.AddressStore.ADDRESS_SIZE;
-import static io.xdag.db.AddressStore.AMOUNT_SUM;
import static io.xdag.db.BlockStore.*;
import static io.xdag.utils.BasicUtils.compareAmountTo;
@@ -68,9 +68,13 @@ public class SnapshotStoreImpl implements SnapshotStore {
private final RocksdbKVSource snapshotSource;
private final Kryo kryo;
+ @Getter
private XAmount ourBalance = XAmount.ZERO;
+ @Getter
private XAmount allBalance = XAmount.ZERO;
+ @Getter
private long nextTime;
+ @Getter
private long height;
@@ -93,10 +97,10 @@ public void reset() {
public void setBlockInfo(BlockInfo blockInfo, PreBlockInfo preBlockInfo) {
blockInfo.setSnapshot(preBlockInfo.isSnapshot());
blockInfo.setSnapshotInfo(preBlockInfo.getSnapshotInfo());
- blockInfo.setFee(preBlockInfo.getFee());
+ blockInfo.setFee(XAmount.of(preBlockInfo.getFee()));
blockInfo.setHash(preBlockInfo.getHash());
blockInfo.setDifficulty(preBlockInfo.getDifficulty());
- blockInfo.setAmount(XAmount.ofXAmount(preBlockInfo.getAmount().toLong()));
+ blockInfo.setAmount(preBlockInfo.getAmount());
blockInfo.setHashlow(preBlockInfo.getHashlow());
blockInfo.setFlags(preBlockInfo.getFlags());
blockInfo.setHeight(preBlockInfo.getHeight());
@@ -231,6 +235,7 @@ public void saveSnapshotToIndex(BlockStore blockStore, TransactionHistoryStore t
blockStore.savePreSeed(iter.value());
}
}
+ System.out.println("amount in blocks: " + allBalance.toDecimal(9, XUnit.XDAG).toPlainString());
if (txHistoryStore != null) {
txHistoryStore.batchSaveTxHistory(null);
}
@@ -247,10 +252,6 @@ public void saveAddress(BlockStore blockStore, AddressStore addressStore, Transa
if (iter.key().length < 20) {
if (iter.key()[0] == ADDRESS_SIZE) {
addressStore.saveAddressSize(iter.value());
- } else if (iter.key()[0] == AMOUNT_SUM) {
- UInt64 u64v = UInt64.fromBytes(Bytes.wrap(iter.value()));
- addressStore.savaAmountSum(XAmount.ofXAmount(u64v.toLong()));
- allBalance = addressStore.getAllBalance();
}
} else {
byte[] address = iter.key();
@@ -262,6 +263,7 @@ public void saveAddress(BlockStore blockStore, AddressStore addressStore, Transa
ourBalance = ourBalance.add(balance);
}
}
+ allBalance = allBalance.add(balance); //calculate the address balance
addressStore.snapshotAddress(address, balance);
if (txHistoryStore != null) {
XdagField.FieldType fieldType = XdagField.FieldType.XDAG_FIELD_SNAPSHOT;
@@ -276,6 +278,9 @@ public void saveAddress(BlockStore blockStore, AddressStore addressStore, Transa
}
}
}
+ System.out.println("amount in address: " + allBalance.toDecimal(9, XUnit.XDAG).toPlainString());
+ //sava Address all Balance as AMOUNT_SUM
+ addressStore.savaAmountSum(allBalance);
}
}
@@ -289,23 +294,6 @@ public void save(RocksIterator iter, BlockInfo blockInfo) {
snapshotSource.put(iter.key(), value);
}
- public XAmount getOurBalance() {
- return this.ourBalance;
- }
-
- public XAmount getAllBalance() {
- return this.allBalance;
- }
-
- public long getNextTime() {
- return nextTime;
- }
-
- public long getHeight() {
- return height;
- }
-
-
public Object deserialize(final byte[] bytes, Class> type) throws DeserializationException {
synchronized (kryo) {
try {
diff --git a/src/main/java/io/xdag/mine/MinerChannel.java b/src/main/java/io/xdag/mine/MinerChannel.java
deleted file mode 100644
index e17dbf304..000000000
--- a/src/main/java/io/xdag/mine/MinerChannel.java
+++ /dev/null
@@ -1,414 +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;
-
-import static io.xdag.mine.miner.MinerStates.MINER_ACTIVE;
-
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelPipeline;
-import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
-import io.netty.handler.timeout.IdleStateHandler;
-import io.xdag.Kernel;
-import io.xdag.config.Config;
-import io.xdag.core.XAmount;
-import io.xdag.core.XdagField;
-import io.xdag.db.AddressStore;
-import io.xdag.db.BlockStore;
-import io.xdag.mine.handler.ConnectionLimitHandler;
-import io.xdag.mine.handler.Miner03;
-import io.xdag.mine.handler.MinerHandShakeHandler;
-import io.xdag.mine.handler.MinerMessageHandler;
-import io.xdag.mine.manager.MinerManager;
-import io.xdag.mine.message.MinerMessageFactory;
-import io.xdag.mine.miner.Miner;
-import io.xdag.mine.miner.MinerStates;
-import io.xdag.net.XdagVersion;
-import io.xdag.net.message.MessageFactory;
-import io.xdag.utils.BytesUtils;
-
-import java.net.InetSocketAddress;
-import java.nio.ByteOrder;
-import java.util.Date;
-import java.util.List;
-import java.util.Objects;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.atomic.AtomicLong;
-
-import io.xdag.utils.WalletUtils;
-import lombok.Getter;
-import lombok.Setter;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.tuweni.bytes.Bytes;
-import org.apache.tuweni.bytes.Bytes32;
-import org.apache.tuweni.bytes.MutableBytes32;
-
-@Slf4j
-@Getter
-public class MinerChannel {
-
- /**
- * 对应的是服务端的还是客户端的
- */
- private final boolean isServer;
- private final Kernel kernel;
- private final Config config;
- private final BlockStore blockStore;
- private final AddressStore addressStore;
- private final MinerManager minerManager;
- /**
- * 存放的是连续16个任务本地计算的最大难度 每一轮放的都是最小hash 计算出来的diffs
- */
- private final List maxDiffs = new CopyOnWriteArrayList<>();
- /**
- * 记录的是出入站的消息
- */
- private final StatHandle inBound;
- private final StatHandle outBound;
- /**
- * 这个channel是否是活跃的 仅当连接成功后变为true
- */
- @Getter
- @Setter
- private boolean isActive;
- /**
- * 记录对应的矿工对象
- */
- @Getter
- @Setter
- private Miner miner;
- /**
- * 当前接受的最近的任务编号
- */
- @Getter
- @Setter
- private long taskIndex;
- private long taskTime;
- /**
- * 每一轮任务分享share的次数 接收一次加1
- */
- @Getter
- @Setter
- private int sharesCounts;
- /**
- * 上一次发送shares 的时间 接收到shares 的时候会更新
- */
- @Getter
- @Setter
- private long lastSharesTime;
- /**
- * 连接成功的时间 暂时只适用于打印 没有其他用途
- */
- @Getter
- private Date connectTime;
- /**
- * 如果是服务端端 则保存的是远程连接的客户端地址 若是客户端,则保存的是本地的地址
- */
- @Getter
- @Setter
- private InetSocketAddress inetAddress;
- /**
- * 发起连接的账户的地址块
- */
- @Getter
- @Setter
- private Bytes32 accountAddressHash;
- @Getter
- @Setter
- private byte[] accountAddressHashByte;
- /**
- * 保存上一轮的share
- */
- @Getter
- @Setter
- private byte[] share = new byte[32];
- /**
- * 跟新为当前最小的hash 每收到一个share 后跟新
- */
- @Getter
- @Setter
- private byte[] lastMinHash = new byte[32];
- /**
- * 记录prevDiff的次数 实际上类似于进行了多少次计算
- */
- @Getter
- @Setter
- private int prevDiffCounts;
- @Setter
- private ChannelHandlerContext ctx;
- /**
- * 记录的是当前任务所有难度之和,每当接收到一个新的nonce 会更新这个
- */
- @Getter
- @Setter
- private double prevDiff;
- @Getter
- @Setter
- private double meanLogDiff;
- @Getter
- @Setter
- private int boundedTaskCounter;
- /**
- * 保存这个channel 最后的计算的hash
- */
- @Getter
- @Setter
- private Bytes32 minHash;
- /**
- * 各种处理器*
- */
- private MinerHandShakeHandler minerHandShakeHandler;
- private MinerMessageHandler minerMessageHandler;
- private Miner03 miner03;
-
-
-
- /**
- * 矿工名
- */
- @Getter
- @Setter
- private String workerName = StringUtils.EMPTY;
-
- /**
- * 初始化 同时需要判断是服务器端还是客户端
- */
- public MinerChannel(Kernel kernel, boolean isServer) {
- this.kernel = kernel;
- this.config = kernel.getConfig();
- this.inBound = new StatHandle();
- this.outBound = new StatHandle();
- this.isServer = isServer;
-
- this.blockStore = kernel.getBlockStore();
- this.addressStore = kernel.getAddressStore();
- this.minerManager = kernel.getMinerManager();
-
- // 容器的初始化
- for (int i = 0; i < 16; i++) {
- maxDiffs.add(0.0);
- }
- }
-
- /**
- * 初始化一个channel 并且注册到管道上
- *
- * @param pipeline 注册的管道
- * @param inetSocketAddress 若是矿池开启的channel 则对应的是远程矿工地址,若为客户端开启,则为本地地址
- */
- public void init(ChannelPipeline pipeline, InetSocketAddress inetSocketAddress) {
- this.inetAddress = inetSocketAddress;
-
- // 给管道添加各种消息处理器
- this.minerMessageHandler = new MinerMessageHandler(this);
- this.miner03 = new Miner03(this, kernel);
-
- if (isServer) {
- pipeline.addLast("connectionLimitHandler", new ConnectionLimitHandler(kernel.getConfig().getPoolSpec().getMaxConnectPerIp()));
- }
-
- // 仅服务器端需要这个握手协议 接受
- this.minerHandShakeHandler = new MinerHandShakeHandler(this, kernel);
- pipeline.addLast("LengthFieldBasedFrameDecoder",new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN,1024*1024,0,4,0,4,true));
- pipeline.addLast("MinerHandShake", minerHandShakeHandler);
- }
-
- /**
- * 根据版本创建一个信息工厂
- */
- private MessageFactory createMinerMessageFactory(XdagVersion version) {
- return switch (version) {
- case V03 -> new MinerMessageFactory();
- };
- }
-
- /**
- * Active Channel and Add Handler 为管道添加各种处理器
- */
- public void activateHandler(ChannelHandlerContext ctx, XdagVersion version) {
- log.debug("Activate Handler");
- MessageFactory messageFactory = createMinerMessageFactory(version);
- minerMessageHandler.setMessageFactory(messageFactory);
- ctx.pipeline().addLast("MinerMessageHandler", minerMessageHandler);
- ctx.pipeline().addLast(new IdleStateHandler(64, 0, 0));
- ctx.pipeline().addLast("Miner03Handler", miner03);
- }
-
- public boolean initMiner(Bytes32 accountAddressHash) {
- this.accountAddressHash = accountAddressHash;
- this.accountAddressHashByte = BytesUtils.byte32ToArray(accountAddressHash.mutableCopy());
- String addrHexStr = WalletUtils.toBase58(accountAddressHashByte);
- log.debug("Init A Miner:" + addrHexStr);
- // 判断这个矿工是否已经存在了
- if (minerManager !=null && minerManager.getActivateMiners().containsKey(accountAddressHash)) {
- log.debug("Miner:{} already exists", addrHexStr);
- this.miner = minerManager.getActivateMiners().get(accountAddressHash);
- if (miner !=null && miner.getConnChannelCounts() < config.getPoolSpec().getMaxMinerPerAccount()) {
- this.miner = minerManager.getActivateMiners().get(accountAddressHash);
- this.miner.putChannel(this.inetAddress, this);
- this.miner.setMinerStates(MINER_ACTIVE);
- return true;
- } else {
- log.debug("Too many connections to the same miner:{}", addrHexStr);
- return false;
- }
- } else {
- this.miner = new Miner(accountAddressHash);
- Objects.requireNonNull(minerManager).getActivateMiners().put(accountAddressHash, miner);
- this.miner.putChannel(this.inetAddress, this);
- this.miner.setMinerStates(MINER_ACTIVE);
- return true;
- }
- }
-
- public void onDisconnect() {
- miner03.dropConnection();
- }
-
- public StatHandle getInBound() {
- return inBound;
- }
-
- public StatHandle getOutBound() {
- return outBound;
- }
-
- public boolean isServer() {
- return isServer;
- }
-
- public void setIsActivate(boolean bool) {
- isActive = bool;
- }
-
- public void setConnectTime(Date time) {
- connectTime = time;
- }
-
- public void addShareCounts(int i) {
- sharesCounts += i;
- }
-
- /**
- * 矿池发送给矿工的任务
- */
- public void sendTaskToMiner(XdagField[] fields) {
- miner03.sendMessage(Bytes.wrap(fields[0].getData(), fields[1].getData()));
- }
-
- /**
- * 矿池发送余额给矿工
- */
- public void sendBalance() {
- XAmount amount = XAmount.ZERO;
- if (!addressStore.addressIsExist(accountAddressHashByte)){
- log.debug("Can't found address,{}", WalletUtils.toBase58(accountAddressHashByte));
- } else {
- amount = addressStore.getBalanceByAddress(accountAddressHashByte);
- }
- MutableBytes32 data = MutableBytes32.create();
- data.set(0, amount.toXAmount().toBytes());
- data.set(8, Bytes.wrap(accountAddressHashByte));
- log.debug("update miner balance {}", data.toHexString());
- miner03.sendMessage(data);
- }
-
- public long getTaskTime() {
- return taskTime;
- }
-
- public void setTaskTime(long taskTime) {
- this.taskTime = taskTime;
- }
-
- public void addPrevDiff(double i) {
- prevDiff += i;
- }
-
- public void addPrevDiffCounts() {
- this.prevDiffCounts++;
- }
-
- public void addMaxDiffs(int index, double diff) {
- maxDiffs.set(index, diff);
- }
-
- public double getMaxDiffs(int index) {
- return maxDiffs.get(index);
- }
-
- public void addBoundedTaskCounter() {
- this.boundedTaskCounter++;
- }
-
- @Override
- public String toString() {
- return "";
- }
-
- public void dropConnection() {
- miner03.dropConnection();
- }
-
- public void updateMiner(Miner miner) {
- this.miner = miner;
- this.accountAddressHash = miner.getAddressHash();
- miner.putChannel(this.getInetAddress(), this);
- miner.setMinerStates(MinerStates.MINER_ACTIVE);
- }
-
- public String getAddressHash(){
- if(this.miner == null){
- return StringUtils.EMPTY;
- }else {
- return WalletUtils.toBase58(accountAddressHashByte);
- }
- }
-
- /**
- * 内部类 用于计算这个channel 的入栈和出战信息
- */
- public static class StatHandle {
-
- AtomicLong count = new AtomicLong(0);
-
- public void add() {
- count.getAndIncrement();
- }
-
- public void add(long delta) {
- count.addAndGet(delta);
- }
-
- public long get() {
- return count.get();
- }
-
- @Override
- public String toString() {
- return count.toString();
- }
- }
-}
diff --git a/src/main/java/io/xdag/mine/MinerChannelInitializer.java b/src/main/java/io/xdag/mine/MinerChannelInitializer.java
deleted file mode 100644
index 144b410d6..000000000
--- a/src/main/java/io/xdag/mine/MinerChannelInitializer.java
+++ /dev/null
@@ -1,67 +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;
-
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelInitializer;
-import io.netty.channel.ChannelOption;
-import io.netty.channel.FixedRecvByteBufAllocator;
-import io.xdag.Kernel;
-import java.net.InetSocketAddress;
-import java.util.concurrent.atomic.AtomicInteger;
-import lombok.extern.slf4j.Slf4j;
-
-@Slf4j
-public class MinerChannelInitializer extends ChannelInitializer {
-
- private final Kernel kernel;
- private final boolean isServer;
-
- public MinerChannelInitializer(Kernel kernel, boolean isServer) {
- this.kernel = kernel;
- this.isServer = isServer;
- }
-
- @Override
- protected void initChannel(Channel ch) {
- AtomicInteger channelsAccount = kernel.getChannelsAccount();
- int channelLimit = kernel.getConfig().getPoolSpec().getGlobalMinerChannelLimit();
- if (channelsAccount.get() >= channelLimit) {
- ch.close();
- log.warn("Pool Miner Channel Limit {}, Too Many Channels In This Pool.", channelLimit);
- return;
- }
- InetSocketAddress channelAddress = isServer
- ? (InetSocketAddress)ch.remoteAddress()
- : new InetSocketAddress(
- kernel.getConfig().getPoolSpec().getPoolIp(), kernel.getConfig().getPoolSpec().getPoolPort());
- MinerChannel minerChannel = new MinerChannel(kernel, isServer);
- minerChannel.init(ch.pipeline(), channelAddress);
- ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(256 * 1024));
- ch.config().setOption(ChannelOption.TCP_NODELAY, true);
- ch.config().setOption(ChannelOption.SO_RCVBUF, 256 * 1024);
- ch.config().setOption(ChannelOption.SO_BACKLOG, 1024);
- }
-}
diff --git a/src/main/java/io/xdag/mine/MinerServer.java b/src/main/java/io/xdag/mine/MinerServer.java
deleted file mode 100644
index 8ea3aee40..000000000
--- a/src/main/java/io/xdag/mine/MinerServer.java
+++ /dev/null
@@ -1,98 +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;
-
-import io.netty.bootstrap.ServerBootstrap;
-import io.netty.channel.ChannelFuture;
-import io.netty.channel.ChannelOption;
-import io.netty.channel.DefaultMessageSizeEstimator;
-import io.netty.channel.EventLoopGroup;
-import io.netty.channel.epoll.EpollEventLoopGroup;
-import io.netty.channel.kqueue.KQueueEventLoopGroup;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.handler.logging.LoggingHandler;
-import io.netty.util.NettyRuntime;
-import io.xdag.Kernel;
-import io.xdag.utils.NettyUtils;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.lang3.SystemUtils;
-
-@Slf4j
-public class MinerServer {
- private Kernel kernel;
- private EventLoopGroup bossGroup;
- private EventLoopGroup workerGroup;
- private ChannelFuture channelFuture;
- private final int workerThreadPoolSize = NettyRuntime.availableProcessors() * 4;
-
- public MinerServer(Kernel kernel) {
- this.kernel = kernel;
- }
-
- public void start() {
- start(kernel.getConfig().getPoolSpec().getPoolIp(), kernel.getConfig().getPoolSpec().getPoolPort());
- }
-
- public void start(String ip, int port) {
- try {
- if(SystemUtils.IS_OS_LINUX) {
- bossGroup = new EpollEventLoopGroup();
- workerGroup = new EpollEventLoopGroup(workerThreadPoolSize);
- } else if(SystemUtils.IS_OS_MAC) {
- bossGroup = new KQueueEventLoopGroup();
- workerGroup = new KQueueEventLoopGroup(workerThreadPoolSize);
-
- } else {
- bossGroup = new NioEventLoopGroup();
- workerGroup = new NioEventLoopGroup(workerThreadPoolSize);
- }
-
- ServerBootstrap b = NettyUtils.nativeEventLoopGroup(bossGroup, workerGroup);
- b.childOption(ChannelOption.TCP_NODELAY, true);
- b.childOption(ChannelOption.SO_KEEPALIVE, true);
- b.childOption(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
- b.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, kernel.getConfig().getPoolSpec().getConnectionTimeout());
- b.handler(new LoggingHandler());
- b.childHandler(new MinerChannelInitializer(kernel, true));
- channelFuture = b.bind(ip, port).sync();
- log.info("Xdag Pool start host:[{}:{}]", ip, port);
- } catch (Exception e) {
- log.error("Xdag Pool start error:{}.", e.getMessage(), e);
- }
- }
-
- public void close() {
- if (channelFuture != null && channelFuture.channel().isOpen()) {
- try {
- channelFuture.channel().close().sync();
- workerGroup.shutdownGracefully();
- bossGroup.shutdownGracefully();
- log.info("Xdag Pool closed.");
- } catch (Exception e) {
- log.error("Xdag Pool close error:{}", e.getMessage(), e);
- }
- }
- }
-}
diff --git a/src/main/java/io/xdag/mine/handler/Miner03.java b/src/main/java/io/xdag/mine/handler/Miner03.java
deleted file mode 100644
index d3490c03e..000000000
--- a/src/main/java/io/xdag/mine/handler/Miner03.java
+++ /dev/null
@@ -1,232 +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.handler;
-
-import static io.xdag.utils.BytesUtils.compareTo;
-
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.SimpleChannelInboundHandler;
-import io.netty.handler.timeout.IdleState;
-import io.netty.handler.timeout.IdleStateEvent;
-import io.xdag.Kernel;
-import io.xdag.consensus.SyncManager;
-import io.xdag.core.Block;
-import io.xdag.core.BlockWrapper;
-import io.xdag.core.ImportResult;
-import io.xdag.db.AddressStore;
-import io.xdag.mine.MinerChannel;
-import io.xdag.mine.manager.MinerManager;
-import io.xdag.mine.message.NewBalanceMessage;
-import io.xdag.mine.message.NewTaskMessage;
-import io.xdag.mine.message.TaskShareMessage;
-import io.xdag.mine.message.WorkerNameMessage;
-import io.xdag.mine.miner.Miner;
-import io.xdag.net.message.Message;
-import io.xdag.net.message.impl.NewBlockMessage;
-import io.xdag.utils.BasicUtils;
-
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-
-import io.xdag.utils.WalletUtils;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.tuweni.bytes.Bytes;
-import org.apache.tuweni.units.bigints.UInt64;
-
-@Slf4j
-public class Miner03 extends SimpleChannelInboundHandler {
-
- private final Kernel kernel;
- private final MinerChannel channel;
- private final AddressStore addressStore;
- private final MinerManager minerManager;
- private final SyncManager syncManager;
- private ChannelHandlerContext ctx;
-
- private int readIdleTimes;
- private int writeIdleTimes;
- private int allIdleTimes;
-
- public Miner03(MinerChannel channel, Kernel kernel) {
- this.channel = channel;
- this.kernel = kernel;
- addressStore = kernel.getAddressStore();
- minerManager = kernel.getMinerManager();
- syncManager = kernel.getSyncMgr();
- }
-
- @Override
- protected void channelRead0(ChannelHandlerContext ctx, Message msg) {
- switch (msg.getCommand()) {
- case NEW_BALANCE -> processNewBalance((NewBalanceMessage) msg);
- case TASK_SHARE -> processTaskShare((TaskShareMessage) msg);
- case NEW_TASK -> processNewTask((NewTaskMessage) msg);
- case NEW_BLOCK -> processNewBlock((NewBlockMessage) msg);
- case WORKER_NAME ->processWorkerName((WorkerNameMessage) msg);
- default -> log.warn("There is no message type for this corresponding data, the content HEX is {}", msg.getEncoded().toHexString());
- }
- }
-
- @Override
- public void handlerAdded(ChannelHandlerContext ctx) {
- channel.setCtx(ctx);
- this.ctx = ctx;
- log.debug("ip&port:{},Address:{} add handler",channel.getInetAddress().toString(),channel.getAddressHash());
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
- log.error(cause.getMessage(), cause);
- if (cause instanceof IOException) {
- ctx.channel().closeFuture();
- log.debug("ExceptionCaught:{}, Close miner channel:{}, address:{}, workName:{}",
- cause.getMessage(), channel.getInetAddress().toString(), channel.getAddressHash(), channel.getWorkerName());
- }
- channel.setActive(false);
- }
-
- @Override
- public void handlerRemoved(ChannelHandlerContext ctx) {
- log.debug("Close miner channel:{}, address:{}, workName:{}",
- channel.getInetAddress().toString(), channel.getAddressHash(), channel.getWorkerName());
- ctx.channel().closeFuture();
- channel.onDisconnect();
- }
-
- /**
- * ********************** Message Processing * ***********************
- */
- protected void processNewBlock(NewBlockMessage msg) {
- Block block = msg.getBlock();
- ImportResult importResult = syncManager
- .validateAndAddNewBlock(new BlockWrapper(block, kernel.getConfig().getNodeSpec().getTTL()));
- if (importResult.isNormal()) {
- log.debug("XDAG:receive transaction. A transaction from ip&port:{},wallet/miner: {}, block hash: {}",
- channel.getInetAddress().toString(),channel.getAddressHash(),block.getHash().toHexString());
- }
- }
-
- protected void processNewBalance(NewBalanceMessage msg) {
- // TODO: 2020/5/9 Process the balance information received by the miner Miner function
- log.debug("ip&port:{},Address:{} receive new balance: [{}]",
- channel.getInetAddress().toString(), WalletUtils.toBase58(channel.getAccountAddressHashByte()),BasicUtils.amount2xdag(UInt64.fromBytes(msg.getEncoded().slice(0,8))));
- }
-
- protected void processNewTask(NewTaskMessage msg) {
- // TODO: 2020/5/9 Handle new tasks received by miners Miner functions
- log.debug("Address:{} receive new task: [{}]",
- WalletUtils.toBase58(channel.getAccountAddressHashByte()),BasicUtils.amount2xdag(UInt64.fromBytes(msg.getEncoded().slice(0,8))));
- }
-
- protected void processTaskShare(TaskShareMessage msg) {
- //share地址不一致,修改对应的miner地址 否则向下进行处理
- //msg 最后12-32位反转 与 addressHashByte相等
- //实际是当初有伪块时区别矿机和钱包用的
- if (compareTo(msg.getEncoded().reverse().toArray(), 0, 20, channel.getAccountAddressHashByte(),0,20) != 0) {
- //TODO: 确定矿机协议,不再获取区块,直接获取Base58或者公钥的hash
-
- Miner miner = kernel.getMinerManager().getActivateMiners()
- .get(channel.getAccountAddressHash());
- if (miner == null) {
- miner = new Miner(channel.getAccountAddressHash());
- log.debug("Create new miner channel:{}, address:{}, workerName:{}.",
- channel.getInetAddress().toString(), WalletUtils.toBase58(miner.getAddressHashByte()), channel.getWorkerName());
- minerManager.addActiveMiner(miner);
- }
- // Change the address corresponding to the channel and replace the new miner connection
- channel.updateMiner(miner);
- log.debug("RandomX miner channel:{}, address:{}, workerName:{}",
- channel.getInetAddress().toString(), WalletUtils.toBase58(miner.getAddressHashByte()), channel.getWorkerName());
- }
-
- if (channel.getSharesCounts() <= kernel.getConfig().getPoolSpec().getMaxShareCountPerChannel()) {
- channel.addShareCounts(1);
- minerManager.onNewShare(channel, msg);
- } else {
- log.debug("Too many Shares from address:{},ip&port:{},Reject...",
- channel.getAddressHash(),channel.getInetAddress().toString());
- channel.onDisconnect();
- }
-
- }
-
- private void processWorkerName(WorkerNameMessage msg) {
- byte[] workerNameByte = msg.getEncoded().reverse().slice(4).toArray();
- String workerName = new String(workerNameByte, StandardCharsets.UTF_8).trim();
- log.debug("Pool receive miner address:{},workerName:{},ip&port:{}",
- channel.getAddressHash() ,workerName,channel.getInetAddress().toString());
- channel.setWorkerName(workerName);
- }
-
- /**
- * Send Task Message
- */
- public void sendMessage(Bytes bytes) {
- ctx.channel().writeAndFlush(bytes.toArray());
- }
-
- public void dropConnection() {
- disconnect();
- }
-
- public void disconnect() {
- if(ctx != null ) {
- ctx.close();
- }
-
- if(channel != null) {
- channel.setActive(false);
- }
-
- if(channel != null) {
- log.info("Disconnect channel: {} with address: {}",
- channel.getInetAddress().toString(), channel.getAddressHash());
- }
- }
-
- @Override
- public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
- try {
- if (evt instanceof IdleStateEvent e) {
- if (e.state() == IdleState.READER_IDLE) {
- readIdleTimes++;
- } else if (e.state() == IdleState.WRITER_IDLE) {
- writeIdleTimes++;
- } else if (e.state() == IdleState.ALL_IDLE) {
- allIdleTimes++;
- }
- log.debug("socket:{}, xdag address:{}, timeout with:{}", channel.getInetAddress().toString(), channel.getAddressHash(),((IdleStateEvent)evt).state().toString());
- }
-
- if (readIdleTimes > 3) {
- log.warn("close channel, socket:{}, xdag address:{}.", channel.getInetAddress().toString(), channel.getAddressHash());
- channel.onDisconnect();
- }
- } catch (Exception e) {
- log.error(e.getMessage(), e);
- }
- }
-
-}
diff --git a/src/main/java/io/xdag/mine/handler/MinerHandShakeHandler.java b/src/main/java/io/xdag/mine/handler/MinerHandShakeHandler.java
deleted file mode 100644
index 7053fccda..000000000
--- a/src/main/java/io/xdag/mine/handler/MinerHandShakeHandler.java
+++ /dev/null
@@ -1,162 +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.handler;
-
-import static io.xdag.net.XdagVersion.V03;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.handler.codec.ByteToMessageDecoder;
-import io.netty.handler.timeout.IdleState;
-import io.netty.handler.timeout.IdleStateEvent;
-import io.xdag.Kernel;
-import io.xdag.crypto.Base58;
-import io.xdag.db.AddressStore;
-import io.xdag.mine.MinerChannel;
-import io.xdag.mine.manager.MinerManager;
-import io.xdag.utils.BytesUtils;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import io.xdag.utils.WalletUtils;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.tuweni.bytes.Bytes32;
-
-@Slf4j
-public class MinerHandShakeHandler extends ByteToMessageDecoder {
-
- private final MinerChannel channel;
- private final Kernel kernel;
- private final MinerManager minerManager;
- private final AddressStore addressStore;
- public static final int MESSAGE_SIZE = 24;
-
- public MinerHandShakeHandler(MinerChannel channel, Kernel kernel) {
- this.channel = channel;
- this.kernel = kernel;
- minerManager = kernel.getMinerManager();
- addressStore = kernel.getAddressStore();
- }
-
- @Override
- protected void decode(ChannelHandlerContext ctx, ByteBuf in, List