() {
+
+ @Override
+ protected int compareParameters(MediaType mediaType1, MediaType mediaType2) {
+ double quality1 = mediaType1.getQualityValue();
+ double quality2 = mediaType2.getQualityValue();
+ int qualityComparison = Double.compare(quality2, quality1);
+ if (qualityComparison != 0) {
+ return qualityComparison; // audio/*;q=0.7 < audio/*;q=0.3
+ }
+ return super.compareParameters(mediaType1, mediaType2);
+ }
+ };
+
+ static {
+ // Not using "valueOf' to avoid static init cost
+ ALL = new MediaType("*", "*");
+ APPLICATION_ATOM_XML = new MediaType("application", "atom+xml");
+ APPLICATION_CBOR = new MediaType("application", "cbor");
+ APPLICATION_FORM_URLENCODED = new MediaType("application", "x-www-form-urlencoded");
+ APPLICATION_GRAPHQL = new MediaType("application", "graphql+json");
+ APPLICATION_JSON = new MediaType("application", "json");
+ APPLICATION_JSON_UTF8 = new MediaType("application", "json", StandardCharsets.UTF_8);
+ APPLICATION_NDJSON = new MediaType("application", "x-ndjson");
+ APPLICATION_OCTET_STREAM = new MediaType("application", "octet-stream");
+ APPLICATION_PDF = new MediaType("application", "pdf");
+ APPLICATION_PROBLEM_JSON = new MediaType("application", "problem+json");
+ APPLICATION_PROBLEM_JSON_UTF8 = new MediaType("application", "problem+json",
+ StandardCharsets.UTF_8);
+ APPLICATION_PROBLEM_XML = new MediaType("application", "problem+xml");
+ APPLICATION_RSS_XML = new MediaType("application", "rss+xml");
+ APPLICATION_STREAM_JSON = new MediaType("application", "stream+json");
+ APPLICATION_XHTML_XML = new MediaType("application", "xhtml+xml");
+ APPLICATION_XML = new MediaType("application", "xml");
+ IMAGE_GIF = new MediaType("image", "gif");
+ IMAGE_JPEG = new MediaType("image", "jpeg");
+ IMAGE_PNG = new MediaType("image", "png");
+ MULTIPART_FORM_DATA = new MediaType("multipart", "form-data");
+ MULTIPART_MIXED = new MediaType("multipart", "mixed");
+ MULTIPART_RELATED = new MediaType("multipart", "related");
+ TEXT_EVENT_STREAM = new MediaType("text", "event-stream");
+ TEXT_HTML = new MediaType("text", "html");
+ TEXT_MARKDOWN = new MediaType("text", "markdown");
+ TEXT_PLAIN = new MediaType("text", "plain");
+ TEXT_XML = new MediaType("text", "xml");
+ }
+
+ /**
+ * Create a new {@code MediaType} for the given primary type.
+ * The {@linkplain #getSubtype() subtype} is set to "*", parameters empty.
+ *
+ * @param type the primary type
+ * @throws IllegalArgumentException if any of the parameters contain illegal characters
+ */
+ public MediaType(String type) {
+ super(type);
+ }
+
+ /**
+ * Create a new {@code MediaType} for the given primary type and subtype.
+ *
The parameters are empty.
+ *
+ * @param type the primary type
+ * @param subtype the subtype
+ * @throws IllegalArgumentException if any of the parameters contain illegal characters
+ */
+ public MediaType(String type, String subtype) {
+ super(type, subtype, Collections.emptyMap());
+ }
+
+ /**
+ * Create a new {@code MediaType} for the given type, subtype, and character set.
+ *
+ * @param type the primary type
+ * @param subtype the subtype
+ * @param charset the character set
+ * @throws IllegalArgumentException if any of the parameters contain illegal characters
+ */
+ public MediaType(String type, String subtype, Charset charset) {
+ super(type, subtype, charset);
+ }
+
+ /**
+ * Create a new {@code MediaType} for the given type, subtype, and quality value.
+ *
+ * @param type the primary type
+ * @param subtype the subtype
+ * @param qualityValue the quality value
+ * @throws IllegalArgumentException if any of the parameters contain illegal characters
+ */
+ public MediaType(String type, String subtype, double qualityValue) {
+ this(type, subtype, Collections.singletonMap(PARAM_QUALITY_FACTOR,
+ Double.toString(qualityValue)));
+ }
+
+ /**
+ * Copy-constructor that copies the type, subtype and parameters of the given
+ * {@code MediaType}, and allows to set the specified character set.
+ *
+ * @param other the other media type
+ * @param charset the character set
+ * @throws IllegalArgumentException if any of the parameters contain illegal characters
+ * @since 4.3
+ */
+ public MediaType(MediaType other, Charset charset) {
+ super(other, charset);
+ }
+
+ /**
+ * Copy-constructor that copies the type and subtype of the given {@code MediaType},
+ * and allows for different parameters.
+ *
+ * @param other the other media type
+ * @param parameters the parameters, may be {@code null}
+ * @throws IllegalArgumentException if any of the parameters contain illegal characters
+ */
+ public MediaType(MediaType other, @Nullable Map parameters) {
+ super(other.getType(), other.getSubtype(), parameters);
+ }
+
+
+ /**
+ * Create a new {@code MediaType} for the given type, subtype, and parameters.
+ *
+ * @param type the primary type
+ * @param subtype the subtype
+ * @param parameters the parameters, may be {@code null}
+ * @throws IllegalArgumentException if any of the parameters contain illegal characters
+ */
+ public MediaType(String type, String subtype, @Nullable Map parameters) {
+ super(type, subtype, parameters);
+ }
+
+ /**
+ * Create a new {@code MediaType} for the given {@link MimeType}.
+ * The type, subtype and parameters information is copied and {@code MediaType}-specific
+ * checks on parameters are performed.
+ *
+ * @param mimeType the MIME type
+ * @throws IllegalArgumentException if any of the parameters contain illegal characters
+ * @since 5.3
+ */
+ public MediaType(MimeType mimeType) {
+ super(mimeType);
+ getParameters().forEach(this::checkParameters);
+ }
+
+ /**
+ * Parse the given String value into a {@code MediaType} object,
+ * with this method name following the 'valueOf' naming convention
+ * (as supported by {@link org.springframework.core.convert.ConversionService}.
+ *
+ * @param value the string to parse
+ * @throws InvalidMediaTypeException if the media type value cannot be parsed
+ * @see #parseMediaType(String)
+ */
+ public static MediaType valueOf(String value) {
+ return parseMediaType(value);
+ }
+
+ /**
+ * Parse the given String into a single {@code MediaType}.
+ *
+ * @param mediaType the string to parse
+ * @return the media type
+ * @throws InvalidMediaTypeException if the media type value cannot be parsed
+ */
+ public static MediaType parseMediaType(String mediaType) {
+ MimeType type;
+ try {
+ type = MimeTypeUtils.parseMimeType(mediaType);
+ } catch (InvalidMimeTypeException ex) {
+ throw new InvalidMediaTypeException(ex);
+ }
+ try {
+ return new MediaType(type);
+ } catch (IllegalArgumentException ex) {
+ throw new InvalidMediaTypeException(mediaType, ex.getMessage());
+ }
+ }
+
+ /**
+ * Parse the comma-separated string into a list of {@code MediaType} objects.
+ * This method can be used to parse an Accept or Content-Type header.
+ *
+ * @param mediaTypes the string to parse
+ * @return the list of media types
+ * @throws InvalidMediaTypeException if the media type value cannot be parsed
+ */
+ public static List parseMediaTypes(@Nullable String mediaTypes) {
+ if (!StringUtils.hasLength(mediaTypes)) {
+ return Collections.emptyList();
+ }
+ // Avoid using java.util.stream.Stream in hot paths
+ List tokenizedTypes = MimeTypeUtils.tokenize(mediaTypes);
+ List result = new ArrayList<>(tokenizedTypes.size());
+ for (String type : tokenizedTypes) {
+ if (StringUtils.hasText(type)) {
+ result.add(parseMediaType(type));
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Parse the given list of (potentially) comma-separated strings into a
+ * list of {@code MediaType} objects.
+ * This method can be used to parse an Accept or Content-Type header.
+ *
+ * @param mediaTypes the string to parse
+ * @return the list of media types
+ * @throws InvalidMediaTypeException if the media type value cannot be parsed
+ * @since 4.3.2
+ */
+ public static List parseMediaTypes(@Nullable List mediaTypes) {
+ if (CollectionUtils.isEmpty(mediaTypes)) {
+ return Collections.emptyList();
+ } else if (mediaTypes.size() == 1) {
+ return parseMediaTypes(mediaTypes.get(0));
+ } else {
+ List result = new ArrayList<>(8);
+ for (String mediaType : mediaTypes) {
+ result.addAll(parseMediaTypes(mediaType));
+ }
+ return result;
+ }
+ }
+
+ /**
+ * Re-create the given mime types as media types.
+ *
+ * @since 5.0
+ */
+ public static List asMediaTypes(List mimeTypes) {
+ List mediaTypes = new ArrayList<>(mimeTypes.size());
+ for (MimeType mimeType : mimeTypes) {
+ mediaTypes.add(MediaType.asMediaType(mimeType));
+ }
+ return mediaTypes;
+ }
+
+ /**
+ * Re-create the given mime type as a media type.
+ *
+ * @since 5.0
+ */
+ public static MediaType asMediaType(MimeType mimeType) {
+ if (mimeType instanceof MediaType) {
+ return (MediaType) mimeType;
+ }
+ return new MediaType(mimeType.getType(), mimeType.getSubtype(), mimeType.getParameters());
+ }
+
+ /**
+ * Return a string representation of the given list of {@code MediaType} objects.
+ * This method can be used to for an {@code Accept} or {@code Content-Type} header.
+ *
+ * @param mediaTypes the media types to create a string representation for
+ * @return the string representation
+ */
+ public static String toString(Collection mediaTypes) {
+ return MimeTypeUtils.toString(mediaTypes);
+ }
+
+ /**
+ * Sorts the given list of {@code MediaType} objects by specificity.
+ * Given two media types:
+ *
+ * - if either media type has a {@linkplain #isWildcardType() wildcard type},
+ * then the media type without the wildcard is ordered before the other.
+ * - if the two media types have different {@linkplain #getType() types},
+ * then they are considered equal and remain their current order.
+ * - if either media type has a {@linkplain #isWildcardSubtype() wildcard subtype},
+ * then the media type without the wildcard is sorted before the other.
+ * - if the two media types have different {@linkplain #getSubtype() subtypes},
+ * then they are considered equal and remain their current order.
+ * - if the two media types have different {@linkplain #getQualityValue() quality value},
+ * then the media type with the highest quality value is ordered before the other.
+ * - if the two media types have a different amount of
+ * {@linkplain #getParameter(String) parameters}, then the
+ * media type with the most parameters is ordered before the other.
+ *
+ * For example:
+ *
audio/basic < audio/* < */*
+ * audio/* < audio/*;q=0.7; audio/*;q=0.3
+ * audio/basic;level=1 < audio/basic
+ * audio/basic == text/html
+ * audio/basic == audio/wave
+ *
+ * @param mediaTypes the list of media types to be sorted
+ * @see HTTP 1.1: Semantics
+ * and Content, section 5.3.2
+ */
+ public static void sortBySpecificity(List mediaTypes) {
+ Assert.notNull(mediaTypes, "'mediaTypes' must not be null");
+ if (mediaTypes.size() > 1) {
+ mediaTypes.sort(SPECIFICITY_COMPARATOR);
+ }
+ }
+
+ /**
+ * Sorts the given list of {@code MediaType} objects by quality value.
+ * Given two media types:
+ *
+ * - if the two media types have different {@linkplain #getQualityValue() quality value},
+ * then the media type with the highest quality value is ordered before the other.
+ * - if either media type has a {@linkplain #isWildcardType() wildcard type},
+ * then the media type without the wildcard is ordered before the other.
+ * - if the two media types have different {@linkplain #getType() types},
+ * then they are considered equal and remain their current order.
+ * - if either media type has a {@linkplain #isWildcardSubtype() wildcard subtype},
+ * then the media type without the wildcard is sorted before the other.
+ * - if the two media types have different {@linkplain #getSubtype() subtypes},
+ * then they are considered equal and remain their current order.
+ * - if the two media types have a different amount of
+ * {@linkplain #getParameter(String) parameters}, then the
+ * media type with the most parameters is ordered before the other.
+ *
+ *
+ * @param mediaTypes the list of media types to be sorted
+ * @see #getQualityValue()
+ */
+ public static void sortByQualityValue(List mediaTypes) {
+ Assert.notNull(mediaTypes, "'mediaTypes' must not be null");
+ if (mediaTypes.size() > 1) {
+ mediaTypes.sort(QUALITY_VALUE_COMPARATOR);
+ }
+ }
+
+ /**
+ * Sorts the given list of {@code MediaType} objects by specificity as the
+ * primary criteria and quality value the secondary.
+ *
+ * @see MediaType#sortBySpecificity(List)
+ * @see MediaType#sortByQualityValue(List)
+ */
+ public static void sortBySpecificityAndQuality(List mediaTypes) {
+ Assert.notNull(mediaTypes, "'mediaTypes' must not be null");
+ if (mediaTypes.size() > 1) {
+ mediaTypes.sort(
+ MediaType.SPECIFICITY_COMPARATOR.thenComparing(MediaType.QUALITY_VALUE_COMPARATOR));
+ }
+ }
+
+ @Override
+ protected void checkParameters(String parameter, String value) {
+ super.checkParameters(parameter, value);
+ if (PARAM_QUALITY_FACTOR.equals(parameter)) {
+ String unquotedValue = unquote(value);
+ double d = Double.parseDouble(unquotedValue);
+ Assert.isTrue(d >= 0D && d <= 1D,
+ () -> "Invalid quality value \"" + unquotedValue + "\": should be between 0.0 and 1.0");
+ }
+ }
+
+ /**
+ * Return the quality factor, as indicated by a {@code q} parameter, if any.
+ * Defaults to {@code 1.0}.
+ *
+ * @return the quality factor as double value
+ */
+ public double getQualityValue() {
+ String qualityFactor = getParameter(PARAM_QUALITY_FACTOR);
+ return (qualityFactor != null ? Double.parseDouble(unquote(qualityFactor)) : 1D);
+ }
+
+ /**
+ * Indicate whether this {@code MediaType} includes the given media type.
+ * For instance, {@code text/*} includes {@code text/plain} and {@code text/html},
+ * and {@code application/*+xml} includes {@code application/soap+xml}, etc.
+ * This method is not symmetric.
+ *
Simply calls {@link MimeType#includes(MimeType)} but declared with a
+ * {@code MediaType} parameter for binary backwards compatibility.
+ *
+ * @param other the reference media type with which to compare
+ * @return {@code true} if this media type includes the given media type;
+ * {@code false} otherwise
+ */
+ public boolean includes(@Nullable MediaType other) {
+ return super.includes(other);
+ }
+
+ /**
+ * Indicate whether this {@code MediaType} is compatible with the given media type.
+ *
For instance, {@code text/*} is compatible with {@code text/plain},
+ * {@code text/html}, and vice versa. In effect, this method is similar to
+ * {@link #includes}, except that it is symmetric.
+ *
Simply calls {@link MimeType#isCompatibleWith(MimeType)} but declared with a
+ * {@code MediaType} parameter for binary backwards compatibility.
+ *
+ * @param other the reference media type with which to compare
+ * @return {@code true} if this media type is compatible with the given media type;
+ * {@code false} otherwise
+ */
+ public boolean isCompatibleWith(@Nullable MediaType other) {
+ return super.isCompatibleWith(other);
+ }
+
+ /**
+ * Return a replica of this instance with the quality value of the given {@code MediaType}.
+ *
+ * @return the same instance if the given MediaType doesn't have a quality value,
+ * or a new one otherwise
+ */
+ public MediaType copyQualityValue(MediaType mediaType) {
+ if (!mediaType.getParameters().containsKey(PARAM_QUALITY_FACTOR)) {
+ return this;
+ }
+ Map params = new LinkedHashMap<>(getParameters());
+ params.put(PARAM_QUALITY_FACTOR, mediaType.getParameters().get(PARAM_QUALITY_FACTOR));
+ return new MediaType(this, params);
+ }
+
+ /**
+ * Return a replica of this instance with its quality value removed.
+ *
+ * @return the same instance if the media type doesn't contain a quality value,
+ * or a new one otherwise
+ */
+ public MediaType removeQualityValue() {
+ if (!getParameters().containsKey(PARAM_QUALITY_FACTOR)) {
+ return this;
+ }
+ Map params = new LinkedHashMap<>(getParameters());
+ params.remove(PARAM_QUALITY_FACTOR);
+ return new MediaType(this, params);
+ }
+
+}
\ No newline at end of file
diff --git a/framework/src/test/java/org/tron/common/runtime/vm/Create2Test.java b/framework/src/test/java/org/tron/common/runtime/vm/Create2Test.java
index f400b3215ee..6fa2801c51f 100644
--- a/framework/src/test/java/org/tron/common/runtime/vm/Create2Test.java
+++ b/framework/src/test/java/org/tron/common/runtime/vm/Create2Test.java
@@ -19,9 +19,9 @@
import org.tron.core.Wallet;
import org.tron.core.exception.ContractExeException;
import org.tron.core.exception.ContractValidateException;
-import org.tron.core.exception.JsonRpcInvalidParamsException;
import org.tron.core.exception.ReceiptCheckErrException;
import org.tron.core.exception.VMIllegalException;
+import org.tron.core.exception.jsonrpc.JsonRpcInvalidParamsException;
import org.tron.core.services.NodeInfoService;
import org.tron.core.services.jsonrpc.TronJsonRpcImpl;
import org.tron.core.vm.config.ConfigLoader;
diff --git a/framework/src/test/java/org/tron/common/storage/leveldb/LevelDbDataSourceImplTest.java b/framework/src/test/java/org/tron/common/storage/leveldb/LevelDbDataSourceImplTest.java
index bf18b988f19..c8b29c3020d 100644
--- a/framework/src/test/java/org/tron/common/storage/leveldb/LevelDbDataSourceImplTest.java
+++ b/framework/src/test/java/org/tron/common/storage/leveldb/LevelDbDataSourceImplTest.java
@@ -28,6 +28,7 @@
import com.google.common.collect.Sets;
import java.io.File;
import java.io.IOException;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -38,15 +39,24 @@
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
+import org.iq80.leveldb.DBException;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
+import org.rocksdb.RocksDB;
+import org.tron.common.parameter.CommonParameter;
+import org.tron.common.storage.WriteOptionsWrapper;
+import org.tron.common.storage.rocksdb.RocksDbDataSourceImpl;
import org.tron.common.utils.ByteArray;
import org.tron.common.utils.FileUtil;
+import org.tron.common.utils.PropUtil;
import org.tron.common.utils.PublicMethod;
+import org.tron.common.utils.StorageUtils;
import org.tron.core.Constant;
import org.tron.core.config.args.Args;
import org.tron.core.db2.common.WrappedByteArray;
@@ -73,6 +83,14 @@ public class LevelDbDataSourceImplTest {
private byte[] key5 = "00000005aa".getBytes();
private byte[] key6 = "00000006aa".getBytes();
+
+ @Rule
+ public final ExpectedException exception = ExpectedException.none();
+
+ static {
+ RocksDB.loadLibrary();
+ }
+
/**
* Release resources.
*/
@@ -102,8 +120,19 @@ public void testPutGet() {
assertNotNull(dataSourceTest.getData(key));
assertEquals(1, dataSourceTest.allKeys().size());
+ assertEquals(1, dataSourceTest.getTotal());
+ assertEquals(1, dataSourceTest.allValues().size());
assertEquals("50000", ByteArray.toStr(dataSourceTest.getData(key1.getBytes())));
+ dataSourceTest.deleteData(key);
+ assertNull(dataSourceTest.getData(key));
+ assertEquals(0, dataSourceTest.getTotal());
+ dataSourceTest.iterator().forEachRemaining(entry -> Assert.fail("iterator should be empty"));
+ dataSourceTest.stream().forEach(entry -> Assert.fail("stream should be empty"));
+ dataSourceTest.stat();
dataSourceTest.closeDB();
+ dataSourceTest.stat(); // stat again
+ exception.expect(DBException.class);
+ dataSourceTest.deleteData(key);
}
@Test
@@ -142,6 +171,23 @@ public void testupdateByBatchInner() {
assertEquals("50000", ByteArray.toStr(dataSource.getData(key1.getBytes())));
assertEquals("10000", ByteArray.toStr(dataSource.getData(key2.getBytes())));
assertEquals(2, dataSource.allKeys().size());
+
+ rows.clear();
+ rows.put(key1.getBytes(), null);
+ rows.put(key2.getBytes(), null);
+ dataSource.updateByBatch(rows, WriteOptionsWrapper.getInstance());
+ assertEquals(0, dataSource.allKeys().size());
+
+ rows.clear();
+ rows.put(key1.getBytes(), value1.getBytes());
+ rows.put(key2.getBytes(), null);
+ dataSource.updateByBatch(rows);
+ assertEquals("50000", ByteArray.toStr(dataSource.getData(key1.getBytes())));
+ assertEquals(1, dataSource.allKeys().size());
+ rows.clear();
+ rows.put(null, null);
+ exception.expect(RuntimeException.class);
+ dataSource.updateByBatch(rows);
dataSource.closeDB();
}
@@ -354,6 +400,118 @@ public void initDbTest() {
assertEquals(TronError.ErrCode.LEVELDB_INIT, thrown.getErrCode());
}
+ @Test
+ public void testCheckOrInitEngine() {
+ String dir =
+ Args.getInstance().getOutputDirectory() + Args.getInstance().getStorage().getDbDirectory();
+ String enginePath = dir + File.separator + "test_engine" + File.separator + "engine.properties";
+ FileUtil.createDirIfNotExists(dir + File.separator + "test_engine");
+ FileUtil.createFileIfNotExists(enginePath);
+ PropUtil.writeProperty(enginePath, "ENGINE", "LEVELDB");
+ Assert.assertEquals("LEVELDB", PropUtil.readProperty(enginePath, "ENGINE"));
+
+ LevelDbDataSourceImpl dataSource;
+ dataSource = new LevelDbDataSourceImpl(dir, "test_engine");
+ dataSource.initDB();
+ dataSource.closeDB();
+
+ System.gc();
+ PropUtil.writeProperty(enginePath, "ENGINE", "ROCKSDB");
+ Assert.assertEquals("ROCKSDB", PropUtil.readProperty(enginePath, "ENGINE"));
+ try {
+ dataSource = new LevelDbDataSourceImpl(dir, "test_engine");
+ dataSource.initDB();
+ } catch (Exception e) {
+ Assert.assertEquals(String.format(
+ "Cannot open RocksDB database '%s' with LevelDB engine."
+ + " Set db.engine=ROCKSDB or use LevelDB database. ", "test_engine"),
+ e.getMessage());
+ }
+ }
+
+ @Test
+ public void testLevelDbOpenRocksDb() {
+ String name = "test_openRocksDb";
+ String output = Paths
+ .get(StorageUtils.getOutputDirectoryByDbName(name), CommonParameter
+ .getInstance().getStorage().getDbDirectory()).toString();
+ RocksDbDataSourceImpl rocksDb = new RocksDbDataSourceImpl(output, name);
+ rocksDb.initDB();
+ rocksDb.putData(key1, value1);
+ rocksDb.closeDB();
+ LevelDbDataSourceImpl levelDB =
+ new LevelDbDataSourceImpl(StorageUtils.getOutputDirectoryByDbName(name), name);
+ exception.expectMessage(String.format(
+ "Cannot open RocksDB database '%s' with LevelDB engine."
+ + " Set db.engine=ROCKSDB or use LevelDB database. ", name));
+ levelDB.initDB();
+ }
+
+ @Test
+ public void testNewInstance() {
+ dataSourceTest.closeDB();
+ LevelDbDataSourceImpl newInst = dataSourceTest.newInstance();
+ newInst.initDB();
+ assertFalse(newInst.flush());
+ newInst.closeDB();
+ LevelDbDataSourceImpl empty = new LevelDbDataSourceImpl();
+ empty.setDBName("empty");
+ assertEquals("empty", empty.getDBName());
+ String name = "newInst2";
+ LevelDbDataSourceImpl newInst2 = new LevelDbDataSourceImpl(
+ StorageUtils.getOutputDirectoryByDbName(name),
+ name);
+ newInst2.initDB();
+ newInst2.closeDB();
+ }
+
+ @Test
+ public void testGetNext() {
+ LevelDbDataSourceImpl dataSource = new LevelDbDataSourceImpl(
+ Args.getInstance().getOutputDirectory(), "test_getNext_key");
+ dataSource.initDB();
+ dataSource.resetDb();
+ putSomeKeyValue(dataSource);
+ // case: normal
+ Map seekKvLimitNext = dataSource.getNext("0000000300".getBytes(), 2);
+ Map hashMap = Maps.newHashMap();
+ hashMap.put(ByteArray.toStr(key3), ByteArray.toStr(value3));
+ hashMap.put(ByteArray.toStr(key4), ByteArray.toStr(value4));
+ seekKvLimitNext.forEach((key, value) -> {
+ String keyStr = ByteArray.toStr(key);
+ Assert.assertTrue("getNext", hashMap.containsKey(keyStr));
+ Assert.assertEquals(ByteArray.toStr(value), hashMap.get(keyStr));
+ });
+ // case: targetKey greater than all existed keys
+ seekKvLimitNext = dataSource.getNext("0000000700".getBytes(), 2);
+ Assert.assertEquals(0, seekKvLimitNext.size());
+ // case: limit<=0
+ seekKvLimitNext = dataSource.getNext("0000000300".getBytes(), 0);
+ Assert.assertEquals(0, seekKvLimitNext.size());
+ dataSource.resetDb();
+ dataSource.closeDB();
+ }
+
+ @Test
+ public void testGetlatestValues() {
+ LevelDbDataSourceImpl dataSource = new LevelDbDataSourceImpl(
+ Args.getInstance().getOutputDirectory(), "test_getlatestValues_key");
+ dataSource.initDB();
+ dataSource.resetDb();
+ putSomeKeyValue(dataSource);
+ // case: normal
+ Set seekKeyLimitNext = dataSource.getlatestValues(2);
+ Set hashSet = Sets.newHashSet(ByteArray.toStr(value5), ByteArray.toStr(value6));
+ seekKeyLimitNext.forEach(value -> {
+ Assert.assertTrue(hashSet.contains(ByteArray.toStr(value)));
+ });
+ // case: limit<=0
+ seekKeyLimitNext = dataSource.getlatestValues(0);
+ assertEquals(0, seekKeyLimitNext.size());
+ dataSource.resetDb();
+ dataSource.closeDB();
+ }
+
private void makeExceptionDb(String dbName) {
LevelDbDataSourceImpl dataSource = new LevelDbDataSourceImpl(
Args.getInstance().getOutputDirectory(), "test_initDb");
diff --git a/framework/src/test/java/org/tron/common/storage/leveldb/RocksDbDataSourceImplTest.java b/framework/src/test/java/org/tron/common/storage/leveldb/RocksDbDataSourceImplTest.java
index c6fce30e3af..8f42c44e3b9 100644
--- a/framework/src/test/java/org/tron/common/storage/leveldb/RocksDbDataSourceImplTest.java
+++ b/framework/src/test/java/org/tron/common/storage/leveldb/RocksDbDataSourceImplTest.java
@@ -10,6 +10,8 @@
import com.google.common.collect.Sets;
import java.io.File;
import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -24,13 +26,20 @@
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
+import org.rocksdb.RocksDBException;
+import org.tron.common.error.TronDBException;
+import org.tron.common.parameter.CommonParameter;
+import org.tron.common.storage.WriteOptionsWrapper;
import org.tron.common.storage.rocksdb.RocksDbDataSourceImpl;
import org.tron.common.utils.ByteArray;
import org.tron.common.utils.FileUtil;
import org.tron.common.utils.PropUtil;
import org.tron.common.utils.PublicMethod;
+import org.tron.common.utils.StorageUtils;
import org.tron.core.config.args.Args;
import org.tron.core.db2.common.WrappedByteArray;
import org.tron.core.exception.TronError;
@@ -55,6 +64,9 @@ public class RocksDbDataSourceImplTest {
private byte[] key5 = "00000005aa".getBytes();
private byte[] key6 = "00000006aa".getBytes();
+ @Rule
+ public final ExpectedException expectedException = ExpectedException.none();
+
/**
* Release resources.
*/
@@ -84,8 +96,18 @@ public void testPutGet() {
assertNotNull(dataSourceTest.getData(key));
assertEquals(1, dataSourceTest.allKeys().size());
+ assertEquals(1, dataSourceTest.getTotal());
+ assertEquals(1, dataSourceTest.allValues().size());
assertEquals("50000", ByteArray.toStr(dataSourceTest.getData(key1.getBytes())));
+ dataSourceTest.deleteData(key);
+ assertNull(dataSourceTest.getData(key));
+ assertEquals(0, dataSourceTest.getTotal());
+ dataSourceTest.iterator().forEachRemaining(entry -> Assert.fail("iterator should be empty"));
+ dataSourceTest.stat();
dataSourceTest.closeDB();
+ dataSourceTest.stat(); // stat again
+ expectedException.expect(TronDBException.class);
+ dataSourceTest.deleteData(key);
}
@Test
@@ -124,6 +146,23 @@ public void testupdateByBatchInner() {
assertEquals("50000", ByteArray.toStr(dataSource.getData(key1.getBytes())));
assertEquals("10000", ByteArray.toStr(dataSource.getData(key2.getBytes())));
assertEquals(2, dataSource.allKeys().size());
+
+ rows.clear();
+ rows.put(key1.getBytes(), null);
+ rows.put(key2.getBytes(), null);
+ dataSource.updateByBatch(rows, WriteOptionsWrapper.getInstance());
+ assertEquals(0, dataSource.allKeys().size());
+
+ rows.clear();
+ rows.put(key1.getBytes(), value1.getBytes());
+ rows.put(key2.getBytes(), null);
+ dataSource.updateByBatch(rows);
+ assertEquals("50000", ByteArray.toStr(dataSource.getData(key1.getBytes())));
+ assertEquals(1, dataSource.allKeys().size());
+ rows.clear();
+ rows.put(null, null);
+ expectedException.expect(RuntimeException.class);
+ dataSource.updateByBatch(rows);
dataSource.closeDB();
}
@@ -276,8 +315,9 @@ public void testCheckOrInitEngine() {
try {
dataSource.initDB();
} catch (Exception e) {
- Assert.assertEquals(String.format("failed to check database: %s, engine do not match",
- "test_engine"),
+ Assert.assertEquals(String.format(
+ "Cannot open LevelDB database '%s' with RocksDB engine."
+ + " Set db.engine=LEVELDB or use RocksDB database. ", "test_engine"),
e.getMessage());
}
Assert.assertNull(dataSource.getDatabase());
@@ -396,6 +436,103 @@ public void initDbTest() {
assertEquals(TronError.ErrCode.ROCKSDB_INIT, thrown.getErrCode());
}
+ @Test
+ public void testRocksDbOpenLevelDb() {
+ String name = "test_openLevelDb";
+ String output = Paths
+ .get(StorageUtils.getOutputDirectoryByDbName(name), CommonParameter
+ .getInstance().getStorage().getDbDirectory()).toString();
+ LevelDbDataSourceImpl levelDb = new LevelDbDataSourceImpl(
+ StorageUtils.getOutputDirectoryByDbName(name), name);
+ levelDb.initDB();
+ levelDb.putData(key1, value1);
+ levelDb.closeDB();
+ RocksDbDataSourceImpl rocksDb = new RocksDbDataSourceImpl(output, name);
+ expectedException.expectMessage(
+ String.format(
+ "Cannot open LevelDB database '%s' with RocksDB engine."
+ + " Set db.engine=LEVELDB or use RocksDB database. ", name));
+ rocksDb.initDB();
+ }
+
+ @Test
+ public void testRocksDbOpenLevelDb2() {
+ String name = "test_openLevelDb2";
+ String output = Paths
+ .get(StorageUtils.getOutputDirectoryByDbName(name), CommonParameter
+ .getInstance().getStorage().getDbDirectory()).toString();
+ LevelDbDataSourceImpl levelDb = new LevelDbDataSourceImpl(
+ StorageUtils.getOutputDirectoryByDbName(name), name);
+ levelDb.initDB();
+ levelDb.putData(key1, value1);
+ levelDb.closeDB();
+ // delete engine.properties file to simulate the case that db.engine is not set.
+ File engineFile = Paths
+ .get(output, name, "engine.properties").toFile();
+ if (engineFile.exists()) {
+ engineFile.delete();
+ }
+ Assert.assertFalse(engineFile.exists());
+ RocksDbDataSourceImpl rocksDb = new RocksDbDataSourceImpl(output, name);
+ expectedException.expectMessage(
+ String.format(
+ "Cannot open LevelDB database '%s' with RocksDB engine."
+ + " Set db.engine=LEVELDB or use RocksDB database. ", name));
+ rocksDb.initDB();
+ }
+
+ @Test
+ public void testNewInstance() {
+ dataSourceTest.closeDB();
+ RocksDbDataSourceImpl newInst = dataSourceTest.newInstance();
+ newInst.initDB();
+ assertFalse(newInst.flush());
+ newInst.closeDB();
+ RocksDbDataSourceImpl empty = new RocksDbDataSourceImpl();
+ empty.setDBName("empty");
+ assertEquals("empty", empty.getDBName());
+ String output = Paths
+ .get(StorageUtils.getOutputDirectoryByDbName("newInst2"), CommonParameter
+ .getInstance().getStorage().getDbDirectory()).toString();
+ RocksDbDataSourceImpl newInst2 = new RocksDbDataSourceImpl(output, "newInst2");
+ newInst2.initDB();
+ newInst2.closeDB();
+ }
+
+ @Test
+ public void backupAndDelete() throws RocksDBException {
+ RocksDbDataSourceImpl dataSource = new RocksDbDataSourceImpl(
+ Args.getInstance().getOutputDirectory(), "backupAndDelete");
+ dataSource.initDB();
+ putSomeKeyValue(dataSource);
+ Path dir = Paths.get(Args.getInstance().getOutputDirectory(), "backup");
+ String path = dir + File.separator;
+ FileUtil.createDirIfNotExists(path);
+ dataSource.backup(path);
+ File backDB = Paths.get(dir.toString(),dataSource.getDBName()).toFile();
+ Assert.assertTrue(backDB.exists());
+ dataSource.deleteDbBakPath(path);
+ Assert.assertFalse(backDB.exists());
+ dataSource.closeDB();
+ }
+
+ @Test
+ public void testGetTotal() {
+ RocksDbDataSourceImpl dataSource = new RocksDbDataSourceImpl(
+ Args.getInstance().getOutputDirectory(), "test_getTotal_key");
+ dataSource.initDB();
+ dataSource.resetDb();
+
+ Map dataMapset = Maps.newHashMap();
+ dataMapset.put(key1, value1);
+ dataMapset.put(key2, value2);
+ dataMapset.put(key3, value3);
+ dataMapset.forEach(dataSource::putData);
+ Assert.assertEquals(dataMapset.size(), dataSource.getTotal());
+ dataSource.resetDb();
+ dataSource.closeDB();
+ }
+
private void makeExceptionDb(String dbName) {
RocksDbDataSourceImpl dataSource = new RocksDbDataSourceImpl(
Args.getInstance().getOutputDirectory(), "test_initDb");
diff --git a/framework/src/test/java/org/tron/common/utils/HashCodeTest.java b/framework/src/test/java/org/tron/common/utils/HashCodeTest.java
new file mode 100644
index 00000000000..36f9435c1aa
--- /dev/null
+++ b/framework/src/test/java/org/tron/common/utils/HashCodeTest.java
@@ -0,0 +1,23 @@
+package org.tron.common.utils;
+
+import java.util.Objects;
+import org.junit.Assert;
+import org.junit.Test;
+import org.tron.core.capsule.AccountCapsule;
+import org.tron.core.vm.repository.Type;
+import org.tron.core.vm.repository.Value;
+import org.tron.protos.Protocol;
+
+public class HashCodeTest {
+
+ @Test
+ public void test() {
+ Type type = new Type();
+ type.setType(Type.NORMAL);
+ Assert.assertEquals(Integer.valueOf(Type.NORMAL).hashCode(), type.hashCode());
+ Protocol.Account account = Protocol.Account.newBuilder().setBalance(100).build();
+ Value value = Value.create(new AccountCapsule(account.toByteArray()));
+ Assert.assertEquals(Integer.valueOf(
+ type.hashCode() + Objects.hashCode(account)).hashCode(), value.hashCode());
+ }
+}
diff --git a/framework/src/test/java/org/tron/common/utils/ObjectSizeUtilTest.java b/framework/src/test/java/org/tron/common/utils/ObjectSizeUtilTest.java
deleted file mode 100644
index c4c72991979..00000000000
--- a/framework/src/test/java/org/tron/common/utils/ObjectSizeUtilTest.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * java-tron is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * java-tron is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see .
- */
-
-package org.tron.common.utils;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-
-public class ObjectSizeUtilTest {
-
- @Test
- public void testGetObjectSize() {
-
- Person person = new Person();
- assertEquals(48, com.carrotsearch.sizeof.RamUsageEstimator.sizeOf(person));
- Person person1 = new Person(1, "tom", new int[]{});
- assertEquals(112, com.carrotsearch.sizeof.RamUsageEstimator.sizeOf(person1));
-
- Person person2 = new Person(1, "tom", new int[]{100});
- assertEquals(120, com.carrotsearch.sizeof.RamUsageEstimator.sizeOf(person2));
-
- Person person3 = new Person(1, "tom", new int[]{100, 100});
- assertEquals(120, com.carrotsearch.sizeof.RamUsageEstimator.sizeOf(person3));
- Person person4 = new Person(1, "tom", new int[]{100, 100, 100});
- assertEquals(128, com.carrotsearch.sizeof.RamUsageEstimator.sizeOf(person4));
- Person person5 = new Person(1, "tom", new int[]{100, 100, 100, 100});
- assertEquals(128, com.carrotsearch.sizeof.RamUsageEstimator.sizeOf(person5));
- Person person6 = new Person(1, "tom", new int[]{100, 100, 100, 100, 100});
- assertEquals(136, com.carrotsearch.sizeof.RamUsageEstimator.sizeOf(person6));
-
- }
-
- class Person {
-
- int age;
- String name;
- int[] scores;
-
- public Person() {
- }
-
- public Person(int age, String name, int[] scores) {
- this.age = age;
- this.name = name;
- this.scores = scores;
- }
- }
-
-}
diff --git a/framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java b/framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java
index b6226d01aae..63ffe1b58ff 100644
--- a/framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java
+++ b/framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java
@@ -14,6 +14,7 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
+import static org.tron.core.capsule.TransactionCapsule.getBase64FromByteString;
import com.google.protobuf.ByteString;
import java.security.SignatureException;
@@ -116,20 +117,6 @@ public static byte[] getOwner(Transaction.Contract contract) {
}
}
- /**
- * constructor.
- */
-
- public static String getBase64FromByteString(ByteString sign) {
- byte[] r = sign.substring(0, 32).toByteArray();
- byte[] s = sign.substring(32, 64).toByteArray();
- byte v = sign.byteAt(64);
- if (v < 27) {
- v += 27; //revId -> v
- }
- ECDSASignature signature = ECDSASignature.fromComponents(r, s, v);
- return signature.toBase64();
- }
/*
* 1. check hash
diff --git a/framework/src/test/java/org/tron/core/CoreExceptionTest.java b/framework/src/test/java/org/tron/core/CoreExceptionTest.java
index 89feaba338c..f82b0efe326 100644
--- a/framework/src/test/java/org/tron/core/CoreExceptionTest.java
+++ b/framework/src/test/java/org/tron/core/CoreExceptionTest.java
@@ -29,11 +29,6 @@
import org.tron.core.exception.HeaderNotFound;
import org.tron.core.exception.HighFreqException;
import org.tron.core.exception.ItemNotFoundException;
-import org.tron.core.exception.JsonRpcInternalException;
-import org.tron.core.exception.JsonRpcInvalidParamsException;
-import org.tron.core.exception.JsonRpcInvalidRequestException;
-import org.tron.core.exception.JsonRpcMethodNotFoundException;
-import org.tron.core.exception.JsonRpcTooManyResultException;
import org.tron.core.exception.NonCommonBlockException;
import org.tron.core.exception.NonUniqueObjectException;
import org.tron.core.exception.P2pException;
@@ -56,6 +51,11 @@
import org.tron.core.exception.ValidateSignatureException;
import org.tron.core.exception.ZkProofValidateException;
import org.tron.core.exception.ZksnarkException;
+import org.tron.core.exception.jsonrpc.JsonRpcInternalException;
+import org.tron.core.exception.jsonrpc.JsonRpcInvalidParamsException;
+import org.tron.core.exception.jsonrpc.JsonRpcInvalidRequestException;
+import org.tron.core.exception.jsonrpc.JsonRpcMethodNotFoundException;
+import org.tron.core.exception.jsonrpc.JsonRpcTooManyResultException;
public class CoreExceptionTest {
diff --git a/framework/src/test/java/org/tron/core/ShieldWalletTest.java b/framework/src/test/java/org/tron/core/ShieldWalletTest.java
index f8d5db1a44c..6e35d600ce7 100644
--- a/framework/src/test/java/org/tron/core/ShieldWalletTest.java
+++ b/framework/src/test/java/org/tron/core/ShieldWalletTest.java
@@ -7,6 +7,7 @@
import java.math.BigInteger;
import javax.annotation.Resource;
import org.junit.Assert;
+import org.junit.BeforeClass;
import org.junit.Test;
import org.tron.api.GrpcAPI.PrivateParameters;
import org.tron.api.GrpcAPI.PrivateParametersWithoutAsk;
@@ -29,13 +30,14 @@ public class ShieldWalletTest extends BaseTest {
@Resource
private Wallet wallet;
- static {
- Args.setParam(new String[] {"-d", dbPath()}, Constant.TEST_CONF);
+ @BeforeClass
+ public static void init() {
+ Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF);
+ librustzcashInitZksnarkParams();
}
@Test
public void testCreateShieldedTransaction1() {
- librustzcashInitZksnarkParams();
String transactionStr1 = new String(ByteArray.fromHexString(
"0x7b0a20202020227472616e73706172656e745f66726f6d5f61646472657373223a202234433930413"
+ "73241433344414546324536383932343545463430303839443634314345414337373433323433414233"
@@ -68,7 +70,6 @@ public void testCreateShieldedTransaction1() {
@Test
public void testCreateShieldedTransaction2() {
- librustzcashInitZksnarkParams();
String transactionStr2 = new String(ByteArray.fromHexString(
"7b0a202020202261736b223a20223938666430333136376632333437623534643737323338343137663"
+ "6373038643537323939643938376362613838353564653037626532346236316464653064222c0a2020"
@@ -176,7 +177,6 @@ public void testCreateShieldedTransaction2() {
@Test
public void testCreateShieldedTransactionWithoutSpendAuthSig() {
- librustzcashInitZksnarkParams();
String transactionStr3 = new String(ByteArray.fromHexString(
"7b0a2020202022616b223a2022373161643638633466353035373464356164333735343863626538363"
+ "63031663732393662393161306362303535353733313462373830383437323730326465222c0a202020"
@@ -286,7 +286,6 @@ public void testCreateShieldedTransactionWithoutSpendAuthSig() {
@Test
public void testGetNewShieldedAddress() {
- librustzcashInitZksnarkParams();
try {
ShieldedAddressInfo shieldedAddressInfo = wallet.getNewShieldedAddress();
Assert.assertNotNull(shieldedAddressInfo);
@@ -297,8 +296,7 @@ public void testGetNewShieldedAddress() {
@Test
public void testCreateShieldedContractParameters() throws ContractExeException {
- librustzcashInitZksnarkParams();
- Args.getInstance().setFullNodeAllowShieldedTransactionArgs(true);
+ Args.getInstance().setAllowShieldedTransactionApi(true);
Wallet wallet1 = spy(new Wallet());
doReturn(BigInteger.valueOf(1).toByteArray())
@@ -340,8 +338,7 @@ public void testCreateShieldedContractParameters() throws ContractExeException {
@Test
public void testCreateShieldedContractParameters2() throws ContractExeException {
- librustzcashInitZksnarkParams();
- Args.getInstance().setFullNodeAllowShieldedTransactionArgs(true);
+ Args.getInstance().setAllowShieldedTransactionApi(true);
Wallet wallet1 = spy(new Wallet());
doReturn(BigInteger.valueOf(1).toByteArray())
@@ -416,8 +413,7 @@ public void testCreateShieldedContractParameters2() throws ContractExeException
@Test
public void testCreateShieldedContractParametersWithoutAsk() throws ContractExeException {
- librustzcashInitZksnarkParams();
- Args.getInstance().setFullNodeAllowShieldedTransactionArgs(true);
+ Args.getInstance().setAllowShieldedTransactionApi(true);
Wallet wallet1 = spy(new Wallet());
doReturn(BigInteger.valueOf(1).toByteArray())
diff --git a/framework/src/test/java/org/tron/core/ShieldedTRC20BuilderTest.java b/framework/src/test/java/org/tron/core/ShieldedTRC20BuilderTest.java
index 2c97473b6c3..c2c4bfe3006 100644
--- a/framework/src/test/java/org/tron/core/ShieldedTRC20BuilderTest.java
+++ b/framework/src/test/java/org/tron/core/ShieldedTRC20BuilderTest.java
@@ -1,7 +1,5 @@
package org.tron.core;
-import static org.tron.core.zksnark.LibrustzcashTest.librustzcashInitZksnarkParams;
-
import com.google.protobuf.ByteString;
import java.math.BigInteger;
import java.util.Arrays;
@@ -12,7 +10,7 @@
import org.apache.commons.lang3.tuple.Pair;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Assert;
-import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.tron.api.GrpcAPI;
@@ -68,7 +66,6 @@ public class ShieldedTRC20BuilderTest extends BaseTest {
SHIELDED_CONTRACT_ADDRESS = WalletClient.decodeFromBase58Check(SHIELDED_CONTRACT_ADDRESS_STR);
DEFAULT_OVK = ByteArray
.fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d");
- ZksnarkInitService.librustzcashInitZksnarkParams();
PUBLIC_TO_ADDRESS = WalletClient.decodeFromBase58Check(PUBLIC_TO_ADDRESS_STR);
}
@@ -76,8 +73,9 @@ public class ShieldedTRC20BuilderTest extends BaseTest {
VerifyTransferProof transferContract = new VerifyTransferProof();
VerifyBurnProof burnContract = new VerifyBurnProof();
- @Before
- public void before() {
+ @BeforeClass
+ public static void initZksnarkParams() {
+ ZksnarkInitService.librustzcashInitZksnarkParams();
}
@Ignore
@@ -2172,7 +2170,6 @@ public void createShieldedContractParametersWithoutAskForBurn1to2()
@Ignore
@Test
public void getTriggerInputForForMint() throws Exception {
- librustzcashInitZksnarkParams();
SpendingKey sk = SpendingKey.random();
ExpandedSpendingKey expsk = sk.expandedSpendingKey();
byte[] ovk = expsk.getOvk();
@@ -2241,7 +2238,6 @@ public void getTriggerInputForForMint() throws Exception {
public void testScanShieldedTRC20NotesByIvk() throws Exception {
int statNum = 1;
int endNum = 100;
- librustzcashInitZksnarkParams();
SpendingKey sk = SpendingKey.decode(priKey);
FullViewingKey fvk = sk.fullViewingKey();
byte[] ivk = fvk.inViewingKey().value;
@@ -2273,7 +2269,6 @@ public void testscanShieldedTRC20NotesByOvk() throws Exception {
public void isShieldedTRC20ContractNoteSpent() throws Exception {
int statNum = 9200;
int endNum = 9240;
- librustzcashInitZksnarkParams();
SpendingKey sk = SpendingKey.decode(priKey);
FullViewingKey fvk = sk.fullViewingKey();
byte[] ivk = fvk.inViewingKey().value;
@@ -2350,7 +2345,6 @@ private byte[] decodePath(byte[] encodedPath) {
private GrpcAPI.PrivateShieldedTRC20Parameters mintParams(String privKey,
long value, String contractAddr, byte[] rcm)
throws ZksnarkException, ContractValidateException {
- librustzcashInitZksnarkParams();
long fromAmount = value;
SpendingKey sk = SpendingKey.decode(privKey);
ExpandedSpendingKey expsk = sk.expandedSpendingKey();
diff --git a/framework/src/test/java/org/tron/core/WalletMockTest.java b/framework/src/test/java/org/tron/core/WalletMockTest.java
index 098ba9aee61..ab7ad7ba10c 100644
--- a/framework/src/test/java/org/tron/core/WalletMockTest.java
+++ b/framework/src/test/java/org/tron/core/WalletMockTest.java
@@ -835,7 +835,7 @@ public void testGetTriggerInputForShieldedTRC20Contract() {
CommonParameter commonParameterMock = mock(Args.class);
try (MockedStatic mockedStatic = mockStatic(CommonParameter.class)) {
when(CommonParameter.getInstance()).thenReturn(commonParameterMock);
- when(commonParameterMock.isFullNodeAllowShieldedTransactionArgs()).thenReturn(true);
+ when(commonParameterMock.isAllowShieldedTransactionApi()).thenReturn(true);
assertThrows(ZksnarkException.class, () -> {
wallet.getTriggerInputForShieldedTRC20Contract(triggerParam.build());
@@ -866,7 +866,7 @@ public void testGetTriggerInputForShieldedTRC20Contract1()
CommonParameter commonParameterMock = mock(Args.class);
try (MockedStatic mockedStatic = mockStatic(CommonParameter.class)) {
when(CommonParameter.getInstance()).thenReturn(commonParameterMock);
- when(commonParameterMock.isFullNodeAllowShieldedTransactionArgs()).thenReturn(true);
+ when(commonParameterMock.isAllowShieldedTransactionApi()).thenReturn(true);
GrpcAPI.BytesMessage reponse =
wallet.getTriggerInputForShieldedTRC20Contract(triggerParam.build());
@@ -1319,4 +1319,4 @@ public void testGetContractInfo1() throws Exception {
wallet.getContractInfo(bytesMessage);
assertNotNull(smartContractDataWrapper);
}
-}
\ No newline at end of file
+}
diff --git a/framework/src/test/java/org/tron/core/actuator/ShieldedTransferActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ShieldedTransferActuatorTest.java
index b71ba432018..cb95194f3d3 100755
--- a/framework/src/test/java/org/tron/core/actuator/ShieldedTransferActuatorTest.java
+++ b/framework/src/test/java/org/tron/core/actuator/ShieldedTransferActuatorTest.java
@@ -85,7 +85,7 @@ public class ShieldedTransferActuatorTest extends BaseTest {
*/
@BeforeClass
public static void init() throws ZksnarkException {
- Args.setFullNodeAllowShieldedTransaction(true);
+ Args.getInstance().setAllowShieldedTransactionApi(true);
librustzcashInitZksnarkParams();
}
@@ -950,7 +950,7 @@ public void publicAddressAToShieldAddressNoToAddressFailure() {
*/
@Test
public void publicToShieldAddressAndShieldToPublicAddressWithZoreValueSuccess() {
- Args.setFullNodeAllowShieldedTransaction(true);
+ Args.getInstance().setAllowShieldedTransactionApi(true);
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
long fee = dbManager.getDynamicPropertiesStore().getShieldedTransactionFee();
diff --git a/framework/src/test/java/org/tron/core/capsule/utils/ExchangeProcessorTest.java b/framework/src/test/java/org/tron/core/capsule/utils/ExchangeProcessorTest.java
index 717c62b01a8..1f0be4b1f7c 100644
--- a/framework/src/test/java/org/tron/core/capsule/utils/ExchangeProcessorTest.java
+++ b/framework/src/test/java/org/tron/core/capsule/utils/ExchangeProcessorTest.java
@@ -138,12 +138,63 @@ public void testWithdraw() {
@Test
public void testStrictMath() {
long supply = 1_000_000_000_000_000_000L;
- ExchangeProcessor processor = new ExchangeProcessor(supply, false);
- long anotherTokenQuant = processor.exchange(4732214, 2202692725330L, 29218);
- processor = new ExchangeProcessor(supply, true);
- long result = processor.exchange(4732214, 2202692725330L, 29218);
- Assert.assertNotEquals(anotherTokenQuant, result);
+ long[][] testData = {
+ {4732214L, 2202692725330L, 29218L},
+ {5618633L, 556559904655L, 1L},
+ {9299554L, 1120271441185L, 7000L},
+ {62433133L, 12013267997895L, 100000L},
+ {64212664L, 725836766395L, 50000L},
+ {64126212L, 2895100109660L, 5000L},
+ {56459055L, 3288380567368L, 165000L},
+ {21084707L, 1589204008960L, 50000L},
+ {24120521L, 1243764649177L, 20000L},
+ {836877L, 212532333234L, 5293L},
+ {55879741L, 13424854054078L, 250000L},
+ {66388882L, 11300012790454L, 300000L},
+ {94470955L, 7941038150919L, 2000L},
+ {13613746L, 5012660712983L, 122L},
+ {71852829L, 5262251868618L, 396L},
+ {3857658L, 446109245044L, 20637L},
+ {35491863L, 3887393269796L, 100L},
+ {295632118L, 1265298439004L, 500000L},
+ {49320113L, 1692106302503L, 123267L},
+ {10966984L, 6222910652894L, 2018L},
+ {41634280L, 2004508994767L, 865L},
+ {10087714L, 6765558834714L, 1009L},
+ {42270078L, 210360843525L, 200000L},
+ {571091915L, 655011397250L, 2032520L},
+ {51026781L, 1635726339365L, 37L},
+ {61594L, 312318864132L, 500L},
+ {11616684L, 5875978057357L, 20L},
+ {60584529L, 1377717821301L, 78132L},
+ {29818073L, 3033545989651L, 182L},
+ {3855280L, 834647482043L, 16L},
+ {58310711L, 1431562205655L, 200000L},
+ {60226263L, 1386036785882L, 178226L},
+ {3537634L, 965771433992L, 225L},
+ {3760534L, 908700758784L, 328L},
+ {80913L, 301864126445L, 4L},
+ {3789271L, 901842209723L, 1L},
+ {4051904L, 843419481286L, 1005L},
+ {89141L, 282107742510L, 100L},
+ {90170L, 282854635378L, 26L},
+ {4229852L, 787503315944L, 137L},
+ {4259884L, 781975090197L, 295L},
+ {3627657L, 918682223700L, 34L},
+ {813519L, 457546358759L, 173L},
+ {89626L, 327856173057L, 27L},
+ {97368L, 306386489550L, 50L},
+ {93712L, 305866015731L, 4L},
+ {3281260L, 723656594544L, 40L},
+ {3442652L, 689908773685L, 18L},
+ };
+
+ for (long[] data : testData) {
+ ExchangeProcessor processor = new ExchangeProcessor(supply, false);
+ long anotherTokenQuant = processor.exchange(data[0], data[1], data[2]);
+ processor = new ExchangeProcessor(supply, true);
+ long result = processor.exchange(data[0], data[1], data[2]);
+ Assert.assertNotEquals(anotherTokenQuant, result);
+ }
}
-
-
}
diff --git a/framework/src/test/java/org/tron/core/config/args/ArgsTest.java b/framework/src/test/java/org/tron/core/config/args/ArgsTest.java
index 4bb8e7e4909..4b656e463be 100644
--- a/framework/src/test/java/org/tron/core/config/args/ArgsTest.java
+++ b/framework/src/test/java/org/tron/core/config/args/ArgsTest.java
@@ -57,7 +57,7 @@ public void destroy() {
@Test
public void get() {
- Args.setParam(new String[] {"-c", Constant.TEST_CONF}, Constant.TESTNET_CONF);
+ Args.setParam(new String[] {"-c", Constant.TEST_CONF, "--keystore"}, Constant.TESTNET_CONF);
CommonParameter parameter = Args.getInstance();
@@ -127,6 +127,8 @@ public void get() {
Assert.assertEquals(address,
ByteArray.toHexString(Args.getLocalWitnesses()
.getWitnessAccountAddress(CommonParameter.getInstance().isECKeyCryptoEngine())));
+
+ Assert.assertTrue(parameter.isKeystore());
}
@Test
diff --git a/framework/src/test/java/org/tron/core/db/AccountStoreTest.java b/framework/src/test/java/org/tron/core/db/AccountStoreTest.java
index 9249a3358dc..aab64df16c7 100755
--- a/framework/src/test/java/org/tron/core/db/AccountStoreTest.java
+++ b/framework/src/test/java/org/tron/core/db/AccountStoreTest.java
@@ -1,20 +1,29 @@
package org.tron.core.db;
import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
import com.google.protobuf.ByteString;
+import com.typesafe.config.Config;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.Mockito;
import org.tron.common.BaseTest;
import org.tron.common.utils.ByteArray;
import org.tron.core.Constant;
import org.tron.core.capsule.AccountCapsule;
import org.tron.core.config.args.Args;
import org.tron.core.db2.ISession;
+import org.tron.core.exception.TronError;
+import org.tron.core.net.peer.PeerManager;
import org.tron.core.store.AccountStore;
import org.tron.core.store.AssetIssueStore;
import org.tron.core.store.DynamicPropertiesStore;
@@ -61,6 +70,21 @@ public void init() {
init = true;
}
+ @Test
+ public void setAccountTest() throws Exception {
+ Field field = AccountStore.class.getDeclaredField("assertsAddress");
+ field.setAccessible(true);
+ field.set(AccountStore.class, new HashMap<>());
+ Config config = mock(Config.class);
+ Mockito.when(config.getObjectList("genesis.block.assets")).thenReturn(new ArrayList<>());
+ try {
+ AccountStore.setAccount(config);
+ Assert.fail();
+ } catch (Throwable e) {
+ Assert.assertTrue(e instanceof TronError);
+ }
+ }
+
@Test
public void get() {
//test get and has Method
diff --git a/framework/src/test/java/org/tron/core/db2/CheckpointV2Test.java b/framework/src/test/java/org/tron/core/db2/CheckpointV2Test.java
index dff2d376fd5..fb7f1987e9f 100644
--- a/framework/src/test/java/org/tron/core/db2/CheckpointV2Test.java
+++ b/framework/src/test/java/org/tron/core/db2/CheckpointV2Test.java
@@ -4,7 +4,7 @@
import com.google.common.primitives.Bytes;
import com.google.common.primitives.Longs;
import com.google.protobuf.ByteString;
-import java.io.File;
+import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -13,11 +13,12 @@
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
import org.tron.common.application.Application;
import org.tron.common.application.ApplicationFactory;
import org.tron.common.application.TronApplicationContext;
-import org.tron.common.utils.FileUtil;
import org.tron.common.utils.Sha256Hash;
import org.tron.core.Constant;
import org.tron.core.capsule.BlockCapsule;
@@ -34,10 +35,12 @@ public class CheckpointV2Test {
private TronApplicationContext context;
private Application appT;
private TestRevokingTronStore tronDatabase;
+ @Rule
+ public final TemporaryFolder temporaryFolder = new TemporaryFolder();
@Before
- public void init() {
- Args.setParam(new String[]{"-d", "output_SnapshotManager_test"},
+ public void init() throws IOException {
+ Args.setParam(new String[]{"-d", temporaryFolder.newFolder().toString()},
Constant.TEST_CONF);
Args.getInstance().getStorage().setCheckpointVersion(2);
Args.getInstance().getStorage().setCheckpointSync(true);
@@ -54,9 +57,6 @@ public void removeDb() {
Args.clearParam();
context.destroy();
tronDatabase.close();
- FileUtil.deleteDir(new File("output_SnapshotManager_test"));
- revokingDatabase.getCheckTmpStore().close();
- tronDatabase.close();
}
@Test
diff --git a/framework/src/test/java/org/tron/core/db2/RevokingDbWithCacheNewValueTest.java b/framework/src/test/java/org/tron/core/db2/RevokingDbWithCacheNewValueTest.java
index 2290df86978..f371f2348a7 100644
--- a/framework/src/test/java/org/tron/core/db2/RevokingDbWithCacheNewValueTest.java
+++ b/framework/src/test/java/org/tron/core/db2/RevokingDbWithCacheNewValueTest.java
@@ -1,22 +1,22 @@
package org.tron.core.db2;
-import java.io.File;
+import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
-import org.apache.commons.lang3.RandomStringUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
import org.tron.common.application.Application;
import org.tron.common.application.ApplicationFactory;
import org.tron.common.application.TronApplicationContext;
import org.tron.common.utils.ByteArray;
-import org.tron.common.utils.FileUtil;
import org.tron.common.utils.SessionOptional;
import org.tron.core.Constant;
import org.tron.core.capsule.utils.MarketUtils;
@@ -34,12 +34,14 @@ public class RevokingDbWithCacheNewValueTest {
private TronApplicationContext context;
private Application appT;
private TestRevokingTronStore tronDatabase;
+ @Rule
+ public final TemporaryFolder temporaryFolder = new TemporaryFolder();
private String databasePath = "";
@Before
- public void init() {
- databasePath = "output_revokingStore_test_" + RandomStringUtils.randomAlphanumeric(10);
+ public void init() throws IOException {
+ databasePath = temporaryFolder.newFolder().toString();
Args.setParam(new String[]{"-d", databasePath},
Constant.TEST_CONF);
context = new TronApplicationContext(DefaultConfig.class);
@@ -51,7 +53,6 @@ public void removeDb() {
Args.clearParam();
context.destroy();
tronDatabase.close();
- FileUtil.deleteDir(new File(databasePath));
}
@Test
diff --git a/framework/src/test/java/org/tron/core/db2/SnapshotImplTest.java b/framework/src/test/java/org/tron/core/db2/SnapshotImplTest.java
index aab6f656b1f..649056aa151 100644
--- a/framework/src/test/java/org/tron/core/db2/SnapshotImplTest.java
+++ b/framework/src/test/java/org/tron/core/db2/SnapshotImplTest.java
@@ -3,16 +3,16 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
-import java.io.File;
+import java.io.IOException;
import java.lang.reflect.Constructor;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
import org.tron.common.application.Application;
import org.tron.common.application.ApplicationFactory;
import org.tron.common.application.TronApplicationContext;
-import org.tron.common.utils.FileUtil;
import org.tron.core.Constant;
import org.tron.core.config.DefaultConfig;
import org.tron.core.config.args.Args;
@@ -26,10 +26,12 @@ public class SnapshotImplTest {
private TronApplicationContext context;
private Application appT;
private SnapshotManager revokingDatabase;
+ @Rule
+ public final TemporaryFolder temporaryFolder = new TemporaryFolder();
@Before
- public void init() {
- Args.setParam(new String[]{"-d", "output_revokingStore_test"}, Constant.TEST_CONF);
+ public void init() throws IOException {
+ Args.setParam(new String[]{"-d", temporaryFolder.newFolder().toString()}, Constant.TEST_CONF);
context = new TronApplicationContext(DefaultConfig.class);
appT = ApplicationFactory.create(context);
@@ -44,10 +46,7 @@ public void init() {
public void removeDb() {
Args.clearParam();
context.destroy();
- FileUtil.deleteDir(new File("output_revokingStore_test"));
-
tronDatabase.close();
- revokingDatabase.shutdown();
}
/**
diff --git a/framework/src/test/java/org/tron/core/db2/SnapshotManagerTest.java b/framework/src/test/java/org/tron/core/db2/SnapshotManagerTest.java
index 134dc99e51c..d6fd319e6a0 100644
--- a/framework/src/test/java/org/tron/core/db2/SnapshotManagerTest.java
+++ b/framework/src/test/java/org/tron/core/db2/SnapshotManagerTest.java
@@ -6,7 +6,7 @@
import com.google.common.collect.Maps;
import com.google.common.primitives.Longs;
import com.google.protobuf.ByteString;
-import java.io.File;
+import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@@ -15,11 +15,12 @@
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
import org.tron.common.application.Application;
import org.tron.common.application.ApplicationFactory;
import org.tron.common.application.TronApplicationContext;
-import org.tron.common.utils.FileUtil;
import org.tron.common.utils.Sha256Hash;
import org.tron.core.Constant;
import org.tron.core.capsule.BlockCapsule;
@@ -40,11 +41,13 @@ public class SnapshotManagerTest {
private TronApplicationContext context;
private Application appT;
private TestRevokingTronStore tronDatabase;
+ @Rule
+ public final TemporaryFolder temporaryFolder = new TemporaryFolder();
@Before
- public void init() {
- Args.setParam(new String[]{"-d", "output_SnapshotManager_test"},
+ public void init() throws IOException {
+ Args.setParam(new String[]{"-d", temporaryFolder.newFolder().toString()},
Constant.TEST_CONF);
context = new TronApplicationContext(DefaultConfig.class);
appT = ApplicationFactory.create(context);
@@ -59,9 +62,6 @@ public void removeDb() {
Args.clearParam();
context.destroy();
tronDatabase.close();
- FileUtil.deleteDir(new File("output_SnapshotManager_test"));
- revokingDatabase.getCheckTmpStore().close();
- tronDatabase.close();
}
@Test
diff --git a/framework/src/test/java/org/tron/core/db2/SnapshotRootTest.java b/framework/src/test/java/org/tron/core/db2/SnapshotRootTest.java
index 70b4d9eff30..635cc018cc2 100644
--- a/framework/src/test/java/org/tron/core/db2/SnapshotRootTest.java
+++ b/framework/src/test/java/org/tron/core/db2/SnapshotRootTest.java
@@ -1,10 +1,13 @@
package org.tron.core.db2;
import com.google.common.collect.Sets;
-import java.io.File;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
@@ -13,7 +16,9 @@
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
import org.springframework.util.CollectionUtils;
import org.tron.common.application.Application;
import org.tron.common.application.ApplicationFactory;
@@ -45,11 +50,13 @@ public class SnapshotRootTest {
"exchange","market_order","account-trace","contract-state","trans"));
private Set allDBNames;
private Set allRevokingDBNames;
+ @Rule
+ public final TemporaryFolder temporaryFolder = new TemporaryFolder();
@Before
- public void init() {
- Args.setParam(new String[]{"-d", "output_revokingStore_test"}, Constant.TEST_CONF);
+ public void init() throws IOException {
+ Args.setParam(new String[]{"-d", temporaryFolder.newFolder().toString()}, Constant.TEST_CONF);
context = new TronApplicationContext(DefaultConfig.class);
appT = ApplicationFactory.create(context);
}
@@ -58,7 +65,6 @@ public void init() {
public void removeDb() {
Args.clearParam();
context.destroy();
- FileUtil.deleteDir(new File("output_revokingStore_test"));
}
@Test
@@ -133,7 +139,9 @@ public void testSecondCacheCheck()
throws ItemNotFoundException {
revokingDatabase = context.getBean(SnapshotManager.class);
allRevokingDBNames = parseRevokingDBNames(context);
- allDBNames = Arrays.stream(new File("output_revokingStore_test/database").list())
+ Path path = Paths.get(Args.getInstance().getOutputDirectory(),
+ Args.getInstance().getStorage().getDbDirectory());
+ allDBNames = Arrays.stream(Objects.requireNonNull(path.toFile().list()))
.collect(Collectors.toSet());
if (CollectionUtils.isEmpty(allDBNames)) {
throw new ItemNotFoundException("No DBs found");
@@ -152,10 +160,13 @@ public void testSecondCacheCheckAddDb()
revokingDatabase = context.getBean(SnapshotManager.class);
allRevokingDBNames = parseRevokingDBNames(context);
allRevokingDBNames.add("secondCheckTestDB");
- FileUtil.createDirIfNotExists("output_revokingStore_test/database/secondCheckTestDB");
- allDBNames = Arrays.stream(new File("output_revokingStore_test/database").list())
+ Path path = Paths.get(Args.getInstance().getOutputDirectory(),
+ Args.getInstance().getStorage().getDbDirectory());
+ Path secondCheckTestDB = Paths.get(path.toString(), "secondCheckTestDB");
+ FileUtil.createDirIfNotExists(secondCheckTestDB.toString());
+ allDBNames = Arrays.stream(Objects.requireNonNull(path.toFile().list()))
.collect(Collectors.toSet());
- FileUtil.deleteDir(new File("output_revokingStore_test/database/secondCheckTestDB"));
+ FileUtil.deleteDir(secondCheckTestDB.toFile());
if (CollectionUtils.isEmpty(allDBNames)) {
throw new ItemNotFoundException("No DBs found");
}
diff --git a/framework/src/test/java/org/tron/core/exception/TronErrorTest.java b/framework/src/test/java/org/tron/core/exception/TronErrorTest.java
index b4c3dc4b07f..98d5596e251 100644
--- a/framework/src/test/java/org/tron/core/exception/TronErrorTest.java
+++ b/framework/src/test/java/org/tron/core/exception/TronErrorTest.java
@@ -59,7 +59,6 @@ public void testTronError() {
@Test
public void ZksnarkInitTest() {
try (MockedStatic mock = mockStatic(JLibrustzcash.class)) {
- mock.when(JLibrustzcash::isOpenZen).thenReturn(true);
mock.when(() -> JLibrustzcash.librustzcashInitZksnarkParams(any()))
.thenAnswer(invocation -> {
throw new ZksnarkException("Zksnark init failed");
diff --git a/framework/src/test/java/org/tron/core/jsonrpc/ApiUtilTest.java b/framework/src/test/java/org/tron/core/jsonrpc/ApiUtilTest.java
index 570e7ed3498..f62d47d5367 100644
--- a/framework/src/test/java/org/tron/core/jsonrpc/ApiUtilTest.java
+++ b/framework/src/test/java/org/tron/core/jsonrpc/ApiUtilTest.java
@@ -4,10 +4,13 @@
import static org.tron.keystore.Wallet.generateRandomBytes;
import com.google.protobuf.ByteString;
+import org.junit.AfterClass;
import org.junit.Assert;
+import org.junit.BeforeClass;
import org.junit.Test;
import org.tron.common.utils.ByteArray;
import org.tron.core.capsule.BlockCapsule;
+import org.tron.core.config.args.Args;
import org.tron.core.services.jsonrpc.JsonRpcApiUtil;
import org.tron.protos.Protocol.Block;
import org.tron.protos.Protocol.BlockHeader;
@@ -16,6 +19,16 @@
public class ApiUtilTest {
+ @BeforeClass
+ public static void init() {
+ Args.setParam(new String[]{}, "config-localtest.conf");
+ }
+
+ @AfterClass
+ public static void clear() {
+ Args.clearParam();
+ }
+
@Test
public void testGetBlockID() {
byte[] mockedHash = generateRandomBytes(128);
diff --git a/framework/src/test/java/org/tron/core/jsonrpc/JsonRpcTest.java b/framework/src/test/java/org/tron/core/jsonrpc/JsonRpcTest.java
index bef0b5a1593..bd357101da3 100644
--- a/framework/src/test/java/org/tron/core/jsonrpc/JsonRpcTest.java
+++ b/framework/src/test/java/org/tron/core/jsonrpc/JsonRpcTest.java
@@ -18,7 +18,7 @@
import org.tron.common.utils.ByteArray;
import org.tron.common.utils.ByteUtil;
import org.tron.common.utils.Commons;
-import org.tron.core.exception.JsonRpcInvalidParamsException;
+import org.tron.core.exception.jsonrpc.JsonRpcInvalidParamsException;
import org.tron.core.services.jsonrpc.JsonRpcApiUtil;
import org.tron.core.services.jsonrpc.TronJsonRpc.FilterRequest;
import org.tron.core.services.jsonrpc.filters.LogBlockQuery;
diff --git a/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java b/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java
index 0f2214c5c9c..f6f4a35c1b7 100644
--- a/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java
+++ b/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java
@@ -1,6 +1,7 @@
package org.tron.core.jsonrpc;
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.getByJsonBlockId;
+import static org.tron.core.services.jsonrpc.TronJsonRpcImpl.TAG_PENDING_SUPPORT_ERROR;
import com.alibaba.fastjson.JSON;
import com.google.gson.JsonArray;
@@ -33,9 +34,12 @@
import org.tron.core.capsule.AccountCapsule;
import org.tron.core.capsule.BlockCapsule;
import org.tron.core.capsule.TransactionCapsule;
+import org.tron.core.capsule.TransactionInfoCapsule;
+import org.tron.core.capsule.TransactionRetCapsule;
import org.tron.core.capsule.utils.BlockUtil;
import org.tron.core.config.args.Args;
-import org.tron.core.exception.JsonRpcInvalidParamsException;
+import org.tron.core.exception.jsonrpc.JsonRpcInternalException;
+import org.tron.core.exception.jsonrpc.JsonRpcInvalidParamsException;
import org.tron.core.services.NodeInfoService;
import org.tron.core.services.interfaceJsonRpcOnPBFT.JsonRpcServiceOnPBFT;
import org.tron.core.services.interfaceJsonRpcOnSolidity.JsonRpcServiceOnSolidity;
@@ -44,6 +48,7 @@
import org.tron.core.services.jsonrpc.TronJsonRpcImpl;
import org.tron.core.services.jsonrpc.filters.LogFilterWrapper;
import org.tron.core.services.jsonrpc.types.BlockResult;
+import org.tron.core.services.jsonrpc.types.TransactionReceipt;
import org.tron.core.services.jsonrpc.types.TransactionResult;
import org.tron.protos.Protocol;
import org.tron.protos.Protocol.Transaction.Contract.ContractType;
@@ -127,6 +132,7 @@ public void init() {
(Wallet.getAddressPreFixString() + "ED738B3A0FE390EAA71B768B6D02CDBD18FB207B"))))
.build();
+
transactionCapsule1 = new TransactionCapsule(transferContract1, ContractType.TransferContract);
transactionCapsule1.setBlockNum(blockCapsule1.getNum());
TransactionCapsule transactionCapsule2 = new TransactionCapsule(transferContract2,
@@ -155,6 +161,59 @@ public void init() {
dbManager.getTransactionStore()
.put(transactionCapsule3.getTransactionId().getBytes(), transactionCapsule3);
+ dbManager.getTransactionStore()
+ .put(transactionCapsule3.getTransactionId().getBytes(), transactionCapsule3);
+
+ blockCapsule0.getTransactions().forEach(tx -> {
+ TransactionCapsule transactionCapsule = new TransactionCapsule(tx.getInstance());
+ transactionCapsule.setBlockNum(blockCapsule0.getNum());
+ dbManager.getTransactionStore()
+ .put(transactionCapsule.getTransactionId().getBytes(), transactionCapsule);
+ });
+
+ TransactionRetCapsule transactionRetCapsule0 = new TransactionRetCapsule();
+ blockCapsule0.getTransactions().forEach(tx -> {
+ TransactionInfoCapsule transactionInfoCapsule = new TransactionInfoCapsule();
+ transactionInfoCapsule.setId(tx.getTransactionId().getBytes());
+ transactionInfoCapsule.setBlockNumber(blockCapsule0.getNum());
+ transactionRetCapsule0.addTransactionInfo(transactionInfoCapsule.getInstance());
+ });
+ dbManager.getTransactionRetStore().put(
+ ByteArray.fromLong(blockCapsule0.getNum()), transactionRetCapsule0);
+
+ List logs = new ArrayList<>();
+ logs.add(Protocol.TransactionInfo.Log.newBuilder()
+ .setAddress(ByteString.copyFrom("address1".getBytes()))
+ .setData(ByteString.copyFrom("data1".getBytes()))
+ .addTopics(ByteString.copyFrom("topic1".getBytes()))
+ .build());
+ logs.add(Protocol.TransactionInfo.Log.newBuilder()
+ .setAddress(ByteString.copyFrom("address2".getBytes()))
+ .setData(ByteString.copyFrom("data2".getBytes()))
+ .addTopics(ByteString.copyFrom("topic2".getBytes()))
+ .build());
+
+ TransactionRetCapsule transactionRetCapsule1 = new TransactionRetCapsule();
+ blockCapsule1.getTransactions().forEach(tx -> {
+ TransactionInfoCapsule transactionInfoCapsule = new TransactionInfoCapsule();
+ transactionInfoCapsule.setId(tx.getTransactionId().getBytes());
+ transactionInfoCapsule.setBlockNumber(blockCapsule1.getNum());
+ transactionInfoCapsule.addAllLog(logs);
+ transactionRetCapsule1.addTransactionInfo(transactionInfoCapsule.getInstance());
+ });
+ dbManager.getTransactionRetStore()
+ .put(ByteArray.fromLong(blockCapsule1.getNum()), transactionRetCapsule1);
+
+ TransactionRetCapsule transactionRetCapsule2 = new TransactionRetCapsule();
+ blockCapsule2.getTransactions().forEach(tx -> {
+ TransactionInfoCapsule transactionInfoCapsule = new TransactionInfoCapsule();
+ transactionInfoCapsule.setId(tx.getTransactionId().getBytes());
+ transactionInfoCapsule.setBlockNumber(blockCapsule2.getNum());
+ transactionRetCapsule2.addTransactionInfo(transactionInfoCapsule.getInstance());
+ });
+ dbManager.getTransactionRetStore()
+ .put(ByteArray.fromLong(blockCapsule2.getNum()), transactionRetCapsule2);
+
tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet, dbManager);
}
@@ -434,7 +493,8 @@ public void testGetByJsonBlockId() {
getByJsonBlockId("0xxabc", wallet);
Assert.fail("Expected to be thrown");
} catch (Exception e) {
- Assert.assertEquals("For input string: \"xabc\"", e.getMessage());
+ // https://bugs.openjdk.org/browse/JDK-8176425, from JDK 12, the exception message is changed
+ Assert.assertTrue(e.getMessage().startsWith("For input string: \"xabc\""));
}
}
@@ -968,4 +1028,76 @@ public void testNewFilterFinalizedBlock() {
Assert.assertEquals("invalid block range params", e.getMessage());
}
}
+
+ @Test
+ public void testGetBlockReceipts() {
+
+ try {
+ List transactionReceiptList = tronJsonRpc.getBlockReceipts("0x2710");
+ Assert.assertFalse(transactionReceiptList.isEmpty());
+ for (TransactionReceipt transactionReceipt: transactionReceiptList) {
+ TransactionReceipt transactionReceipt1
+ = tronJsonRpc.getTransactionReceipt(transactionReceipt.getTransactionHash());
+
+ Assert.assertEquals(
+ JSON.toJSONString(transactionReceipt), JSON.toJSONString(transactionReceipt1));
+ }
+ } catch (JsonRpcInvalidParamsException | JsonRpcInternalException e) {
+ throw new RuntimeException(e);
+ }
+
+ try {
+ List transactionReceiptList = tronJsonRpc.getBlockReceipts("earliest");
+ Assert.assertFalse(transactionReceiptList.isEmpty());
+ } catch (JsonRpcInvalidParamsException | JsonRpcInternalException e) {
+ throw new RuntimeException(e);
+ }
+
+ try {
+ List transactionReceiptList = tronJsonRpc.getBlockReceipts("latest");
+ Assert.assertFalse(transactionReceiptList.isEmpty());
+ } catch (JsonRpcInvalidParamsException | JsonRpcInternalException e) {
+ throw new RuntimeException(e);
+ }
+
+ try {
+ List transactionReceiptList = tronJsonRpc.getBlockReceipts("finalized");
+ Assert.assertFalse(transactionReceiptList.isEmpty());
+ } catch (JsonRpcInvalidParamsException | JsonRpcInternalException e) {
+ throw new RuntimeException(e);
+ }
+
+ try {
+ tronJsonRpc.getBlockReceipts("pending");
+ Assert.fail();
+ } catch (Exception e) {
+ Assert.assertEquals(TAG_PENDING_SUPPORT_ERROR, e.getMessage());
+ }
+
+ try {
+ tronJsonRpc.getBlockReceipts("test");
+ Assert.fail();
+ } catch (Exception e) {
+ Assert.assertEquals("invalid block number", e.getMessage());
+ }
+
+ try {
+ List transactionReceiptList = tronJsonRpc.getBlockReceipts("0x2");
+ Assert.assertNull(transactionReceiptList);
+ } catch (JsonRpcInvalidParamsException | JsonRpcInternalException e) {
+ throw new RuntimeException(e);
+ }
+
+ }
+
+ @Test
+ public void testWeb3ClientVersion() {
+ try {
+ String[] versions = tronJsonRpc.web3ClientVersion().split("/");
+ String javaVersion = versions[versions.length - 1];
+ Assert.assertTrue("Java1.8".equals(javaVersion) || "Java17".equals(javaVersion));
+ } catch (Exception e) {
+ Assert.fail();
+ }
+ }
}
diff --git a/framework/src/test/java/org/tron/core/jsonrpc/LogBlockQueryTest.java b/framework/src/test/java/org/tron/core/jsonrpc/LogBlockQueryTest.java
new file mode 100644
index 00000000000..deae8babb32
--- /dev/null
+++ b/framework/src/test/java/org/tron/core/jsonrpc/LogBlockQueryTest.java
@@ -0,0 +1,100 @@
+package org.tron.core.jsonrpc;
+
+import java.lang.reflect.Method;
+import java.util.BitSet;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import javax.annotation.Resource;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.tron.common.BaseTest;
+import org.tron.core.Constant;
+import org.tron.core.config.args.Args;
+import org.tron.core.services.jsonrpc.TronJsonRpc.FilterRequest;
+import org.tron.core.services.jsonrpc.filters.LogBlockQuery;
+import org.tron.core.services.jsonrpc.filters.LogFilterWrapper;
+import org.tron.core.store.SectionBloomStore;
+
+public class LogBlockQueryTest extends BaseTest {
+
+ @Resource
+ SectionBloomStore sectionBloomStore;
+ private ExecutorService sectionExecutor;
+ private Method partialMatchMethod;
+ private static final long CURRENT_MAX_BLOCK_NUM = 50000L;
+
+ static {
+ Args.setParam(new String[] {"--output-directory", dbPath()}, Constant.TEST_CONF);
+ }
+
+ @Before
+ public void setup() throws Exception {
+ sectionExecutor = Executors.newFixedThreadPool(5);
+
+ // Get private method through reflection
+ partialMatchMethod = LogBlockQuery.class.getDeclaredMethod("partialMatch",
+ int[][].class, int.class);
+ partialMatchMethod.setAccessible(true);
+
+ BitSet bitSet = new BitSet(SectionBloomStore.BLOCK_PER_SECTION);
+ bitSet.set(0, SectionBloomStore.BLOCK_PER_SECTION);
+ sectionBloomStore.put(0, 1, bitSet);
+ sectionBloomStore.put(0, 2, bitSet);
+ sectionBloomStore.put(0, 3, bitSet);
+ BitSet bitSet2 = new BitSet(SectionBloomStore.BLOCK_PER_SECTION);
+ bitSet2.set(0);
+ sectionBloomStore.put(1, 1, bitSet2);
+ sectionBloomStore.put(1, 2, bitSet2);
+ sectionBloomStore.put(1, 3, bitSet2);
+ }
+
+ @Test
+ public void testPartialMatch() throws Exception {
+ // Create a basic LogFilterWrapper
+ LogFilterWrapper logFilterWrapper = new LogFilterWrapper(
+ new FilterRequest("0x0", "0x1", null, null, null),
+ CURRENT_MAX_BLOCK_NUM, null, false);
+
+ LogBlockQuery logBlockQuery = new LogBlockQuery(logFilterWrapper, sectionBloomStore,
+ CURRENT_MAX_BLOCK_NUM, sectionExecutor);
+
+ int section = 0;
+
+ // Create a hit condition
+ int[][] bitIndexes = new int[][] {
+ {1, 2, 3}, // topic0
+ {4, 5, 6} // topic1
+ };
+
+ // topic0 hit section 0
+ BitSet result = (BitSet) partialMatchMethod.invoke(logBlockQuery, bitIndexes, section);
+ Assert.assertNotNull(result);
+ Assert.assertEquals(SectionBloomStore.BLOCK_PER_SECTION, result.cardinality());
+
+ // topic0 hit section 1
+ result = (BitSet) partialMatchMethod.invoke(logBlockQuery, bitIndexes, 1);
+ Assert.assertNotNull(result);
+ Assert.assertEquals(1, result.cardinality());
+
+ // not exist section 2
+ result = (BitSet) partialMatchMethod.invoke(logBlockQuery, bitIndexes, 2);
+ Assert.assertNotNull(result);
+ Assert.assertTrue(result.isEmpty());
+
+ //not hit
+ bitIndexes = new int[][] {
+ {1, 2, 4}, // topic0
+ {3, 5, 6} // topic1
+ };
+ result = (BitSet) partialMatchMethod.invoke(logBlockQuery, bitIndexes, section);
+ Assert.assertNotNull(result);
+ Assert.assertTrue(result.isEmpty());
+
+ // null condition
+ bitIndexes = new int[0][];
+ result = (BitSet) partialMatchMethod.invoke(logBlockQuery, bitIndexes, section);
+ Assert.assertNotNull(result);
+ Assert.assertTrue(result.isEmpty());
+ }
+}
\ No newline at end of file
diff --git a/framework/src/test/java/org/tron/core/jsonrpc/LogMatchExactlyTest.java b/framework/src/test/java/org/tron/core/jsonrpc/LogMatchExactlyTest.java
index 600cc52b58e..f55e3bc2cfa 100644
--- a/framework/src/test/java/org/tron/core/jsonrpc/LogMatchExactlyTest.java
+++ b/framework/src/test/java/org/tron/core/jsonrpc/LogMatchExactlyTest.java
@@ -9,7 +9,7 @@
import org.tron.common.runtime.vm.DataWord;
import org.tron.common.runtime.vm.LogInfo;
import org.tron.common.utils.ByteArray;
-import org.tron.core.exception.JsonRpcInvalidParamsException;
+import org.tron.core.exception.jsonrpc.JsonRpcInvalidParamsException;
import org.tron.core.services.jsonrpc.TronJsonRpc.FilterRequest;
import org.tron.core.services.jsonrpc.TronJsonRpc.LogFilterElement;
import org.tron.core.services.jsonrpc.filters.LogFilter;
diff --git a/framework/src/test/java/org/tron/core/net/BaseNet.java b/framework/src/test/java/org/tron/core/net/BaseNet.java
index 65771bae952..bdaab1b4301 100644
--- a/framework/src/test/java/org/tron/core/net/BaseNet.java
+++ b/framework/src/test/java/org/tron/core/net/BaseNet.java
@@ -1,24 +1,10 @@
package org.tron.core.net;
-import io.netty.bootstrap.Bootstrap;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelInitializer;
-import io.netty.channel.ChannelOption;
-import io.netty.channel.DefaultMessageSizeEstimator;
-import io.netty.channel.FixedRecvByteBufAllocator;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.channel.socket.nio.NioSocketChannel;
-import io.netty.handler.codec.ByteToMessageDecoder;
-import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
-import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
-import io.netty.handler.timeout.ReadTimeoutHandler;
-import io.netty.handler.timeout.WriteTimeoutHandler;
-import java.io.File;
import java.io.IOException;
import java.util.Collection;
+import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.junit.AfterClass;
import org.junit.Assert;
@@ -29,7 +15,6 @@
import org.tron.common.application.ApplicationFactory;
import org.tron.common.application.TronApplicationContext;
import org.tron.common.parameter.CommonParameter;
-import org.tron.common.utils.FileUtil;
import org.tron.common.utils.PublicMethod;
import org.tron.common.utils.ReflectUtils;
import org.tron.core.Constant;
@@ -53,30 +38,6 @@ public class BaseNet {
private static ExecutorService executorService = Executors.newFixedThreadPool(1);
- public static Channel connect(ByteToMessageDecoder decoder) throws InterruptedException {
- NioEventLoopGroup group = new NioEventLoopGroup(1);
- Bootstrap b = new Bootstrap();
- b.group(group).channel(NioSocketChannel.class)
- .handler(new ChannelInitializer() {
- @Override
- protected void initChannel(Channel ch) throws Exception {
- ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(256 * 1024));
- ch.config().setOption(ChannelOption.SO_RCVBUF, 256 * 1024);
- ch.config().setOption(ChannelOption.SO_BACKLOG, 1024);
- ch.pipeline()
- .addLast("readTimeoutHandler", new ReadTimeoutHandler(600, TimeUnit.SECONDS))
- .addLast("writeTimeoutHandler", new WriteTimeoutHandler(600, TimeUnit.SECONDS));
- ch.pipeline().addLast("protoPender", new ProtobufVarint32LengthFieldPrepender());
- ch.pipeline().addLast("lengthDecode", new ProtobufVarint32FrameDecoder());
- ch.pipeline().addLast("handshakeHandler", decoder);
- ch.closeFuture();
- }
- }).option(ChannelOption.SO_KEEPALIVE, true)
- .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 60000)
- .option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
- return b.connect(Constant.LOCAL_HOST, port).sync().channel();
- }
-
@BeforeClass
public static void init() throws Exception {
executorService.execute(() -> {
@@ -123,10 +84,12 @@ public static void init() throws Exception {
@AfterClass
public static void destroy() {
- Collection peerConnections = ReflectUtils
- .invokeMethod(tronNetDelegate, "getActivePeer");
- for (PeerConnection peer : peerConnections) {
- peer.getChannel().close();
+ if (Objects.nonNull(tronNetDelegate)) {
+ Collection peerConnections = ReflectUtils
+ .invokeMethod(tronNetDelegate, "getActivePeer");
+ for (PeerConnection peer : peerConnections) {
+ peer.getChannel().close();
+ }
}
Args.clearParam();
context.destroy();
diff --git a/framework/src/test/java/org/tron/core/net/P2pRateLimiterTest.java b/framework/src/test/java/org/tron/core/net/P2pRateLimiterTest.java
new file mode 100644
index 00000000000..8a1d9c52749
--- /dev/null
+++ b/framework/src/test/java/org/tron/core/net/P2pRateLimiterTest.java
@@ -0,0 +1,23 @@
+package org.tron.core.net;
+
+import static org.tron.core.net.message.MessageTypes.FETCH_INV_DATA;
+import static org.tron.core.net.message.MessageTypes.SYNC_BLOCK_CHAIN;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class P2pRateLimiterTest {
+ @Test
+ public void test() {
+ P2pRateLimiter limiter = new P2pRateLimiter();
+ limiter.register(SYNC_BLOCK_CHAIN.asByte(), 2);
+ limiter.acquire(SYNC_BLOCK_CHAIN.asByte());
+ boolean ret = limiter.tryAcquire(SYNC_BLOCK_CHAIN.asByte());
+ Assert.assertTrue(ret);
+ limiter.tryAcquire(SYNC_BLOCK_CHAIN.asByte());
+ ret = limiter.tryAcquire(SYNC_BLOCK_CHAIN.asByte());
+ Assert.assertFalse(ret);
+ ret = limiter.tryAcquire(FETCH_INV_DATA.asByte());
+ Assert.assertTrue(ret);
+ }
+}
diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandlerTest.java
index 5fd6d6725ba..43036ce142a 100644
--- a/framework/src/test/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandlerTest.java
+++ b/framework/src/test/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandlerTest.java
@@ -1,5 +1,7 @@
package org.tron.core.net.messagehandler;
+import static org.tron.core.net.message.MessageTypes.FETCH_INV_DATA;
+
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.lang.reflect.Field;
@@ -13,6 +15,7 @@
import org.tron.common.utils.Sha256Hash;
import org.tron.core.capsule.BlockCapsule;
import org.tron.core.config.Parameter;
+import org.tron.core.net.P2pRateLimiter;
import org.tron.core.net.TronNetDelegate;
import org.tron.core.net.message.adv.BlockMessage;
import org.tron.core.net.message.adv.FetchInvDataMessage;
@@ -55,6 +58,9 @@ public void testProcessMessage() throws Exception {
Mockito.when(advService.getMessage(new Item(blockId, Protocol.Inventory.InventoryType.BLOCK)))
.thenReturn(new BlockMessage(blockCapsule));
ReflectUtils.setFieldValue(fetchInvDataMsgHandler, "advService", advService);
+ P2pRateLimiter p2pRateLimiter = new P2pRateLimiter();
+ p2pRateLimiter.register(FETCH_INV_DATA.asByte(), 2);
+ Mockito.when(peer.getP2pRateLimiter()).thenReturn(p2pRateLimiter);
fetchInvDataMsgHandler.processMessage(peer,
new FetchInvDataMessage(blockIds, Protocol.Inventory.InventoryType.BLOCK));
@@ -74,6 +80,9 @@ public void testSyncFetchCheck() {
Cache- advInvSpread = CacheBuilder.newBuilder().maximumSize(100)
.expireAfterWrite(1, TimeUnit.HOURS).recordStats().build();
Mockito.when(peer.getAdvInvSpread()).thenReturn(advInvSpread);
+ P2pRateLimiter p2pRateLimiter = new P2pRateLimiter();
+ p2pRateLimiter.register(FETCH_INV_DATA.asByte(), 2);
+ Mockito.when(peer.getP2pRateLimiter()).thenReturn(p2pRateLimiter);
FetchInvDataMsgHandler fetchInvDataMsgHandler = new FetchInvDataMsgHandler();
@@ -93,4 +102,36 @@ public void testSyncFetchCheck() {
Assert.assertEquals(e.getMessage(), "minBlockNum: 16000, blockNum: 10000");
}
}
+
+ @Test
+ public void testRateLimiter() {
+ BlockCapsule.BlockId blockId = new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 10000L);
+ List blockIds = new LinkedList<>();
+ for (int i = 0; i <= 100; i++) {
+ blockIds.add(blockId);
+ }
+ FetchInvDataMessage msg =
+ new FetchInvDataMessage(blockIds, Protocol.Inventory.InventoryType.BLOCK);
+ PeerConnection peer = Mockito.mock(PeerConnection.class);
+ Mockito.when(peer.isNeedSyncFromUs()).thenReturn(true);
+ Cache
- advInvSpread = CacheBuilder.newBuilder().maximumSize(100)
+ .expireAfterWrite(1, TimeUnit.HOURS).recordStats().build();
+ Mockito.when(peer.getAdvInvSpread()).thenReturn(advInvSpread);
+ P2pRateLimiter p2pRateLimiter = new P2pRateLimiter();
+ p2pRateLimiter.register(FETCH_INV_DATA.asByte(), 1);
+ p2pRateLimiter.acquire(FETCH_INV_DATA.asByte());
+ Mockito.when(peer.getP2pRateLimiter()).thenReturn(p2pRateLimiter);
+ FetchInvDataMsgHandler fetchInvDataMsgHandler = new FetchInvDataMsgHandler();
+
+ try {
+ fetchInvDataMsgHandler.processMessage(peer, msg);
+ } catch (Exception e) {
+ Assert.assertEquals("fetch too many blocks, size:101", e.getMessage());
+ }
+ try {
+ fetchInvDataMsgHandler.processMessage(peer, msg);
+ } catch (Exception e) {
+ Assert.assertTrue(e.getMessage().endsWith("rate limit"));
+ }
+ }
}
diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandlerTest.java
index e654e1c9cc2..eccab2aeb00 100644
--- a/framework/src/test/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandlerTest.java
+++ b/framework/src/test/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandlerTest.java
@@ -55,6 +55,7 @@ public void init() throws Exception {
@Test
public void testProcessMessage() throws Exception {
try {
+ peer.setRemainNum(1);
handler.processMessage(peer, new SyncBlockChainMessage(new ArrayList<>()));
} catch (P2pException e) {
Assert.assertEquals("SyncBlockChain blockIds is empty", e.getMessage());
@@ -71,6 +72,10 @@ public void testProcessMessage() throws Exception {
Assert.assertNotNull(message.toString());
Assert.assertNotNull(((BlockInventoryMessage) message).getAnswerMessage());
Assert.assertFalse(f);
+ method.invoke(handler, peer, message);
+ method.invoke(handler, peer, message);
+ f = (boolean)method.invoke(handler, peer, message);
+ Assert.assertFalse(f);
Method method1 = handler.getClass().getDeclaredMethod(
"getLostBlockIds", List.class, BlockId.class);
diff --git a/framework/src/test/java/org/tron/core/net/services/HandShakeServiceTest.java b/framework/src/test/java/org/tron/core/net/services/HandShakeServiceTest.java
index f4fabce5d64..54ee84cee6c 100644
--- a/framework/src/test/java/org/tron/core/net/services/HandShakeServiceTest.java
+++ b/framework/src/test/java/org/tron/core/net/services/HandShakeServiceTest.java
@@ -21,7 +21,6 @@
import org.mockito.Mockito;
import org.springframework.context.ApplicationContext;
import org.tron.common.application.TronApplicationContext;
-import org.tron.common.utils.ByteArray;
import org.tron.common.utils.ReflectUtils;
import org.tron.common.utils.Sha256Hash;
import org.tron.core.ChainBaseManager;
@@ -34,6 +33,7 @@
import org.tron.core.net.message.handshake.HelloMessage;
import org.tron.core.net.peer.PeerConnection;
import org.tron.core.net.peer.PeerManager;
+import org.tron.core.net.service.handshake.HandshakeService;
import org.tron.p2p.P2pConfig;
import org.tron.p2p.base.Parameter;
import org.tron.p2p.connection.Channel;
@@ -101,6 +101,7 @@ public void testOkHelloMessage()
Node node = new Node(NetUtil.getNodeId(), a1.getAddress().getHostAddress(), null, a1.getPort());
HelloMessage helloMessage = new HelloMessage(node, System.currentTimeMillis(),
ChainBaseManager.getChainBaseManager());
+ Assert.assertNotNull(helloMessage.toString());
Assert.assertEquals(Version.getVersion(),
new String(helloMessage.getHelloMessage().getCodeVersion().toByteArray()));
@@ -126,13 +127,27 @@ public void testInvalidHelloMessage() {
//block hash is empty
try {
BlockCapsule.BlockId hid = ChainBaseManager.getChainBaseManager().getHeadBlockId();
- Protocol.HelloMessage.BlockId hBlockId = Protocol.HelloMessage.BlockId.newBuilder()
- .setHash(ByteString.copyFrom(new byte[0]))
+ Protocol.HelloMessage.BlockId okBlockId = Protocol.HelloMessage.BlockId.newBuilder()
+ .setHash(ByteString.copyFrom(new byte[32]))
.setNumber(hid.getNum())
.build();
- builder.setHeadBlockId(hBlockId);
+ Protocol.HelloMessage.BlockId invalidBlockId = Protocol.HelloMessage.BlockId.newBuilder()
+ .setHash(ByteString.copyFrom(new byte[31]))
+ .setNumber(hid.getNum())
+ .build();
+ builder.setHeadBlockId(invalidBlockId);
HelloMessage helloMessage = new HelloMessage(builder.build().toByteArray());
- Assert.assertTrue(!helloMessage.valid());
+ Assert.assertFalse(helloMessage.valid());
+
+ builder.setHeadBlockId(okBlockId);
+ builder.setGenesisBlockId(invalidBlockId);
+ HelloMessage helloMessage2 = new HelloMessage(builder.build().toByteArray());
+ Assert.assertFalse(helloMessage2.valid());
+
+ builder.setGenesisBlockId(okBlockId);
+ builder.setSolidBlockId(invalidBlockId);
+ HelloMessage helloMessage3 = new HelloMessage(builder.build().toByteArray());
+ Assert.assertFalse(helloMessage3.valid());
} catch (Exception e) {
Assert.fail();
}
@@ -214,7 +229,7 @@ public void testLowAndGenesisBlockNum() throws NoSuchMethodException {
Node node2 = new Node(NetUtil.getNodeId(), a1.getAddress().getHostAddress(), null, 10002);
- //lowestBlockNum > headBlockNum
+ //peer's lowestBlockNum > my headBlockNum => peer is light, LIGHT_NODE_SYNC_FAIL
Protocol.HelloMessage.Builder builder =
getHelloMessageBuilder(node2, System.currentTimeMillis(),
ChainBaseManager.getChainBaseManager());
@@ -226,7 +241,7 @@ public void testLowAndGenesisBlockNum() throws NoSuchMethodException {
Assert.fail();
}
- //genesisBlock is not equal
+ //genesisBlock is not equal => INCOMPATIBLE_CHAIN
builder = getHelloMessageBuilder(node2, System.currentTimeMillis(),
ChainBaseManager.getChainBaseManager());
BlockCapsule.BlockId gid = ChainBaseManager.getChainBaseManager().getGenesisBlockId();
@@ -242,9 +257,11 @@ public void testLowAndGenesisBlockNum() throws NoSuchMethodException {
Assert.fail();
}
- //solidityBlock <= us, but not contained
+ // peer's solidityBlock <= my solidityBlock, but not contained
+ // and my lowestBlockNum <= peer's solidityBlock => FORKED
builder = getHelloMessageBuilder(node2, System.currentTimeMillis(),
ChainBaseManager.getChainBaseManager());
+
BlockCapsule.BlockId sid = ChainBaseManager.getChainBaseManager().getSolidBlockId();
Random gen = new Random();
@@ -262,6 +279,46 @@ public void testLowAndGenesisBlockNum() throws NoSuchMethodException {
} catch (Exception e) {
Assert.fail();
}
+
+ // peer's solidityBlock <= my solidityBlock, but not contained
+ // and my lowestBlockNum > peer's solidityBlock => i am light, LIGHT_NODE_SYNC_FAIL
+ ChainBaseManager.getChainBaseManager().setLowestBlockNum(2);
+ try {
+ HelloMessage helloMessage = new HelloMessage(builder.build().toByteArray());
+ method.invoke(p2pEventHandler, peer, helloMessage.getSendBytes());
+ } catch (Exception e) {
+ Assert.fail();
+ }
+ }
+
+ @Test
+ public void testProcessHelloMessage() {
+ InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001);
+ Channel c1 = mock(Channel.class);
+ Mockito.when(c1.getInetSocketAddress()).thenReturn(a1);
+ Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress());
+ PeerManager.add(ctx, c1);
+ PeerConnection p = PeerManager.getPeers().get(0);
+
+ try {
+ Node node = new Node(NetUtil.getNodeId(), a1.getAddress().getHostAddress(),
+ null, a1.getPort());
+ Protocol.HelloMessage.Builder builder =
+ getHelloMessageBuilder(node, System.currentTimeMillis(),
+ ChainBaseManager.getChainBaseManager());
+ BlockCapsule.BlockId hid = ChainBaseManager.getChainBaseManager().getHeadBlockId();
+ Protocol.HelloMessage.BlockId invalidBlockId = Protocol.HelloMessage.BlockId.newBuilder()
+ .setHash(ByteString.copyFrom(new byte[31]))
+ .setNumber(hid.getNum())
+ .build();
+ builder.setHeadBlockId(invalidBlockId);
+
+ HelloMessage helloMessage = new HelloMessage(builder.build().toByteArray());
+ HandshakeService handshakeService = new HandshakeService();
+ handshakeService.processHelloMessage(p, helloMessage);
+ } catch (Exception e) {
+ Assert.fail();
+ }
}
private Protocol.HelloMessage.Builder getHelloMessageBuilder(Node from, long timestamp,
diff --git a/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java b/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java
index 5e22e538e80..2ed09019fc9 100644
--- a/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java
+++ b/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java
@@ -1,8 +1,9 @@
package org.tron.core.net.services;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
-import com.google.common.collect.Lists;
import com.google.protobuf.ByteString;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
@@ -12,7 +13,6 @@
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
-
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Assert;
@@ -21,19 +21,27 @@
import org.mockito.Mockito;
import org.springframework.context.ApplicationContext;
import org.tron.common.BaseTest;
+import org.tron.common.crypto.SignInterface;
+import org.tron.common.crypto.SignUtils;
+import org.tron.common.parameter.CommonParameter;
+import org.tron.common.utils.ByteArray;
import org.tron.common.utils.ReflectUtils;
+import org.tron.common.utils.Sha256Hash;
import org.tron.core.ChainBaseManager;
import org.tron.core.Constant;
import org.tron.core.capsule.BlockCapsule;
import org.tron.core.capsule.WitnessCapsule;
import org.tron.core.config.args.Args;
import org.tron.core.net.P2pEventHandlerImpl;
+import org.tron.core.net.TronNetDelegate;
+import org.tron.core.net.TronNetService;
import org.tron.core.net.message.adv.BlockMessage;
import org.tron.core.net.message.handshake.HelloMessage;
import org.tron.core.net.peer.Item;
import org.tron.core.net.peer.PeerConnection;
import org.tron.core.net.peer.PeerManager;
import org.tron.core.net.service.relay.RelayService;
+import org.tron.p2p.P2pConfig;
import org.tron.p2p.connection.Channel;
import org.tron.p2p.discover.Node;
import org.tron.p2p.utils.NetUtil;
@@ -44,11 +52,13 @@ public class RelayServiceTest extends BaseTest {
@Resource
private RelayService service;
- @Resource
- private PeerConnection peer;
+
@Resource
private P2pEventHandlerImpl p2pEventHandler;
+ @Resource
+ private TronNetService tronNetService;
+
/**
* init context.
*/
@@ -67,8 +77,12 @@ public void test() throws Exception {
}
private void initWitness() {
- byte[] key = Hex.decode("A04711BF7AFBDF44557DEFBDF4C4E7AA6138C6331F");
+ // key: 0154435f065a57fec6af1e12eaa2fa600030639448d7809f4c65bdcf8baed7e5
+ // Hex: A08A8D690BF36806C36A7DAE3AF796643C1AA9CC01
+ // Base58: 27bi7CD8d94AgXY3XFS9A9vx78Si5MqrECz
+ byte[] key = Hex.decode("A08A8D690BF36806C36A7DAE3AF796643C1AA9CC01");//exist already
WitnessCapsule witnessCapsule = chainBaseManager.getWitnessStore().get(key);
+ System.out.println(witnessCapsule.getInstance());
witnessCapsule.setVoteCount(1000);
chainBaseManager.getWitnessStore().put(key, witnessCapsule);
List list = new ArrayList<>();
@@ -83,7 +97,7 @@ public void testGetNextWitnesses() throws Exception {
"getNextWitnesses", ByteString.class, Integer.class);
method.setAccessible(true);
Set s1 = (Set) method.invoke(
- service, getFromHexString("A04711BF7AFBDF44557DEFBDF4C4E7AA6138C6331F"), 3);
+ service, getFromHexString("A08A8D690BF36806C36A7DAE3AF796643C1AA9CC01"), 3);
Assert.assertEquals(3, s1.size());
assertContains(s1, "A0299F3DB80A24B20A254B89CE639D59132F157F13");
assertContains(s1, "A0807337F180B62A77576377C1D0C9C24DF5C0DD62");
@@ -93,35 +107,51 @@ public void testGetNextWitnesses() throws Exception {
service, getFromHexString("A0FAB5FBF6AFB681E4E37E9D33BDDB7E923D6132E5"), 3);
Assert.assertEquals(3, s2.size());
assertContains(s2, "A014EEBE4D30A6ACB505C8B00B218BDC4733433C68");
- assertContains(s2, "A04711BF7AFBDF44557DEFBDF4C4E7AA6138C6331F");
+ assertContains(s2, "A08A8D690BF36806C36A7DAE3AF796643C1AA9CC01");
assertContains(s2, "A0299F3DB80A24B20A254B89CE639D59132F157F13");
Set s3 = (Set) method.invoke(
- service, getFromHexString("A04711BF7AFBDF44557DEFBDF4C4E7AA6138C6331F"), 1);
+ service, getFromHexString("A08A8D690BF36806C36A7DAE3AF796643C1AA9CC01"), 1);
Assert.assertEquals(1, s3.size());
assertContains(s3, "A0299F3DB80A24B20A254B89CE639D59132F157F13");
}
private void testBroadcast() {
try {
+ PeerConnection peer = new PeerConnection();
+ InetSocketAddress a1 = new InetSocketAddress("127.0.0.2", 10001);
+ Channel c1 = mock(Channel.class);
+ Mockito.when(c1.getInetSocketAddress()).thenReturn(a1);
+ Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress());
+ doNothing().when(c1).send((byte[]) any());
+
+ peer.setChannel(c1);
peer.setAddress(getFromHexString("A0299F3DB80A24B20A254B89CE639D59132F157F13"));
peer.setNeedSyncFromPeer(false);
peer.setNeedSyncFromUs(false);
- List peers = Lists.newArrayList();
+ List peers = new ArrayList<>();
peers.add(peer);
- ReflectUtils.setFieldValue(p2pEventHandler, "activePeers", peers);
+
+ TronNetDelegate tronNetDelegate = Mockito.mock(TronNetDelegate.class);
+ Mockito.doReturn(peers).when(tronNetDelegate).getActivePeer();
+
+ Field field = service.getClass().getDeclaredField("tronNetDelegate");
+ field.setAccessible(true);
+ field.set(service, tronNetDelegate);
+
BlockCapsule blockCapsule = new BlockCapsule(chainBaseManager.getHeadBlockNum() + 1,
chainBaseManager.getHeadBlockId(),
- 0, getFromHexString("A04711BF7AFBDF44557DEFBDF4C4E7AA6138C6331F"));
+ 0, getFromHexString("A08A8D690BF36806C36A7DAE3AF796643C1AA9CC01"));
BlockMessage msg = new BlockMessage(blockCapsule);
service.broadcast(msg);
Item item = new Item(blockCapsule.getBlockId(), Protocol.Inventory.InventoryType.BLOCK);
Assert.assertEquals(1, peer.getAdvInvSpread().size());
Assert.assertNotNull(peer.getAdvInvSpread().getIfPresent(item));
peer.getChannel().close();
- } catch (NullPointerException e) {
- System.out.println(e);
+ } catch (Exception e) {
+ logger.info("", e);
+ assert false;
}
}
@@ -135,20 +165,32 @@ private ByteString getFromHexString(String s) {
}
private void testCheckHelloMessage() {
- ByteString address = getFromHexString("A04711BF7AFBDF44557DEFBDF4C4E7AA6138C6331F");
+ String key = "0154435f065a57fec6af1e12eaa2fa600030639448d7809f4c65bdcf8baed7e5";
+ ByteString address = getFromHexString("A08A8D690BF36806C36A7DAE3AF796643C1AA9CC01");
InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001);
Node node = new Node(NetUtil.getNodeId(), a1.getAddress().getHostAddress(),
null, a1.getPort());
+
+ SignInterface cryptoEngine = SignUtils.fromPrivate(ByteArray.fromHexString(key),
+ Args.getInstance().isECKeyCryptoEngine());
HelloMessage helloMessage = new HelloMessage(node, System.currentTimeMillis(),
ChainBaseManager.getChainBaseManager());
+ ByteString sig = ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine
+ .signHash(Sha256Hash.of(CommonParameter.getInstance()
+ .isECKeyCryptoEngine(), ByteArray.fromLong(helloMessage
+ .getTimestamp())).getBytes())));
helloMessage.setHelloMessage(helloMessage.getHelloMessage().toBuilder()
- .setAddress(address).build());
+ .setAddress(address)
+ .setSignature(sig)
+ .build());
+
Channel c1 = mock(Channel.class);
Mockito.when(c1.getInetSocketAddress()).thenReturn(a1);
Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress());
Channel c2 = mock(Channel.class);
Mockito.when(c2.getInetSocketAddress()).thenReturn(a1);
Mockito.when(c2.getInetAddress()).thenReturn(a1.getAddress());
+
Args.getInstance().fastForward = true;
ApplicationContext ctx = (ApplicationContext) ReflectUtils.getFieldObject(p2pEventHandler,
"ctx");
@@ -158,14 +200,23 @@ private void testCheckHelloMessage() {
PeerConnection peer2 = PeerManager.add(ctx, c2);
assert peer2 != null;
peer2.setAddress(address);
+
+ ReflectUtils.setFieldValue(tronNetService, "p2pConfig", new P2pConfig());
+
try {
Field field = service.getClass().getDeclaredField("witnessScheduleStore");
field.setAccessible(true);
field.set(service, chainBaseManager.getWitnessScheduleStore());
+
+ Field field2 = service.getClass().getDeclaredField("manager");
+ field2.setAccessible(true);
+ field2.set(service, dbManager);
+
boolean res = service.checkHelloMessage(helloMessage, c1);
- Assert.assertFalse(res);
+ Assert.assertTrue(res);
} catch (Exception e) {
- logger.info("{}", e.getMessage());
+ logger.info("", e);
+ assert false;
}
}
}
\ No newline at end of file
diff --git a/framework/src/test/java/org/tron/core/net/services/SyncServiceTest.java b/framework/src/test/java/org/tron/core/net/services/SyncServiceTest.java
index c2883fb349d..e5b111a7abe 100644
--- a/framework/src/test/java/org/tron/core/net/services/SyncServiceTest.java
+++ b/framework/src/test/java/org/tron/core/net/services/SyncServiceTest.java
@@ -19,6 +19,7 @@
import org.springframework.context.ApplicationContext;
import org.tron.common.application.TronApplicationContext;
import org.tron.common.utils.ReflectUtils;
+import org.tron.common.utils.Sha256Hash;
import org.tron.core.Constant;
import org.tron.core.capsule.BlockCapsule;
import org.tron.core.config.DefaultConfig;
@@ -91,6 +92,13 @@ public void testStartSync() {
ReflectUtils.setFieldValue(peer, "tronState", TronState.INIT);
+ try {
+ peer.setBlockBothHave(new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, -1));
+ service.syncNext(peer);
+ } catch (Exception e) {
+ // no need to deal with
+ }
+
service.startSync(peer);
} catch (Exception e) {
// no need to deal with
diff --git a/framework/src/test/java/org/tron/core/services/ProposalServiceTest.java b/framework/src/test/java/org/tron/core/services/ProposalServiceTest.java
index 300a38a0916..e81c75948b7 100644
--- a/framework/src/test/java/org/tron/core/services/ProposalServiceTest.java
+++ b/framework/src/test/java/org/tron/core/services/ProposalServiceTest.java
@@ -1,7 +1,9 @@
package org.tron.core.services;
+import static org.tron.core.Constant.MAX_PROPOSAL_EXPIRE_TIME;
import static org.tron.core.utils.ProposalUtil.ProposalType.CONSENSUS_LOGIC_OPTIMIZATION;
import static org.tron.core.utils.ProposalUtil.ProposalType.ENERGY_FEE;
+import static org.tron.core.utils.ProposalUtil.ProposalType.PROPOSAL_EXPIRE_TIME;
import static org.tron.core.utils.ProposalUtil.ProposalType.TRANSACTION_FEE;
import static org.tron.core.utils.ProposalUtil.ProposalType.WITNESS_127_PAY_PER_BLOCK;
@@ -13,6 +15,7 @@
import org.junit.BeforeClass;
import org.junit.Test;
import org.tron.common.BaseTest;
+import org.tron.common.parameter.CommonParameter;
import org.tron.core.Constant;
import org.tron.core.capsule.ProposalCapsule;
import org.tron.core.config.args.Args;
@@ -131,4 +134,21 @@ public void testUpdateConsensusLogicOptimization() {
Assert.assertTrue(dbManager.getDynamicPropertiesStore().disableJavaLangMath());
}
+ @Test
+ public void testProposalExpireTime() {
+ long defaultWindow = dbManager.getDynamicPropertiesStore().getProposalExpireTime();
+ long proposalExpireTime = CommonParameter.getInstance().getProposalExpireTime();
+ Assert.assertEquals(proposalExpireTime, defaultWindow);
+
+ Proposal proposal = Proposal.newBuilder().putParameters(PROPOSAL_EXPIRE_TIME.getCode(),
+ 31536000000L).build();
+ ProposalCapsule proposalCapsule = new ProposalCapsule(proposal);
+ proposalCapsule.setExpirationTime(1627279200000L);
+ boolean result = ProposalService.process(dbManager, proposalCapsule);
+ Assert.assertTrue(result);
+
+ long window = dbManager.getDynamicPropertiesStore().getProposalExpireTime();
+ Assert.assertEquals(MAX_PROPOSAL_EXPIRE_TIME - 3000, window);
+ }
+
}
\ No newline at end of file
diff --git a/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java
index 3ae090d3caf..3af0b8fb9b2 100644
--- a/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java
+++ b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java
@@ -60,8 +60,6 @@
import org.tron.core.config.DefaultConfig;
import org.tron.core.config.args.Args;
import org.tron.core.db.Manager;
-import org.tron.core.services.interfaceOnPBFT.RpcApiServiceOnPBFT;
-import org.tron.core.services.interfaceOnSolidity.RpcApiServiceOnSolidity;
import org.tron.protos.Protocol;
import org.tron.protos.Protocol.Account;
import org.tron.protos.Protocol.Block;
@@ -144,11 +142,11 @@ public static void init() throws IOException {
getInstance().setMetricsPrometheusPort(PublicMethod.chooseRandomPort());
getInstance().setMetricsPrometheusEnable(true);
getInstance().setP2pDisable(true);
- String fullNode = String.format("%s:%d", getInstance().getNodeLanIp(),
+ String fullNode = String.format("%s:%d", Constant.LOCAL_HOST,
getInstance().getRpcPort());
- String solidityNode = String.format("%s:%d", getInstance().getNodeLanIp(),
+ String solidityNode = String.format("%s:%d", Constant.LOCAL_HOST,
getInstance().getRpcOnSolidityPort());
- String pBFTNode = String.format("%s:%d", getInstance().getNodeLanIp(),
+ String pBFTNode = String.format("%s:%d", Constant.LOCAL_HOST,
getInstance().getRpcOnPBFTPort());
ManagedChannel channelFull = ManagedChannelBuilder.forTarget(fullNode)
diff --git a/framework/src/test/java/org/tron/core/services/filter/HttpApiAccessFilterTest.java b/framework/src/test/java/org/tron/core/services/filter/HttpApiAccessFilterTest.java
index 420d890aa48..0d2c9c9ae78 100644
--- a/framework/src/test/java/org/tron/core/services/filter/HttpApiAccessFilterTest.java
+++ b/framework/src/test/java/org/tron/core/services/filter/HttpApiAccessFilterTest.java
@@ -38,7 +38,7 @@ public class HttpApiAccessFilterTest extends BaseTest {
static {
Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF);
- Args.getInstance().setFullNodeAllowShieldedTransactionArgs(false);
+ Args.getInstance().setAllowShieldedTransactionApi(false);
Args.getInstance().setFullNodeHttpEnable(true);
Args.getInstance().setFullNodeHttpPort(PublicMethod.chooseRandomPort());
Args.getInstance().setPBFTHttpEnable(true);
diff --git a/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java b/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java
index 84869ea0750..d98e2c9267e 100644
--- a/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java
+++ b/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java
@@ -25,9 +25,6 @@
import org.tron.core.Constant;
import org.tron.core.config.DefaultConfig;
import org.tron.core.config.args.Args;
-import org.tron.core.services.RpcApiService;
-import org.tron.core.services.interfaceOnPBFT.RpcApiServiceOnPBFT;
-import org.tron.core.services.interfaceOnSolidity.RpcApiServiceOnSolidity;
@Slf4j
public class LiteFnQueryGrpcInterceptorTest {
@@ -62,11 +59,11 @@ public static void init() throws IOException {
Args.getInstance().setRpcPBFTEnable(true);
Args.getInstance().setRpcOnPBFTPort(PublicMethod.chooseRandomPort());
Args.getInstance().setP2pDisable(true);
- String fullnode = String.format("%s:%d", Args.getInstance().getNodeLanIp(),
+ String fullnode = String.format("%s:%d", Constant.LOCAL_HOST,
Args.getInstance().getRpcPort());
- String solidityNode = String.format("%s:%d", Args.getInstance().getNodeLanIp(),
+ String solidityNode = String.format("%s:%d", Constant.LOCAL_HOST,
Args.getInstance().getRpcOnSolidityPort());
- String pBFTNode = String.format("%s:%d", Args.getInstance().getNodeLanIp(),
+ String pBFTNode = String.format("%s:%d", Constant.LOCAL_HOST,
Args.getInstance().getRpcOnPBFTPort());
channelFull = ManagedChannelBuilder.forTarget(fullnode)
.usePlaintext()
diff --git a/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryHttpFilterTest.java b/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryHttpFilterTest.java
index 0f0bdf1eb1f..978042a8578 100644
--- a/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryHttpFilterTest.java
+++ b/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryHttpFilterTest.java
@@ -31,7 +31,7 @@ public class LiteFnQueryHttpFilterTest extends BaseTest {
static {
Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF);
- Args.getInstance().setFullNodeAllowShieldedTransactionArgs(false);
+ Args.getInstance().setAllowShieldedTransactionApi(false);
Args.getInstance().setRpcEnable(false);
Args.getInstance().setRpcSolidityEnable(false);
Args.getInstance().setRpcPBFTEnable(false);
diff --git a/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java b/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java
index 900ca304e7d..ce7efabef0c 100644
--- a/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java
+++ b/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java
@@ -36,8 +36,6 @@
import org.tron.core.config.DefaultConfig;
import org.tron.core.config.args.Args;
import org.tron.core.services.RpcApiService;
-import org.tron.core.services.interfaceOnPBFT.RpcApiServiceOnPBFT;
-import org.tron.core.services.interfaceOnSolidity.RpcApiServiceOnSolidity;
import org.tron.protos.Protocol.Transaction;
@Slf4j
@@ -63,11 +61,11 @@ public static void init() throws IOException {
Args.getInstance().setRpcPBFTEnable(true);
Args.getInstance().setRpcOnPBFTPort(PublicMethod.chooseRandomPort());
Args.getInstance().setP2pDisable(true);
- String fullNode = String.format("%s:%d", Args.getInstance().getNodeLanIp(),
+ String fullNode = String.format("%s:%d", Constant.LOCAL_HOST,
Args.getInstance().getRpcPort());
- String solidityNode = String.format("%s:%d", Args.getInstance().getNodeLanIp(),
+ String solidityNode = String.format("%s:%d", Constant.LOCAL_HOST,
Args.getInstance().getRpcOnSolidityPort());
- String pBFTNode = String.format("%s:%d", Args.getInstance().getNodeLanIp(),
+ String pBFTNode = String.format("%s:%d", Constant.LOCAL_HOST,
Args.getInstance().getRpcOnPBFTPort());
ManagedChannel channelFull = ManagedChannelBuilder.forTarget(fullNode)
diff --git a/framework/src/test/java/org/tron/core/services/http/GetRewardServletTest.java b/framework/src/test/java/org/tron/core/services/http/GetRewardServletTest.java
index 404e154a4c3..bd367fc3700 100644
--- a/framework/src/test/java/org/tron/core/services/http/GetRewardServletTest.java
+++ b/framework/src/test/java/org/tron/core/services/http/GetRewardServletTest.java
@@ -58,7 +58,7 @@ public MockHttpServletRequest createRequest(String contentType) {
@Before
public void init() {
manager.getDynamicPropertiesStore().saveChangeDelegation(1);
- byte[] sr = decodeFromBase58Check("27VZHn9PFZwNh7o2EporxmLkpe157iWZVkh");
+ byte[] sr = decodeFromBase58Check("27bi7CD8d94AgXY3XFS9A9vx78Si5MqrECz");
delegationStore.setBrokerage(0, sr, 10);
delegationStore.setWitnessVote(0, sr, 100000000);
}
@@ -66,7 +66,7 @@ public void init() {
@Test
public void getRewardValueByJsonTest() {
int expect = 138181;
- String jsonParam = "{\"address\": \"27VZHn9PFZwNh7o2EporxmLkpe157iWZVkh\"}";
+ String jsonParam = "{\"address\": \"27bi7CD8d94AgXY3XFS9A9vx78Si5MqrECz\"}";
MockHttpServletRequest request = createRequest("application/json");
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContent(jsonParam.getBytes());
@@ -84,7 +84,7 @@ public void getRewardValueByJsonTest() {
@Test
public void getRewardByJsonUTF8Test() {
int expect = 138181;
- String jsonParam = "{\"address\": \"27VZHn9PFZwNh7o2EporxmLkpe157iWZVkh\"}";
+ String jsonParam = "{\"address\": \"27bi7CD8d94AgXY3XFS9A9vx78Si5MqrECz\"}";
MockHttpServletRequest request = createRequest("application/json; charset=utf-8");
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContent(jsonParam.getBytes());
@@ -105,7 +105,7 @@ public void getRewardValueTest() {
MockHttpServletRequest request = createRequest("application/x-www-form-urlencoded");
MockHttpServletResponse response = new MockHttpServletResponse();
mortgageService.payStandbyWitness();
- request.addParameter("address", "27VZHn9PFZwNh7o2EporxmLkpe157iWZVkh");
+ request.addParameter("address", "27bi7CD8d94AgXY3XFS9A9vx78Si5MqrECz");
getRewardServlet.doPost(request, response);
try {
String contentAsString = response.getContentAsString();
diff --git a/framework/src/test/java/org/tron/core/services/jsonrpc/BuildArgumentsTest.java b/framework/src/test/java/org/tron/core/services/jsonrpc/BuildArgumentsTest.java
index f9e264c515f..952e9c81467 100644
--- a/framework/src/test/java/org/tron/core/services/jsonrpc/BuildArgumentsTest.java
+++ b/framework/src/test/java/org/tron/core/services/jsonrpc/BuildArgumentsTest.java
@@ -8,8 +8,8 @@
import org.tron.core.Constant;
import org.tron.core.Wallet;
import org.tron.core.config.args.Args;
-import org.tron.core.exception.JsonRpcInvalidParamsException;
-import org.tron.core.exception.JsonRpcInvalidRequestException;
+import org.tron.core.exception.jsonrpc.JsonRpcInvalidParamsException;
+import org.tron.core.exception.jsonrpc.JsonRpcInvalidRequestException;
import org.tron.core.services.jsonrpc.types.BuildArguments;
import org.tron.core.services.jsonrpc.types.CallArguments;
import org.tron.protos.Protocol;
diff --git a/framework/src/test/java/org/tron/core/services/jsonrpc/CallArgumentsTest.java b/framework/src/test/java/org/tron/core/services/jsonrpc/CallArgumentsTest.java
index 19dd76e5e07..1d7f568453b 100644
--- a/framework/src/test/java/org/tron/core/services/jsonrpc/CallArgumentsTest.java
+++ b/framework/src/test/java/org/tron/core/services/jsonrpc/CallArgumentsTest.java
@@ -8,8 +8,8 @@
import org.tron.core.Constant;
import org.tron.core.Wallet;
import org.tron.core.config.args.Args;
-import org.tron.core.exception.JsonRpcInvalidParamsException;
-import org.tron.core.exception.JsonRpcInvalidRequestException;
+import org.tron.core.exception.jsonrpc.JsonRpcInvalidParamsException;
+import org.tron.core.exception.jsonrpc.JsonRpcInvalidRequestException;
import org.tron.core.services.jsonrpc.types.CallArguments;
import org.tron.protos.Protocol;
diff --git a/framework/src/test/java/org/tron/core/services/jsonrpc/JsonRpcErrorResolverTest.java b/framework/src/test/java/org/tron/core/services/jsonrpc/JsonRpcErrorResolverTest.java
new file mode 100644
index 00000000000..d8e64308ab8
--- /dev/null
+++ b/framework/src/test/java/org/tron/core/services/jsonrpc/JsonRpcErrorResolverTest.java
@@ -0,0 +1,75 @@
+package org.tron.core.services.jsonrpc;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.googlecode.jsonrpc4j.ErrorData;
+import com.googlecode.jsonrpc4j.ErrorResolver.JsonError;
+import com.googlecode.jsonrpc4j.JsonRpcError;
+import com.googlecode.jsonrpc4j.JsonRpcErrors;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.Assert;
+import org.junit.Test;
+import org.tron.core.exception.jsonrpc.JsonRpcException;
+import org.tron.core.exception.jsonrpc.JsonRpcInternalException;
+import org.tron.core.exception.jsonrpc.JsonRpcInvalidParamsException;
+import org.tron.core.exception.jsonrpc.JsonRpcInvalidRequestException;
+
+public class JsonRpcErrorResolverTest {
+
+ private final JsonRpcErrorResolver resolver = JsonRpcErrorResolver.INSTANCE;
+
+ @JsonRpcErrors({
+ @JsonRpcError(exception = JsonRpcInvalidRequestException.class, code = -32600, data = "{}"),
+ @JsonRpcError(exception = JsonRpcInvalidParamsException.class, code = -32602, data = "{}"),
+ @JsonRpcError(exception = JsonRpcInternalException.class, code = -32000, data = "{}"),
+ @JsonRpcError(exception = JsonRpcException.class, code = -1)
+ })
+ public void dummyMethod() {
+ }
+
+ @Test
+ public void testResolveErrorWithTronException() throws Exception {
+
+ String message = "JsonRpcInvalidRequestException";
+
+ JsonRpcException exception = new JsonRpcInvalidRequestException(message);
+ Method method = this.getClass().getMethod("dummyMethod");
+ List arguments = new ArrayList<>();
+
+ JsonError error = resolver.resolveError(exception, method, arguments);
+ Assert.assertNotNull(error);
+ Assert.assertEquals(-32600, error.code);
+ Assert.assertEquals(message, error.message);
+ Assert.assertEquals("{}", error.data);
+
+ message = "JsonRpcInternalException";
+ String data = "JsonRpcInternalException data";
+ exception = new JsonRpcInternalException(message, data);
+ error = resolver.resolveError(exception, method, arguments);
+
+ Assert.assertNotNull(error);
+ Assert.assertEquals(-32000, error.code);
+ Assert.assertEquals(message, error.message);
+ Assert.assertEquals(data, error.data);
+
+ exception = new JsonRpcInternalException(message, null);
+ error = resolver.resolveError(exception, method, arguments);
+
+ Assert.assertNotNull(error);
+ Assert.assertEquals(-32000, error.code);
+ Assert.assertEquals(message, error.message);
+ Assert.assertEquals("{}", error.data);
+
+ message = "JsonRpcException";
+ exception = new JsonRpcException(message, null);
+ error = resolver.resolveError(exception, method, arguments);
+
+ Assert.assertNotNull(error);
+ Assert.assertEquals(-1, error.code);
+ Assert.assertEquals(message, error.message);
+ Assert.assertTrue(error.data instanceof ErrorData);
+
+ }
+
+}
\ No newline at end of file
diff --git a/framework/src/test/java/org/tron/core/services/jsonrpc/TransactionReceiptTest.java b/framework/src/test/java/org/tron/core/services/jsonrpc/TransactionReceiptTest.java
index f10526e30a4..23bc11e293f 100644
--- a/framework/src/test/java/org/tron/core/services/jsonrpc/TransactionReceiptTest.java
+++ b/framework/src/test/java/org/tron/core/services/jsonrpc/TransactionReceiptTest.java
@@ -8,31 +8,32 @@
import org.tron.common.utils.ByteArray;
import org.tron.core.Constant;
import org.tron.core.Wallet;
+import org.tron.core.capsule.BlockCapsule;
import org.tron.core.capsule.TransactionRetCapsule;
import org.tron.core.config.args.Args;
+import org.tron.core.exception.jsonrpc.JsonRpcInternalException;
import org.tron.core.services.jsonrpc.types.TransactionReceipt;
+import org.tron.core.services.jsonrpc.types.TransactionReceipt.TransactionContext;
import org.tron.core.store.TransactionRetStore;
import org.tron.protos.Protocol;
public class TransactionReceiptTest extends BaseTest {
- @Resource
- private Wallet wallet;
+ @Resource private Wallet wallet;
- @Resource
- private TransactionRetStore transactionRetStore;
+ @Resource private TransactionRetStore transactionRetStore;
static {
- Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF);
+ Args.setParam(new String[] {"-d", dbPath()}, Constant.TEST_CONF);
}
@Test
- public void testTransactionReceipt() {
+ public void testTransactionReceipt() throws JsonRpcInternalException {
Protocol.TransactionInfo transactionInfo = Protocol.TransactionInfo.newBuilder()
.setId(ByteString.copyFrom("1".getBytes()))
.setContractAddress(ByteString.copyFrom("address1".getBytes()))
.setReceipt(Protocol.ResourceReceipt.newBuilder()
- .setEnergyUsageTotal(0L)
+ .setEnergyUsageTotal(100L)
.setResult(Protocol.Transaction.Result.contractResult.DEFAULT)
.build())
.addLog(Protocol.TransactionInfo.Log.newBuilder()
@@ -50,17 +51,49 @@ public void testTransactionReceipt() {
raw.addContract(contract.build());
Protocol.Transaction transaction = Protocol.Transaction.newBuilder().setRawData(raw).build();
- TransactionReceipt transactionReceipt = new TransactionReceipt(
- Protocol.Block.newBuilder().setBlockHeader(
- Protocol.BlockHeader.newBuilder().setRawData(
- Protocol.BlockHeader.raw.newBuilder().setNumber(1))).addTransactions(
- transaction).build(), transactionInfo, wallet);
+ Protocol.Block block = Protocol.Block.newBuilder().setBlockHeader(
+ Protocol.BlockHeader.newBuilder().setRawData(
+ Protocol.BlockHeader.raw.newBuilder().setNumber(1))).addTransactions(
+ transaction).build();
- Assert.assertEquals(transactionReceipt.getBlockNumber(),"0x1");
- Assert.assertEquals(transactionReceipt.getTransactionIndex(),"0x0");
- Assert.assertEquals(transactionReceipt.getLogs().length,1);
- Assert.assertEquals(transactionReceipt.getBlockHash(),
- "0x0000000000000001464f071c8a336fd22eb5145dff1b245bda013ec89add8497");
- }
+ BlockCapsule blockCapsule = new BlockCapsule(block);
+ long energyFee = wallet.getEnergyFee(blockCapsule.getTimeStamp());
+ TransactionReceipt.TransactionContext context
+ = new TransactionContext(0, 2, 3);
+
+ TransactionReceipt transactionReceipt =
+ new TransactionReceipt(blockCapsule, transactionInfo, context, energyFee);
+
+ Assert.assertNotNull(transactionReceipt);
+ String blockHash = "0x0000000000000001464f071c8a336fd22eb5145dff1b245bda013ec89add8497";
+
+ // assert basic fields
+ Assert.assertEquals(transactionReceipt.getBlockHash(), blockHash);
+ Assert.assertEquals(transactionReceipt.getBlockNumber(), "0x1");
+ Assert.assertEquals(transactionReceipt.getTransactionHash(), "0x31");
+ Assert.assertEquals(transactionReceipt.getTransactionIndex(), "0x0");
+ Assert.assertEquals(transactionReceipt.getCumulativeGasUsed(), ByteArray.toJsonHex(102));
+ Assert.assertEquals(transactionReceipt.getGasUsed(), ByteArray.toJsonHex(100));
+ Assert.assertEquals(transactionReceipt.getEffectiveGasPrice(), ByteArray.toJsonHex(energyFee));
+ Assert.assertEquals(transactionReceipt.getStatus(), "0x1");
+ // assert contract fields
+ Assert.assertEquals(transactionReceipt.getFrom(), ByteArray.toJsonHexAddress(new byte[0]));
+ Assert.assertEquals(transactionReceipt.getTo(), ByteArray.toJsonHexAddress(new byte[0]));
+ Assert.assertNull(transactionReceipt.getContractAddress());
+
+ // assert logs fields
+ Assert.assertEquals(transactionReceipt.getLogs().length, 1);
+ Assert.assertEquals(transactionReceipt.getLogs()[0].getLogIndex(), "0x3");
+ Assert.assertEquals(
+ transactionReceipt.getLogs()[0].getBlockHash(), blockHash);
+ Assert.assertEquals(transactionReceipt.getLogs()[0].getBlockNumber(), "0x1");
+ Assert.assertEquals(transactionReceipt.getLogs()[0].getTransactionHash(), "0x31");
+ Assert.assertEquals(transactionReceipt.getLogs()[0].getTransactionIndex(), "0x0");
+
+ // assert default fields
+ Assert.assertNull(transactionReceipt.getRoot());
+ Assert.assertEquals(transactionReceipt.getType(), "0x0");
+ Assert.assertEquals(transactionReceipt.getLogsBloom(), ByteArray.toJsonHex(new byte[256]));
+ }
}
diff --git a/framework/src/test/java/org/tron/core/zksnark/LibrustzcashTest.java b/framework/src/test/java/org/tron/core/zksnark/LibrustzcashTest.java
index 049fb2528b1..f3852952cc7 100644
--- a/framework/src/test/java/org/tron/core/zksnark/LibrustzcashTest.java
+++ b/framework/src/test/java/org/tron/core/zksnark/LibrustzcashTest.java
@@ -84,7 +84,8 @@ public static void init() {
},
"config-test-mainnet.conf"
);
- Args.setFullNodeAllowShieldedTransaction(true);
+ Args.getInstance().setAllowShieldedTransactionApi(true);
+ ZksnarkInitService.librustzcashInitZksnarkParams();
}
private static int randomInt(int minInt, int maxInt) {
@@ -115,10 +116,6 @@ public static void test(byte[] K, byte[] ovk, byte[] cv, byte[] cm, byte[] epk)
null, 0, cipher_nonce, K)));
}
- public static void librustzcashInitZksnarkParams() {
- ZksnarkInitService.librustzcashInitZksnarkParams();
- }
-
@Test
public void testLibsodium() throws ZksnarkException {
byte[] K = new byte[32];
@@ -275,7 +272,6 @@ public long benchmarkCreateSpend() throws ZksnarkException {
@Ignore
@Test
public void calBenchmarkSpendConcurrent() throws Exception {
- librustzcashInitZksnarkParams();
System.out.println("--- load ok ---");
int count = 2;
@@ -307,7 +303,6 @@ public void calBenchmarkSpendConcurrent() throws Exception {
@Test
public void calBenchmarkSpend() throws ZksnarkException {
- librustzcashInitZksnarkParams();
System.out.println("--- load ok ---");
int count = 2;
@@ -374,7 +369,6 @@ public long benchmarkCreateSaplingSpend() throws BadItemException, ZksnarkExcept
@Test
public void calBenchmarkCreateSaplingSpend() throws BadItemException, ZksnarkException {
- librustzcashInitZksnarkParams();
System.out.println("--- load ok ---");
int count = 2;
@@ -451,7 +445,6 @@ public long benchmarkCreateSaplingOutput() throws BadItemException, ZksnarkExcep
@Test
public void calBenchmarkCreateSaplingOutPut() throws BadItemException, ZksnarkException {
- librustzcashInitZksnarkParams();
System.out.println("--- load ok ---");
int count = 2;
@@ -479,7 +472,6 @@ public void calBenchmarkCreateSaplingOutPut() throws BadItemException, ZksnarkEx
@Test
public void checkVerifyOutErr() throws ZksnarkException {
- librustzcashInitZksnarkParams();
System.out.println("--- load ok ---");
// expect fail
diff --git a/framework/src/test/java/org/tron/core/zksnark/SaplingNoteTest.java b/framework/src/test/java/org/tron/core/zksnark/SaplingNoteTest.java
index da4df70d9ac..34913c98ccc 100644
--- a/framework/src/test/java/org/tron/core/zksnark/SaplingNoteTest.java
+++ b/framework/src/test/java/org/tron/core/zksnark/SaplingNoteTest.java
@@ -22,7 +22,7 @@ public class SaplingNoteTest {
@BeforeClass
public static void init() {
- Args.setFullNodeAllowShieldedTransaction(true);
+ Args.getInstance().setAllowShieldedTransactionApi(true);
// Args.getInstance().setAllowShieldedTransaction(1);
ZksnarkInitService.librustzcashInitZksnarkParams();
}
diff --git a/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java b/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java
index 7746066abfa..e7dfa06d094 100644
--- a/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java
+++ b/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java
@@ -17,6 +17,7 @@
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.tron.api.GrpcAPI;
@@ -118,6 +119,11 @@ public class SendCoinShieldTest extends BaseTest {
.fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d");
}
+ @BeforeClass
+ public static void initZksnarkParams() {
+ ZksnarkInitService.librustzcashInitZksnarkParams();
+ }
+
/**
* Init data.
*/
@@ -219,10 +225,6 @@ private IncrementalMerkleVoucherContainer createSimpleMerkleVoucherContainer(byt
return tree.toVoucher();
}
- private void librustzcashInitZksnarkParams() {
- ZksnarkInitService.librustzcashInitZksnarkParams();
- }
-
@Test
public void testStringRevert() {
byte[] bytes = ByteArray
@@ -235,7 +237,6 @@ public void testStringRevert() {
@Test
public void testGenerateSpendProof() throws Exception {
- librustzcashInitZksnarkParams();
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
SpendingKey sk = SpendingKey
.decode("ff2c06269315333a9207f817d2eca0ac555ca8f90196976324c7756504e7c9ee");
@@ -270,7 +271,6 @@ public void testGenerateSpendProof() throws Exception {
@Test
public void generateOutputProof() throws ZksnarkException {
- librustzcashInitZksnarkParams();
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
SpendingKey spendingKey = SpendingKey.random();
FullViewingKey fullViewingKey = spendingKey.fullViewingKey();
@@ -289,7 +289,6 @@ public void generateOutputProof() throws ZksnarkException {
@Test
public void verifyOutputProof() throws ZksnarkException {
- librustzcashInitZksnarkParams();
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
SpendingKey spendingKey = SpendingKey.random();
FullViewingKey fullViewingKey = spendingKey.fullViewingKey();
@@ -321,7 +320,6 @@ public void verifyOutputProof() throws ZksnarkException {
@Test
public void testDecryptReceiveWithIvk() throws ZksnarkException {
//verify c_enc
- librustzcashInitZksnarkParams();
ZenTransactionBuilder builder = new ZenTransactionBuilder();
SpendingKey spendingKey = SpendingKey.random();
@@ -385,9 +383,6 @@ public String byte2intstring(byte[] input) {
@Test
public void testDecryptReceiveWithOvk() throws Exception {
- //decode c_out with ovk.
- librustzcashInitZksnarkParams();
-
// construct payment address
SpendingKey spendingKey2 = SpendingKey
.decode("ff2c06269315333a9207f817d2eca0ac555ca8f90196976324c7756504e7c9ee");
@@ -467,7 +462,6 @@ public void pushShieldedTransactionAndDecryptWithIvk()
AccountResourceInsufficientException, InvalidProtocolBufferException, ZksnarkException {
long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit();
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
dbManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(1000 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -556,7 +550,6 @@ public void pushShieldedTransactionAndDecryptWithOvk()
AccountResourceInsufficientException, InvalidProtocolBufferException, ZksnarkException {
long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit();
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
dbManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(1000 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -643,10 +636,8 @@ private byte[] getHash() {
@Ignore
@Test
public void checkZksnark() throws BadItemException, ZksnarkException {
- librustzcashInitZksnarkParams();
long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit();
// generate spend proof
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
dbManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(4010 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -679,7 +670,6 @@ public void checkZksnark() throws BadItemException, ZksnarkException {
@Test
public void testVerifySpendProof() throws BadItemException, ZksnarkException {
- librustzcashInitZksnarkParams();
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
SpendingKey sk = SpendingKey
.decode("ff2c06269315333a9207f817d2eca0ac555ca8f90196976324c7756504e7c9ee");
@@ -717,7 +707,6 @@ public void testVerifySpendProof() throws BadItemException, ZksnarkException {
public void saplingBindingSig() throws BadItemException, ZksnarkException {
long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit();
// generate spend proof
- librustzcashInitZksnarkParams();
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
SpendingKey sk = SpendingKey
.decode("ff2c06269315333a9207f817d2eca0ac555ca8f90196976324c7756504e7c9ee");
@@ -756,7 +745,6 @@ public void pushShieldedTransaction()
ContractExeException, AccountResourceInsufficientException, ZksnarkException {
long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit();
// generate spend proof
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
dbManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(4010 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -789,7 +777,6 @@ public void pushShieldedTransaction()
@Test
public void finalCheck() throws BadItemException, ZksnarkException {
long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit();
- librustzcashInitZksnarkParams();
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
// generate spend proof
SpendingKey sk = SpendingKey
@@ -965,7 +952,6 @@ public void getSpendingKey() throws Exception {
@Test
public void testTwoCMWithDiffSkInOneTx() throws Exception {
// generate spend proof
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(110 * 1000000L);
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1025,7 +1011,6 @@ private void executeTx(TransactionCapsule transactionCap) throws Exception {
@Test
public void testValueBalance() throws Exception {
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
//case 1, a public input, no input cm, an output cm, no public output
{
@@ -1246,7 +1231,6 @@ public void testValueBalance() throws Exception {
@Test
public void TestCreateMultipleTxAtTheSameTime() throws Exception {
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
List txList = Lists.newArrayList();
//case 1, a public input, no input cm, an output cm, no public output
@@ -1364,7 +1348,6 @@ public void TestCreateMultipleTxAtTheSameTime() throws Exception {
@Test
public void TestCtxGeneratesTooMuchProof() throws Exception {
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
//case 3, no public input, an input cm, no output cm, a public output
{
@@ -1439,7 +1422,6 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo
@Test
public void TestGeneratesProofWithDiffCtx() throws Exception {
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
//case 3, no public input, an input cm, no output cm, a public output
@@ -1498,7 +1480,6 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo
@Test
public void TestGeneratesProofWithWrongAlpha() throws Exception {
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
//case 3, no public input, an input cm, no output cm, a public output
{
@@ -1536,7 +1517,6 @@ public void TestGeneratesProofWithWrongAlpha() throws Exception {
@Test
public void TestGeneratesProofWithWrongRcm() throws Exception {
long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit();
- librustzcashInitZksnarkParams();
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
// generate spend proof
SpendingKey sk = SpendingKey.random();
@@ -1557,7 +1537,6 @@ public void TestGeneratesProofWithWrongRcm() throws Exception {
@Test
public void TestWrongAsk() throws Exception {
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
//case 3, no public input, an input cm, no output cm, a public output
@@ -1667,7 +1646,6 @@ private TransactionCapsule generateDefaultBuilder(ZenTransactionBuilder builder)
@Test
public void TestDefaultBuilder() throws Exception {
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
dbManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(1000 * 1000000L);
@@ -1678,7 +1656,6 @@ public void TestDefaultBuilder() throws Exception {
@Test
public void TestWrongSpendRk() throws Exception {
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
{
@@ -1716,7 +1693,6 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo
@Test
public void TestWrongSpendProof() throws Exception {
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
{
@@ -1761,7 +1737,6 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo
@Test
public void TestWrongNf() throws Exception {
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
{
@@ -1800,7 +1775,6 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo
@Test
public void TestWrongAnchor() throws Exception {
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
{
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet) {
diff --git a/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java b/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java
index 2a7545f7a9b..4012029e8ae 100755
--- a/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java
+++ b/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java
@@ -17,6 +17,7 @@
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Test;
import org.tron.api.GrpcAPI.BytesMessage;
import org.tron.api.GrpcAPI.DecryptNotes;
@@ -129,7 +130,12 @@ public class ShieldedReceiveTest extends BaseTest {
static {
Args.setParam(new String[]{"--output-directory", dbPath()}, "config-localtest.conf");
ADDRESS_ONE_PRIVATE_KEY = getRandomPrivateKey();
- FROM_ADDRESS = getHexAddressByPrivateKey(ADDRESS_ONE_PRIVATE_KEY);;
+ FROM_ADDRESS = getHexAddressByPrivateKey(ADDRESS_ONE_PRIVATE_KEY);
+ }
+
+ @BeforeClass
+ public static void initZksnarkParams() {
+ ZksnarkInitService.librustzcashInitZksnarkParams();
}
/**
@@ -145,10 +151,6 @@ public void init() {
init = true;
}
- private static void librustzcashInitZksnarkParams() {
- ZksnarkInitService.librustzcashInitZksnarkParams();
- }
-
private static byte[] randomUint256() {
return org.tron.keystore.Wallet.generateRandomBytes(32);
}
@@ -244,7 +246,6 @@ public void testSetShieldedTransactionFee() {
*/
@Test
public void testCreateBeforeAllowZksnark() throws ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(0);
createCapsule();
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -284,7 +285,6 @@ public void testCreateBeforeAllowZksnark() throws ZksnarkException {
@Test
public void testBroadcastBeforeAllowZksnark()
throws ZksnarkException, SignatureFormatException, SignatureException, PermissionException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(0);// or 1
createCapsule();
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -309,21 +309,18 @@ public void testBroadcastBeforeAllowZksnark()
transactionCap = TransactionUtils.addTransactionSign(transactionCap.getInstance(),
ADDRESS_ONE_PRIVATE_KEY, chainBaseManager.getAccountStore());
try {
- dbManager.pushTransaction(transactionCap);
- Assert.assertFalse(true);
+ boolean res = dbManager.pushTransaction(transactionCap);
+ Assert.assertFalse(res);
} catch (Exception e) {
- Assert.assertTrue(e instanceof ContractValidateException);
- Assert.assertEquals(
- "Not support Shielded Transaction, need to be opened by the committee",
- e.getMessage());
+ Assert.fail(e.getMessage());
}
}
/*
- * generate spendproof, dataToBeSigned, outputproof example dynamically according to the params file
+ * generate spendproof, dataToBeSigned,
+ * outputproof example dynamically according to the params file
*/
public String[] generateSpendAndOutputParams() throws ZksnarkException, BadItemException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -460,7 +457,6 @@ private long benchmarkVerifyOutput(String outputParams) throws ZksnarkException
@Test
public void calBenchmarkVerifySpend() throws ZksnarkException, BadItemException {
- librustzcashInitZksnarkParams();
System.out.println("--- load ok ---");
int count = 10;
@@ -492,7 +488,6 @@ public void calBenchmarkVerifySpend() throws ZksnarkException, BadItemException
@Test
public void calBenchmarkVerifyOutput() throws ZksnarkException, BadItemException {
- librustzcashInitZksnarkParams();
System.out.println("--- load ok ---");
int count = 2;
@@ -588,7 +583,6 @@ private ZenTransactionBuilder generateBuilderWithoutColumnInDescription(
@Test
public void testReceiveDescriptionWithEmptyCv()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -634,7 +628,6 @@ public void testReceiveDescriptionWithEmptyCv()
@Test
public void testReceiveDescriptionWithEmptyCm()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -677,7 +670,6 @@ public void testReceiveDescriptionWithEmptyCm()
@Test
public void testReceiveDescriptionWithEmptyEpk()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -719,7 +711,6 @@ public void testReceiveDescriptionWithEmptyEpk()
@Test
public void testReceiveDescriptionWithEmptyZkproof()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -762,7 +753,6 @@ public void testReceiveDescriptionWithEmptyZkproof()
@Test
public void testReceiveDescriptionWithEmptyCenc()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
dbManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -805,7 +795,6 @@ public void testReceiveDescriptionWithEmptyCenc()
@Test
public void testReceiveDescriptionWithEmptyCout()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1063,7 +1052,6 @@ private ZenTransactionBuilder generateBuilder(ZenTransactionBuilder builder, lon
@Test
public void testReceiveDescriptionWithWrongCv()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1092,7 +1080,6 @@ public void testReceiveDescriptionWithWrongCv()
@Test
public void testReceiveDescriptionWithWrongZkproof()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1121,7 +1108,6 @@ public void testReceiveDescriptionWithWrongZkproof()
@Test
public void testReceiveDescriptionWithWrongD()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1152,7 +1138,6 @@ public void testReceiveDescriptionWithWrongD()
@Test
public void testReceiveDescriptionWithWrongPkd()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1183,7 +1168,6 @@ public void testReceiveDescriptionWithWrongPkd()
@Test
public void testReceiveDescriptionWithWrongValue()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1212,7 +1196,6 @@ public void testReceiveDescriptionWithWrongValue()
@Test
public void testReceiveDescriptionWithWrongRcm()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1241,7 +1224,6 @@ public void testReceiveDescriptionWithWrongRcm()
@Test
public void testNotMatchAskAndNsk()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1292,7 +1274,6 @@ public void testNotMatchAskAndNsk()
@Test
public void testRandomOvk()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1336,7 +1317,6 @@ public void testRandomOvk()
//@Test not used
public void testSameInputCm()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1385,7 +1365,6 @@ public void testSameInputCm()
@Test
public void testSameOutputCm()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1437,7 +1416,6 @@ public void testSameOutputCm()
@Test
public void testShieldInputInsufficient()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1482,7 +1460,6 @@ public void testShieldInputInsufficient()
*/
@Test
public void testTransparentInputInsufficient() throws RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit();
@@ -1731,7 +1708,6 @@ public TransactionCapsule generateTransactionCapsule(ZenTransactionBuilder build
public void testSignWithoutFromAddress()
throws BadItemException, ContractValidateException, RuntimeException,
ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1771,7 +1747,6 @@ public void testSignWithoutFromAddress()
public void testSignWithoutFromAmout()
throws BadItemException, ContractValidateException, RuntimeException,
ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1810,7 +1785,6 @@ public void testSignWithoutFromAmout()
@Test
public void testSignWithoutSpendDescription()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1856,7 +1830,6 @@ public void testSignWithoutSpendDescription()
@Test
public void testSignWithoutReceiveDescription()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1903,7 +1876,6 @@ public void testSignWithoutReceiveDescription()
public void testSignWithoutToAddress()
throws BadItemException, ContractValidateException, RuntimeException,
ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1943,7 +1915,6 @@ public void testSignWithoutToAddress()
public void testSignWithoutToAmount()
throws BadItemException, ContractValidateException, RuntimeException,
ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -1982,7 +1953,6 @@ public void testSignWithoutToAmount()
@Test
public void testSpendSignatureWithWrongColumn()
throws BadItemException, RuntimeException, ZksnarkException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -2100,7 +2070,6 @@ public void testSpendSignatureWithWrongColumn()
@Test
public void testIsolateSignature()
throws ZksnarkException, BadItemException, ContractValidateException, ContractExeException {
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -2235,7 +2204,6 @@ public void testMemoTooLong() throws ContractValidateException, TooBigTransactio
AccountResourceInsufficientException, InvalidProtocolBufferException, ZksnarkException {
long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit();
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -2318,7 +2286,6 @@ public void testMemoNotEnough() throws ContractValidateException, TooBigTransact
AccountResourceInsufficientException, InvalidProtocolBufferException, ZksnarkException {
long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit();
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(100 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
@@ -2412,7 +2379,6 @@ public void pushSameSkAndScanAndSpend() throws Exception {
dbManager.pushBlock(new BlockCapsule(block));
//create transactions
- librustzcashInitZksnarkParams();
chainBaseManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1);
chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(1000 * 1000000L);
ZenTransactionBuilder builder = new ZenTransactionBuilder(wallet);
diff --git a/framework/src/test/java/org/tron/keystroe/CredentialsTest.java b/framework/src/test/java/org/tron/keystroe/CredentialsTest.java
index ce992c3443f..2642129e00a 100644
--- a/framework/src/test/java/org/tron/keystroe/CredentialsTest.java
+++ b/framework/src/test/java/org/tron/keystroe/CredentialsTest.java
@@ -1,6 +1,5 @@
package org.tron.keystroe;
-import lombok.var;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
@@ -11,24 +10,24 @@ public class CredentialsTest {
@Test
public void test_equality() {
- var aObject = new Object();
- var si = Mockito.mock(SignInterface.class);
- var si2 = Mockito.mock(SignInterface.class);
- var si3 = Mockito.mock(SignInterface.class);
- var address = "TQhZ7W1RudxFdzJMw6FvMnujPxrS6sFfmj".getBytes();
- var address2 = "TNCmcTdyrYKMtmE1KU2itzeCX76jGm5Not".getBytes();
+ Object aObject = new Object();
+ SignInterface si = Mockito.mock(SignInterface.class);
+ SignInterface si2 = Mockito.mock(SignInterface.class);
+ SignInterface si3 = Mockito.mock(SignInterface.class);
+ byte[] address = "TQhZ7W1RudxFdzJMw6FvMnujPxrS6sFfmj".getBytes();
+ byte[] address2 = "TNCmcTdyrYKMtmE1KU2itzeCX76jGm5Not".getBytes();
Mockito.when(si.getAddress()).thenReturn(address);
Mockito.when(si2.getAddress()).thenReturn(address);
Mockito.when(si3.getAddress()).thenReturn(address2);
- var aCredential = Credentials.create(si);
+ Credentials aCredential = Credentials.create(si);
Assert.assertFalse(aObject.equals(aCredential));
Assert.assertFalse(aCredential.equals(aObject));
Assert.assertFalse(aCredential.equals(null));
- var anotherCredential = Credentials.create(si);
- Assert.assertTrue(aCredential.equals(anotherCredential));
- var aCredential2 = Credentials.create(si2);
+ Credentials anotherCredential = Credentials.create(si);
Assert.assertTrue(aCredential.equals(anotherCredential));
- var aCredential3 = Credentials.create(si3);
+ Credentials aCredential2 = Credentials.create(si2);
+ Assert.assertTrue(aCredential.equals(anotherCredential));
+ Credentials aCredential3 = Credentials.create(si3);
Assert.assertFalse(aCredential.equals(aCredential3));
}
}
diff --git a/framework/src/test/java/org/tron/program/DBConvertTest.java b/framework/src/test/java/org/tron/program/DBConvertTest.java
deleted file mode 100644
index 7b3f797d627..00000000000
--- a/framework/src/test/java/org/tron/program/DBConvertTest.java
+++ /dev/null
@@ -1,116 +0,0 @@
-package org.tron.program;
-
-import static org.fusesource.leveldbjni.JniDBFactory.factory;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.util.UUID;
-import org.iq80.leveldb.DB;
-import org.iq80.leveldb.Options;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.tron.common.utils.ByteArray;
-import org.tron.common.utils.FileUtil;
-import org.tron.common.utils.MarketOrderPriceComparatorForLevelDB;
-import org.tron.core.capsule.MarketOrderIdListCapsule;
-import org.tron.core.capsule.utils.MarketUtils;
-
-public class DBConvertTest {
-
-
- private static final String INPUT_DIRECTORY = "output-directory/convert-database/";
- private static final String OUTPUT_DIRECTORY = "output-directory/convert-database-dest/";
- private static final String ACCOUNT = "account";
- private static final String MARKET = "market_pair_price_to_order";
-
-
- @BeforeClass
- public static void init() throws IOException {
- if (new File(INPUT_DIRECTORY).mkdirs()) {
- initDB(new File(INPUT_DIRECTORY,ACCOUNT));
- initDB(new File(INPUT_DIRECTORY,MARKET));
- }
- }
-
- private static void initDB(File file) throws IOException {
- Options dbOptions = DBConvert.newDefaultLevelDbOptions();
- if (file.getName().contains("market_pair_price_to_order")) {
- dbOptions.comparator(new MarketOrderPriceComparatorForLevelDB());
- try (DB db = factory.open(file,dbOptions)) {
-
- byte[] sellTokenID1 = ByteArray.fromString("100");
- byte[] buyTokenID1 = ByteArray.fromString("200");
- byte[] pairPriceKey1 = MarketUtils.createPairPriceKey(
- sellTokenID1,
- buyTokenID1,
- 1000L,
- 2001L
- );
- byte[] pairPriceKey2 = MarketUtils.createPairPriceKey(
- sellTokenID1,
- buyTokenID1,
- 1000L,
- 2002L
- );
- byte[] pairPriceKey3 = MarketUtils.createPairPriceKey(
- sellTokenID1,
- buyTokenID1,
- 1000L,
- 2003L
- );
-
- MarketOrderIdListCapsule capsule1 = new MarketOrderIdListCapsule(ByteArray.fromLong(1),
- ByteArray.fromLong(1));
- MarketOrderIdListCapsule capsule2 = new MarketOrderIdListCapsule(ByteArray.fromLong(2),
- ByteArray.fromLong(2));
- MarketOrderIdListCapsule capsule3 = new MarketOrderIdListCapsule(ByteArray.fromLong(3),
- ByteArray.fromLong(3));
-
- //Use out-of-order insertion,key in store should be 1,2,3
- db.put(pairPriceKey1, capsule1.getData());
- db.put(pairPriceKey2, capsule2.getData());
- db.put(pairPriceKey3, capsule3.getData());
- }
-
- } else {
- try (DB db = factory.open(file,dbOptions)) {
- for (int i = 0; i < 100; i++) {
- byte[] bytes = UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8);
- db.put(bytes, bytes);
- }
- }
- }
-
- }
-
- @AfterClass
- public static void destroy() {
- FileUtil.deleteDir(new File(INPUT_DIRECTORY));
- FileUtil.deleteDir(new File(OUTPUT_DIRECTORY));
- }
-
- @Test
- public void testRun() {
- String[] args = new String[] { INPUT_DIRECTORY, OUTPUT_DIRECTORY };
- Assert.assertEquals(0, DBConvert.run(args));
- }
-
- @Test
- public void testNotExist() {
- String[] args = new String[] {OUTPUT_DIRECTORY + File.separator + UUID.randomUUID(),
- OUTPUT_DIRECTORY};
- Assert.assertEquals(404, DBConvert.run(args));
- }
-
- @Test
- public void testEmpty() {
- File file = new File(OUTPUT_DIRECTORY + File.separator + UUID.randomUUID());
- file.mkdirs();
- file.deleteOnExit();
- String[] args = new String[] {file.toString(), OUTPUT_DIRECTORY};
- Assert.assertEquals(0, DBConvert.run(args));
- }
-}
diff --git a/framework/src/test/java/org/tron/program/SolidityNodeTest.java b/framework/src/test/java/org/tron/program/SolidityNodeTest.java
index a95d07c0c11..cb2be8cd688 100755
--- a/framework/src/test/java/org/tron/program/SolidityNodeTest.java
+++ b/framework/src/test/java/org/tron/program/SolidityNodeTest.java
@@ -1,5 +1,8 @@
package org.tron.program;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
+
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
@@ -8,6 +11,7 @@
import org.tron.common.client.DatabaseGrpcClient;
import org.tron.core.Constant;
import org.tron.core.config.args.Args;
+import org.tron.core.exception.TronError;
import org.tron.core.services.RpcApiService;
import org.tron.core.services.http.solidity.SolidityNodeHttpApiService;
import org.tron.protos.Protocol.Block;
@@ -22,14 +26,19 @@ public class SolidityNodeTest extends BaseTest {
SolidityNodeHttpApiService solidityNodeHttpApiService;
static {
- Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF);
- Args.getInstance().setSolidityNode(true);
+ Args.setParam(new String[]{"-d", dbPath(), "--solidity"}, Constant.TEST_CONF);
}
@Test
public void testSolidityArgs() {
Assert.assertNotNull(Args.getInstance().getTrustNodeAddr());
Assert.assertTrue(Args.getInstance().isSolidityNode());
+ String trustNodeAddr = Args.getInstance().getTrustNodeAddr();
+ Args.getInstance().setTrustNodeAddr(null);
+ TronError thrown = assertThrows(TronError.class,
+ SolidityNode::start);
+ assertEquals(TronError.ErrCode.SOLID_NODE_INIT, thrown.getErrCode());
+ Args.getInstance().setTrustNodeAddr(trustNodeAddr);
}
@Test
diff --git a/framework/src/test/resources/config-localtest.conf b/framework/src/test/resources/config-localtest.conf
index ff31369a915..50a3f97d8b7 100644
--- a/framework/src/test/resources/config-localtest.conf
+++ b/framework/src/test/resources/config-localtest.conf
@@ -90,7 +90,7 @@ node {
minParticipationRate = 0
- fullNodeAllowShieldedTransaction = true
+ allowShieldedTransactionApi = true
zenTokenId = 1000001
diff --git a/framework/src/test/resources/config-test.conf b/framework/src/test/resources/config-test.conf
index eaa6659a8c4..f7884eec831 100644
--- a/framework/src/test/resources/config-test.conf
+++ b/framework/src/test/resources/config-test.conf
@@ -327,7 +327,7 @@ genesis.block = {
voteCount = 96
},
{
- address: 27VZHn9PFZwNh7o2EporxmLkpe157iWZVkh
+ address: 27bi7CD8d94AgXY3XFS9A9vx78Si5MqrECz
url = "http://AlphaLyrae.org",
voteCount = 95
}
diff --git a/gradle/jdk17/java-tron.vmoptions b/gradle/jdk17/java-tron.vmoptions
new file mode 100644
index 00000000000..91accd05016
--- /dev/null
+++ b/gradle/jdk17/java-tron.vmoptions
@@ -0,0 +1,8 @@
+-XX:+UseZGC
+-Xlog:gc*:file=gc.log:time,uptime,level,tags:filecount=50,filesize=100M
+-XX:ReservedCodeCacheSize=256m
+-XX:+UseCodeCacheFlushing
+-XX:MetaspaceSize=256m
+-XX:MaxMetaspaceSize=512m
+-XX:MaxDirectMemorySize=1g
+-XX:+HeapDumpOnOutOfMemoryError
\ No newline at end of file
diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml
index b3c879f6b40..53d4958f1e5 100644
--- a/gradle/verification-metadata.xml
+++ b/gradle/verification-metadata.xml
@@ -150,28 +150,12 @@
-
-
-
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
@@ -179,9 +163,9 @@
-
-
-
+
+
+
@@ -189,9 +173,9 @@
-
-
-
+
+
+
@@ -199,9 +183,9 @@
-
-
-
+
+
+
@@ -209,9 +193,9 @@
-
-
-
+
+
+
@@ -219,15 +203,15 @@
-
-
-
+
+
+
-
-
+
+
-
-
+
+
@@ -235,15 +219,15 @@
-
-
-
+
+
+
-
-
+
+
-
-
+
+
@@ -251,15 +235,15 @@
-
-
-
+
+
+
-
-
+
+
-
-
+
+
@@ -269,6 +253,9 @@
+
+
+
@@ -483,19 +470,6 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
@@ -547,9 +521,16 @@
+
+
+
+
+
+
+
@@ -728,6 +709,14 @@
+
+
+
+
+
+
+
+
@@ -820,12 +809,15 @@
-
-
-
+
+
+
-
-
+
+
+
+
+
@@ -909,9 +901,16 @@
+
+
+
+
+
+
+
@@ -1019,6 +1018,9 @@
+
+
+
@@ -1086,27 +1088,14 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
@@ -1139,6 +1128,14 @@
+
+
+
+
+
+
+
+
@@ -1298,9 +1295,9 @@
-
-
-
+
+
+
@@ -1393,16 +1390,16 @@
-
-
-
-
-
+
+
+
+
+
@@ -1540,28 +1537,28 @@
-
-
-
+
+
+
-
-
+
+
-
-
-
+
+
+
-
-
+
+
-
-
-
+
+
+
-
-
+
+
@@ -1597,6 +1594,9 @@
+
+
+
@@ -1666,65 +1666,65 @@
-
-
-
+
+
+
-
-
+
+
-
-
-
+
+
+
-
-
+
+
-
-
-
+
+
+
-
-
-
+
+
+
-
-
+
+
-
-
-
+
+
+
-
-
+
+
-
-
-
+
+
+
-
-
+
+
-
-
-
+
+
+
-
-
+
+
-
-
-
+
+
+
-
-
+
+
@@ -1807,14 +1807,6 @@
-
-
-
-
-
-
-
-
@@ -1823,27 +1815,19 @@
-
-
-
-
-
-
-
-
-
-
-
+
+
+
-
-
-
+
+
+
@@ -1943,6 +1927,30 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -2080,12 +2088,12 @@
-
-
-
+
+
+
-
-
+
+
@@ -2112,6 +2120,14 @@
+
+
+
+
+
+
+
+
@@ -2207,81 +2223,86 @@
-
-
-
-
-
-
+
+
+
-
-
-
-
+
+
-
-
+
+
-
-
-
-
-
-
+
+
+
-
-
-
-
+
+
-
-
+
+
-
-
-
+
+
+
+
+
+
-
-
+
+
-
-
-
+
+
+
-
-
+
+
+
+
+
-
-
-
+
+
+
+
+
+
-
-
+
+
-
-
-
+
+
+
-
-
+
+
+
+
+
-
-
-
+
+
+
+
+
+
-
-
+
+
-
-
-
+
+
+
diff --git a/platform/build.gradle b/platform/build.gradle
new file mode 100644
index 00000000000..a94aad3cf17
--- /dev/null
+++ b/platform/build.gradle
@@ -0,0 +1,17 @@
+description = "platform – a distributed consensus arithmetic for blockchain."
+
+sourceSets {
+ main {
+ java.srcDirs = rootProject.archInfo.sourceSets.main.java.srcDirs
+ }
+ test {
+ java.srcDirs = rootProject.archInfo.sourceSets.test.java.srcDirs
+ }
+}
+
+dependencies {
+ api group: 'org.fusesource.leveldbjni', name: 'leveldbjni-all', version: '1.8'
+ api group: 'org.rocksdb', name: 'rocksdbjni', version: "${rootProject.archInfo.requires.RocksdbVersion}"
+ api group: 'commons-io', name: 'commons-io', version: '2.18.0'
+ api 'io.github.tronprotocol:zksnark-java-sdk:1.0.0' exclude(group: 'commons-io', module: 'commons-io')
+}
diff --git a/platform/src/main/java/arm/org/tron/common/math/MathWrapper.java b/platform/src/main/java/arm/org/tron/common/math/MathWrapper.java
new file mode 100644
index 00000000000..12395dffcea
--- /dev/null
+++ b/platform/src/main/java/arm/org/tron/common/math/MathWrapper.java
@@ -0,0 +1,254 @@
+package org.tron.common.math;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * This class is deprecated and should not be used in new code,
+ * for cross-platform consistency, please use {@link StrictMathWrapper} instead,
+ * especially for floating-point calculations.
+ */
+@Deprecated
+public class MathWrapper {
+
+ private static final Map powData = Collections.synchronizedMap(new HashMap<>());
+ private static final String EXPONENT = "3f40624dd2f1a9fc"; // 1/2000 = 0.0005
+
+ public static double pow(double a, double b) {
+ double strictResult = StrictMath.pow(a, b);
+ return powData.getOrDefault(new PowData(a, b), strictResult);
+ }
+
+ /**
+ * This static block is used to initialize the data map.
+ */
+ static {
+ // init main-net pow data start
+ addPowData("3ff0192278704be3", EXPONENT, "3ff000033518c576"); // 4137160(block)
+ addPowData("3ff000002fc6a33f", EXPONENT, "3ff0000000061d86"); // 4065476
+ addPowData("3ff00314b1e73ecf", EXPONENT, "3ff0000064ea3ef8"); // 4071538
+ addPowData("3ff0068cd52978ae", EXPONENT, "3ff00000d676966c"); // 4109544
+ addPowData("3ff0032fda05447d", EXPONENT, "3ff0000068636fe0"); // 4123826
+ addPowData("3ff00051c09cc796", EXPONENT, "3ff000000a76c20e"); // 4166806
+ addPowData("3ff00bef8115b65d", EXPONENT, "3ff0000186893de0"); // 4225778
+ addPowData("3ff009b0b2616930", EXPONENT, "3ff000013d27849e"); // 4251796
+ addPowData("3ff00364ba163146", EXPONENT, "3ff000006f26a9dc"); // 4257157
+ addPowData("3ff019be4095d6ae", EXPONENT, "3ff0000348e9f02a"); // 4260583
+ addPowData("3ff0123e52985644", EXPONENT, "3ff0000254797fd0"); // 4367125
+ addPowData("3ff0126d052860e2", EXPONENT, "3ff000025a6cde26"); // 4402197
+ addPowData("3ff0001632cccf1b", EXPONENT, "3ff0000002d76406"); // 4405788
+ addPowData("3ff0000965922b01", EXPONENT, "3ff000000133e966"); // 4490332
+ addPowData("3ff00005c7692d61", EXPONENT, "3ff0000000bd5d34"); // 4499056
+ addPowData("3ff015cba20ec276", EXPONENT, "3ff00002c84cef0e"); // 4518035
+ addPowData("3ff00002f453d343", EXPONENT, "3ff000000060cf4e"); // 4533215
+ addPowData("3ff006ea73f88946", EXPONENT, "3ff00000e26d4ea2"); // 4647814
+ addPowData("3ff00a3632db72be", EXPONENT, "3ff000014e3382a6"); // 4766695
+ addPowData("3ff000c0e8df0274", EXPONENT, "3ff0000018b0aeb2"); // 4771494
+ addPowData("3ff00015c8f06afe", EXPONENT, "3ff0000002c9d73e"); // 4793587
+ addPowData("3ff00068def18101", EXPONENT, "3ff000000d6c3cac"); // 4801947
+ addPowData("3ff01349f3ac164b", EXPONENT, "3ff000027693328a"); // 4916843
+ addPowData("3ff00e86a7859088", EXPONENT, "3ff00001db256a52"); // 4924111
+ addPowData("3ff00000c2a51ab7", EXPONENT, "3ff000000018ea20"); // 5098864
+ addPowData("3ff020fb74e9f170", EXPONENT, "3ff00004346fbfa2"); // 5133963
+ addPowData("3ff00001ce277ce7", EXPONENT, "3ff00000003b27dc"); // 5139389
+ addPowData("3ff005468a327822", EXPONENT, "3ff00000acc20750"); // 5151258
+ addPowData("3ff00006666f30ff", EXPONENT, "3ff0000000d1b80e"); // 5185021
+ addPowData("3ff000045a0b2035", EXPONENT, "3ff00000008e98e6"); // 5295829
+ addPowData("3ff00e00380e10d7", EXPONENT, "3ff00001c9ff83c8"); // 5380897
+ addPowData("3ff00c15de2b0d5e", EXPONENT, "3ff000018b6eaab6"); // 5400886
+ addPowData("3ff00042afe6956a", EXPONENT, "3ff0000008892244"); // 5864127
+ addPowData("3ff0005b7357c2d4", EXPONENT, "3ff000000bb48572"); // 6167339
+ addPowData("3ff00033d5ab51c8", EXPONENT, "3ff0000006a279c8"); // 6240974
+ addPowData("3ff0000046d74585", EXPONENT, "3ff0000000091150"); // 6279093
+ addPowData("3ff0010403f34767", EXPONENT, "3ff0000021472146"); // 6428736
+ addPowData("3ff00496fe59bc98", EXPONENT, "3ff000009650a4ca"); // 6432355,6493373
+ addPowData("3ff0012e43815868", EXPONENT, "3ff0000026af266e"); // 6555029
+ addPowData("3ff00021f6080e3c", EXPONENT, "3ff000000458d16a"); // 7092933
+ addPowData("3ff000489c0f28bd", EXPONENT, "3ff00000094b3072"); // 7112412
+ addPowData("3ff00009d3df2e9c", EXPONENT, "3ff00000014207b4"); // 7675535
+ addPowData("3ff000def05fa9c8", EXPONENT, "3ff000001c887cdc"); // 7860324
+ addPowData("3ff0013bca543227", EXPONENT, "3ff00000286a42d2"); // 8292427
+ addPowData("3ff0021a2f14a0ee", EXPONENT, "3ff0000044deb040"); // 8517311
+ addPowData("3ff0002cc166be3c", EXPONENT, "3ff0000005ba841e"); // 8763101
+ addPowData("3ff0000cc84e613f", EXPONENT, "3ff0000001a2da46"); // 9269124
+ addPowData("3ff000057b83c83f", EXPONENT, "3ff0000000b3a640"); // 9631452
+ // init main-net pow data end
+ // add pow data
+ }
+
+ private static void addPowData(String a, String b, String ret) {
+ powData.put(new PowData(hexToDouble(a), hexToDouble(b)), hexToDouble(ret));
+ }
+
+ private static double hexToDouble(String input) {
+ // Convert the hex string to a long
+ long hexAsLong = Long.parseLong(input, 16);
+ // and then convert the long to a double
+ return Double.longBitsToDouble(hexAsLong);
+ }
+
+ private static class PowData {
+ final double a;
+ final double b;
+
+ public PowData(double a, double b) {
+ this.a = a;
+ this.b = b;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ PowData powData = (PowData) o;
+ return Double.compare(powData.a, a) == 0 && Double.compare(powData.b, b) == 0;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(a, b);
+ }
+ }
+
+ /**
+ * *** methods are same as {@link java.lang.Math} methods, guaranteed by the call start ***
+ */
+
+ /**
+ * finally calls {@link java.lang.Math#addExact(long, long)}
+ */
+
+ public static long addExact(long x, long y) {
+ return StrictMath.addExact(x, y);
+ }
+
+ /**
+ * finally calls {@link java.lang.Math#addExact(int, int)}
+ */
+
+ public static int addExact(int x, int y) {
+ return StrictMath.addExact(x, y);
+ }
+
+ /**
+ * finally calls {@link java.lang.Math#subtractExact(long, long)}
+ */
+
+ public static long subtractExact(long x, long y) {
+ return StrictMath.subtractExact(x, y);
+ }
+
+ /**
+ * finally calls {@link java.lang.Math#floorMod(long, long)}
+ */
+ public static long multiplyExact(long x, long y) {
+ return StrictMath.multiplyExact(x, y);
+ }
+
+ public static long multiplyExact(long x, int y) {
+ return multiplyExact(x, (long) y);
+ }
+
+ public static int multiplyExact(int x, int y) {
+ return StrictMath.multiplyExact(x, y);
+ }
+
+ /**
+ * finally calls {@link java.lang.Math#floorDiv(long, long)}
+ */
+ public static long floorDiv(long x, long y) {
+ return StrictMath.floorDiv(x, y);
+ }
+
+ public static long floorDiv(long x, int y) {
+ return floorDiv(x, (long) y);
+ }
+
+ /**
+ * finally calls {@link java.lang.Math#min(int, int)}
+ */
+ public static int min(int a, int b) {
+ return StrictMath.min(a, b);
+ }
+
+ /**
+ * finally calls {@link java.lang.Math#min(long, long)}
+ */
+ public static long min(long a, long b) {
+ return StrictMath.min(a, b);
+ }
+
+ /**
+ * finally calls {@link java.lang.Math#max(int, int)}
+ */
+ public static int max(int a, int b) {
+ return StrictMath.max(a, b);
+ }
+
+ /**
+ * finally calls {@link java.lang.Math#max(long, long)}
+ */
+ public static long max(long a, long b) {
+ return StrictMath.max(a, b);
+ }
+
+ /**
+ * finally calls {@link java.lang.Math#round(float)}
+ */
+ public static int round(float a) {
+ return StrictMath.round(a);
+ }
+
+ /**
+ * finally calls {@link java.lang.Math#round(double)}
+ */
+ public static long round(double a) {
+ return StrictMath.round(a);
+ }
+
+ /**
+ * finally calls {@link java.lang.Math#signum(double)}
+ */
+ public static double signum(double d) {
+ return StrictMath.signum(d);
+ }
+
+ /**
+ * finally calls {@link java.lang.Math#signum(float)}
+ */
+ public static long abs(long a) {
+ return StrictMath.abs(a);
+ }
+
+ /**
+ * *** methods are same as {@link java.lang.Math} methods, guaranteed by the call end ***
+ */
+
+ /**
+ * *** methods are same as {@link java.lang.Math} methods by mathematical algorithms***
+ * /
+
+
+ /**
+ * mathematical integer: ceil(i) = floor(i) = i
+ * @return the smallest (closest to negative infinity) double value that is greater
+ * than or equal to the argument and is equal to a mathematical integer.
+ */
+ public static double ceil(double a) {
+ return StrictMath.ceil(a);
+ }
+
+ /**
+ * *** methods are no matters ***
+ */
+ public static double random() {
+ return StrictMath.random();
+ }
+
+}
diff --git a/platform/src/main/java/arm/org/tron/common/utils/MarketOrderPriceComparatorForRocksDB.java b/platform/src/main/java/arm/org/tron/common/utils/MarketOrderPriceComparatorForRocksDB.java
new file mode 100644
index 00000000000..26c246faf0e
--- /dev/null
+++ b/platform/src/main/java/arm/org/tron/common/utils/MarketOrderPriceComparatorForRocksDB.java
@@ -0,0 +1,32 @@
+package org.tron.common.utils;
+
+import java.nio.ByteBuffer;
+import org.rocksdb.AbstractComparator;
+import org.rocksdb.ComparatorOptions;
+
+public class MarketOrderPriceComparatorForRocksDB extends AbstractComparator {
+
+ public MarketOrderPriceComparatorForRocksDB(final ComparatorOptions copt) {
+ super(copt);
+ }
+
+ @Override
+ public String name() {
+ return "MarketOrderPriceComparator";
+ }
+
+ @Override
+ public int compare(final ByteBuffer a, final ByteBuffer b) {
+ return MarketComparator.comparePriceKey(convertDataToBytes(a), convertDataToBytes(b));
+ }
+
+ /**
+ * DirectSlice.data().array will throw UnsupportedOperationException.
+ * */
+ public byte[] convertDataToBytes(ByteBuffer buf) {
+ byte[] bytes = new byte[buf.remaining()];
+ buf.get(bytes);
+ return bytes;
+ }
+
+}
diff --git a/platform/src/main/java/common/org/tron/common/arch/Arch.java b/platform/src/main/java/common/org/tron/common/arch/Arch.java
new file mode 100644
index 00000000000..20744d755a4
--- /dev/null
+++ b/platform/src/main/java/common/org/tron/common/arch/Arch.java
@@ -0,0 +1,86 @@
+package org.tron.common.arch;
+
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j(topic = "arch")
+public final class Arch {
+
+ private Arch() {
+ }
+
+ public static String withAll() {
+ final StringBuilder info = new StringBuilder();
+ info.append("os.name").append(": ").append(getOsName()).append("\n");
+ info.append("os.arch").append(": ").append(getOsArch()).append("\n");
+ info.append("bit.model").append(": ").append(getBitModel()).append("\n");
+ info.append("java.version").append(": ").append(javaVersion()).append("\n");
+ info.append("java.specification.version").append(": ").append(javaSpecificationVersion())
+ .append("\n");
+ info.append("java.vendor").append(": ").append(javaVendor()).append("\n");
+ return info.toString();
+ }
+
+ public static String getOsName() {
+ return System.getProperty("os.name").toLowerCase().trim();
+
+ }
+ public static String getOsArch() {
+ return System.getProperty("os.arch").toLowerCase().trim();
+ }
+
+ public static int getBitModel() {
+ String prop = System.getProperty("sun.arch.data.model");
+ if (prop == null) {
+ prop = System.getProperty("com.ibm.vm.bitmode");
+ }
+ if (prop != null) {
+ return Integer.parseInt(prop);
+ }
+ // GraalVM support, see https://github.com/fusesource/jansi/issues/162
+ String arch = System.getProperty("os.arch");
+ if (arch.endsWith("64") && "Substrate VM".equals(System.getProperty("java.vm.name"))) {
+ return 64;
+ }
+ return -1; // we don't know...
+ }
+
+ public static String javaVersion() {
+ return System.getProperty("java.version").toLowerCase().trim();
+ }
+
+ public static String javaSpecificationVersion() {
+ return System.getProperty("java.specification.version").toLowerCase().trim();
+ }
+
+ public static String javaVendor() {
+ return System.getProperty("java.vendor").toLowerCase().trim();
+ }
+
+ public static boolean isArm64() {
+ String osArch = getOsArch();
+ return osArch.contains("arm64") || osArch.contains("aarch64");
+ }
+
+ public static boolean isX86() {
+ return !isArm64();
+ }
+
+ public static boolean isJava8() {
+ return javaSpecificationVersion().equals("1.8");
+ }
+
+ public static void throwUnsupportedJavaException() {
+ if (isX86() && !isJava8()) {
+ logger.info(withAll());
+ throw new UnsupportedOperationException(String.format(
+ "Java %s is required for %s architecture. Detected version %s",
+ "1.8 ", getOsArch(), javaSpecificationVersion()));
+ }
+ }
+
+ public static void throwUnsupportedArm64Exception() {
+ if (isArm64()) {
+ throw new UnsupportedOperationException("unsupported on " + getOsArch() + " architecture");
+ }
+ }
+}
diff --git a/plugins/src/main/java/org/tron/plugins/utils/MarketUtils.java b/platform/src/main/java/common/org/tron/common/utils/MarketComparator.java
similarity index 50%
rename from plugins/src/main/java/org/tron/plugins/utils/MarketUtils.java
rename to platform/src/main/java/common/org/tron/common/utils/MarketComparator.java
index dbd578a59a3..c2742d4d10b 100644
--- a/plugins/src/main/java/org/tron/plugins/utils/MarketUtils.java
+++ b/platform/src/main/java/common/org/tron/common/utils/MarketComparator.java
@@ -1,71 +1,10 @@
-package org.tron.plugins.utils;
+package org.tron.common.utils;
import java.math.BigInteger;
-import org.tron.plugins.utils.ByteArray;
-public class MarketUtils {
+public class MarketComparator {
- public static final int TOKEN_ID_LENGTH = ByteArray
- .fromString(Long.toString(Long.MAX_VALUE)).length; // 19
-
-
-
- /**
- * In order to avoid the difference between the data of same key stored and fetched by hashMap and
- * levelDB, when creating the price key, we will find the GCD (Greatest Common Divisor) of
- * sellTokenQuantity and buyTokenQuantity.
- */
- public static byte[] createPairPriceKey(byte[] sellTokenId, byte[] buyTokenId,
- long sellTokenQuantity, long buyTokenQuantity) {
-
- byte[] sellTokenQuantityBytes;
- byte[] buyTokenQuantityBytes;
-
- // cal the GCD
- long gcd = findGCD(sellTokenQuantity, buyTokenQuantity);
- if (gcd == 0) {
- sellTokenQuantityBytes = ByteArray.fromLong(sellTokenQuantity);
- buyTokenQuantityBytes = ByteArray.fromLong(buyTokenQuantity);
- } else {
- sellTokenQuantityBytes = ByteArray.fromLong(sellTokenQuantity / gcd);
- buyTokenQuantityBytes = ByteArray.fromLong(buyTokenQuantity / gcd);
- }
-
- return doCreatePairPriceKey(sellTokenId, buyTokenId,
- sellTokenQuantityBytes, buyTokenQuantityBytes);
- }
-
- public static long findGCD(long number1, long number2) {
- if (number1 == 0 || number2 == 0) {
- return 0;
- }
- return calGCD(number1, number2);
- }
-
- private static long calGCD(long number1, long number2) {
- if (number2 == 0) {
- return number1;
- }
- return calGCD(number2, number1 % number2);
- }
-
-
- private static byte[] doCreatePairPriceKey(byte[] sellTokenId, byte[] buyTokenId,
- byte[] sellTokenQuantity, byte[] buyTokenQuantity) {
- byte[] result = new byte[TOKEN_ID_LENGTH + TOKEN_ID_LENGTH
- + sellTokenQuantity.length + buyTokenQuantity.length];
-
- System.arraycopy(sellTokenId, 0, result, 0, sellTokenId.length);
- System.arraycopy(buyTokenId, 0, result, TOKEN_ID_LENGTH, buyTokenId.length);
- System.arraycopy(sellTokenQuantity, 0, result,
- TOKEN_ID_LENGTH + TOKEN_ID_LENGTH,
- sellTokenQuantity.length);
- System.arraycopy(buyTokenQuantity, 0, result,
- TOKEN_ID_LENGTH + TOKEN_ID_LENGTH + buyTokenQuantity.length,
- buyTokenQuantity.length);
-
- return result;
- }
+ public static final int TOKEN_ID_LENGTH = Long.toString(Long.MAX_VALUE).getBytes().length; // 19
public static int comparePriceKey(byte[] o1, byte[] o2) {
@@ -76,7 +15,7 @@ public static int comparePriceKey(byte[] o1, byte[] o2) {
System.arraycopy(o1, 0, pair1, 0, TOKEN_ID_LENGTH * 2);
System.arraycopy(o2, 0, pair2, 0, TOKEN_ID_LENGTH * 2);
- int pairResult = ByteArray.compareUnsigned(pair1, pair2);
+ int pairResult = compareUnsigned(pair1, pair2);
if (pairResult != 0) {
return pairResult;
}
@@ -100,10 +39,10 @@ public static int comparePriceKey(byte[] o1, byte[] o2) {
System.arraycopy(o2, TOKEN_ID_LENGTH + TOKEN_ID_LENGTH + longByteNum,
getBuyTokenQuantity2, 0, longByteNum);
- long sellTokenQuantity1 = ByteArray.toLong(getSellTokenQuantity1);
- long buyTokenQuantity1 = ByteArray.toLong(getBuyTokenQuantity1);
- long sellTokenQuantity2 = ByteArray.toLong(getSellTokenQuantity2);
- long buyTokenQuantity2 = ByteArray.toLong(getBuyTokenQuantity2);
+ long sellTokenQuantity1 = toLong(getSellTokenQuantity1);
+ long buyTokenQuantity1 = toLong(getBuyTokenQuantity1);
+ long sellTokenQuantity2 = toLong(getSellTokenQuantity2);
+ long buyTokenQuantity2 = toLong(getBuyTokenQuantity2);
if ((sellTokenQuantity1 == 0 || buyTokenQuantity1 == 0)
&& (sellTokenQuantity2 == 0 || buyTokenQuantity2 == 0)) {
@@ -145,4 +84,41 @@ public static int comparePrice(long price1SellQuantity, long price1BuyQuantity,
return price1BuyQuantityBI.multiply(price2SellQuantityBI)
.compareTo(price2BuyQuantityBI.multiply(price1SellQuantityBI));
}
+
+ /**
+ * copy from org.bouncycastle.util.Arrays.compareUnsigned
+ */
+ private static int compareUnsigned(byte[] a, byte[] b) {
+ if (a == b) {
+ return 0;
+ }
+ if (a == null) {
+ return -1;
+ }
+ if (b == null) {
+ return 1;
+ }
+ int minLen = StrictMath.min(a.length, b.length);
+ for (int i = 0; i < minLen; ++i) {
+ int aVal = a[i] & 0xFF;
+ int bVal = b[i] & 0xFF;
+ if (aVal < bVal) {
+ return -1;
+ }
+ if (aVal > bVal) {
+ return 1;
+ }
+ }
+ if (a.length < b.length) {
+ return -1;
+ }
+ if (a.length > b.length) {
+ return 1;
+ }
+ return 0;
+ }
+
+ public static long toLong(byte[] b) {
+ return (b == null || b.length == 0) ? 0 : new BigInteger(1, b).longValue();
+ }
}
diff --git a/chainbase/src/main/java/org/tron/common/utils/MarketOrderPriceComparatorForLevelDB.java b/platform/src/main/java/common/org/tron/common/utils/MarketOrderPriceComparatorForLevelDB.java
similarity index 87%
rename from chainbase/src/main/java/org/tron/common/utils/MarketOrderPriceComparatorForLevelDB.java
rename to platform/src/main/java/common/org/tron/common/utils/MarketOrderPriceComparatorForLevelDB.java
index c4c519f68f1..efb7219b211 100644
--- a/chainbase/src/main/java/org/tron/common/utils/MarketOrderPriceComparatorForLevelDB.java
+++ b/platform/src/main/java/common/org/tron/common/utils/MarketOrderPriceComparatorForLevelDB.java
@@ -1,7 +1,5 @@
package org.tron.common.utils;
-import org.tron.core.capsule.utils.MarketUtils;
-
public class MarketOrderPriceComparatorForLevelDB implements org.iq80.leveldb.DBComparator {
@Override
@@ -26,7 +24,7 @@ public byte[] findShortSuccessor(byte[] key) {
*/
@Override
public int compare(byte[] o1, byte[] o2) {
- return MarketUtils.comparePriceKey(o1, o2);
+ return MarketComparator.comparePriceKey(o1, o2);
}
}
diff --git a/common/src/main/java/org/tron/common/math/MathWrapper.java b/platform/src/main/java/x86/org/tron/common/math/MathWrapper.java
similarity index 100%
rename from common/src/main/java/org/tron/common/math/MathWrapper.java
rename to platform/src/main/java/x86/org/tron/common/math/MathWrapper.java
diff --git a/chainbase/src/main/java/org/tron/common/utils/MarketOrderPriceComparatorForRockDB.java b/platform/src/main/java/x86/org/tron/common/utils/MarketOrderPriceComparatorForRocksDB.java
similarity index 70%
rename from chainbase/src/main/java/org/tron/common/utils/MarketOrderPriceComparatorForRockDB.java
rename to platform/src/main/java/x86/org/tron/common/utils/MarketOrderPriceComparatorForRocksDB.java
index d3812f0f6bc..be406ff658d 100644
--- a/chainbase/src/main/java/org/tron/common/utils/MarketOrderPriceComparatorForRockDB.java
+++ b/platform/src/main/java/x86/org/tron/common/utils/MarketOrderPriceComparatorForRocksDB.java
@@ -3,11 +3,10 @@
import org.rocksdb.ComparatorOptions;
import org.rocksdb.DirectSlice;
import org.rocksdb.util.DirectBytewiseComparator;
-import org.tron.core.capsule.utils.MarketUtils;
-public class MarketOrderPriceComparatorForRockDB extends DirectBytewiseComparator {
+public class MarketOrderPriceComparatorForRocksDB extends DirectBytewiseComparator {
- public MarketOrderPriceComparatorForRockDB(final ComparatorOptions copt) {
+ public MarketOrderPriceComparatorForRocksDB(final ComparatorOptions copt) {
super(copt);
}
@@ -18,7 +17,7 @@ public String name() {
@Override
public int compare(final DirectSlice a, final DirectSlice b) {
- return MarketUtils.comparePriceKey(convertDataToBytes(a), convertDataToBytes(b));
+ return MarketComparator.comparePriceKey(convertDataToBytes(a), convertDataToBytes(b));
}
/**
diff --git a/plugins/README.md b/plugins/README.md
index 0db6f2e6143..db25811882f 100644
--- a/plugins/README.md
+++ b/plugins/README.md
@@ -2,7 +2,7 @@
This package contains a set of tools for TRON, the followings are the documentation for each tool.
-## DB Archive
+## DB Archive(Requires x86 + LevelDB)
DB archive provides the ability to reformat the manifest according to the current `database`, parameters are compatible with the previous `ArchiveManifest`.
@@ -26,7 +26,7 @@ DB archive provides the ability to reformat the manifest according to the curren
```
-## DB Convert
+## DB Convert(Requires x86 + LevelDB)
DB convert provides a helper which can convert LevelDB data to RocksDB data, parameters are compatible with previous `DBConvert`.
@@ -34,15 +34,13 @@ DB convert provides a helper which can convert LevelDB data to RocksDB data, par
- ``: Input path for leveldb, default: output-directory/database.
- ``: Output path for rocksdb, default: output-directory-dst/database.
-- `--safe`: In safe mode, read data from leveldb then put into rocksdb, it's a very time-consuming procedure. If not, just change engine.properties from leveldb to rocksdb, rocksdb
- is compatible with leveldb for the current version. This may not be the case in the future, default: false.
- `-h | --help`: Provide the help info.
### Examples:
```shell script
# full command
- java -jar Toolkit.jar db convert [-h] [--safe]
+ java -jar Toolkit.jar db convert [-h]
# examples
java -jar Toolkit.jar db convert output-directory/database /tmp/database
```
@@ -66,7 +64,7 @@ DB copy provides a helper which can copy LevelDB or RocksDB data quickly on the
java -jar Toolkit.jar db cp output-directory/database /tmp/databse
```
-## DB Lite
+## DB Lite(LevelDB unavailable on ARM)
DB lite provides lite database, parameters are compatible with previous `LiteFullNodeTool`.
@@ -134,7 +132,7 @@ Execute move command.
java -jar Toolkit.jar db mv -c main_net_config.conf -d /data/tron/output-directory
```
-## DB Root
+## DB Root(LevelDB unavailable on ARM)
DB root provides a helper which can compute merkle root for tiny db.
diff --git a/plugins/build.gradle b/plugins/build.gradle
index 01afaa01708..40d68e19d2f 100644
--- a/plugins/build.gradle
+++ b/plugins/build.gradle
@@ -20,6 +20,15 @@ configurations.getByName('checkstyleConfig') {
transitive = false
}
+sourceSets {
+ main {
+ java.srcDirs = rootProject.archInfo.sourceSets.main.java.srcDirs
+ }
+ test {
+ java.srcDirs = rootProject.archInfo.sourceSets.test.java.srcDirs
+ }
+}
+
dependencies {
//local libraries
implementation fileTree(dir: 'libs', include: '*.jar')
@@ -29,9 +38,18 @@ dependencies {
implementation group: 'com.typesafe', name: 'config', version: '1.3.2'
implementation group: 'me.tongfei', name: 'progressbar', version: '0.9.3'
implementation group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.69'
- implementation group: 'org.rocksdb', name: 'rocksdbjni', version: '5.15.10'
- implementation 'io.github.tronprotocol:leveldbjni-all:1.18.2'
- implementation 'io.github.tronprotocol:leveldb:1.18.2'
+ if (rootProject.archInfo.isArm64) {
+ testRuntimeOnly group: 'org.fusesource.hawtjni', name: 'hawtjni-runtime', version: '1.18' // for test
+ implementation project(":platform")
+ } else {
+ implementation project(":platform"), {
+ exclude(group: 'org.fusesource.leveldbjni', module: 'leveldbjni-all')
+ exclude(group: 'io.github.tronprotocol', module: 'zksnark-java-sdk')
+ exclude(group: 'commons-io', module: 'commons-io')
+ }
+ implementation 'io.github.tronprotocol:leveldbjni-all:1.18.2'
+ implementation 'io.github.tronprotocol:leveldb:1.18.2'
+ }
implementation project(":protocol")
}
@@ -76,6 +94,17 @@ test {
destinationFile = file("../framework/build/jacoco/jacocoTest1.exec")
classDumpDir = file("$buildDir/jacoco/classpathdumps")
}
+
+ if (rootProject.archInfo.isArm64) {
+ exclude 'org/tron/plugins/leveldb/**'
+ filter {
+ excludeTestsMatching '*.*leveldb*'
+ excludeTestsMatching '*.*Leveldb*'
+ excludeTestsMatching '*.*LevelDB*'
+ excludeTestsMatching '*.*LevelDb*'
+ excludeTestsMatching '*.*Archive*'
+ }
+ }
}
jacocoTestReport {
@@ -94,7 +123,7 @@ def binaryRelease(taskName, jarName, mainClass) {
from(sourceSets.main.output) {
include "/**"
}
- dependsOn project(':protocol').jar // explicit_dependency
+ dependsOn (project(':protocol').jar, project(':platform').jar) // explicit_dependency
from {
configurations.runtimeClasspath.collect { // https://docs.gradle.org/current/userguide/upgrading_version_6.html#changes_6.3
it.isDirectory() ? it : zipTree(it)
@@ -127,7 +156,7 @@ def createScript(project, mainClass, name) {
}
}
}
-applicationDistribution.from("../gradle/java-tron.vmoptions") {
+applicationDistribution.from(rootProject.archInfo.VMOptions) {
into "bin"
}
createScript(project, 'org.tron.plugins.ArchiveManifest', 'ArchiveManifest')
diff --git a/plugins/src/main/java/arm/org/tron/plugins/ArchiveManifest.java b/plugins/src/main/java/arm/org/tron/plugins/ArchiveManifest.java
new file mode 100644
index 00000000000..b7848cf4c6f
--- /dev/null
+++ b/plugins/src/main/java/arm/org/tron/plugins/ArchiveManifest.java
@@ -0,0 +1,29 @@
+package org.tron.plugins;
+
+import lombok.extern.slf4j.Slf4j;
+import org.tron.common.arch.Arch;
+
+/**
+ * ARM architecture only supports RocksDB,
+ * which does not require manifest rebuilding (manifest rebuilding is a LevelDB-only feature).
+ * This command is not supported but retained for compatibility.
+ **/
+@Slf4j(topic = "archive")
+public class ArchiveManifest {
+
+ public static void main(String[] args) {
+ int exitCode = run(args);
+ System.exit(exitCode);
+ }
+
+ public static int run(String[] args) {
+ String tips = String.format(
+ "%s architecture only supports RocksDB, which does not require manifest rebuilding "
+ + "(manifest rebuilding is a LevelDB-only feature).",
+ Arch.getOsArch());
+ System.out.println(tips);
+ logger.warn(tips);
+ return 0;
+ }
+
+}
diff --git a/plugins/src/main/java/arm/org/tron/plugins/DbArchive.java b/plugins/src/main/java/arm/org/tron/plugins/DbArchive.java
new file mode 100644
index 00000000000..03c52f33f02
--- /dev/null
+++ b/plugins/src/main/java/arm/org/tron/plugins/DbArchive.java
@@ -0,0 +1,50 @@
+package org.tron.plugins;
+
+import java.util.concurrent.Callable;
+import lombok.extern.slf4j.Slf4j;
+import org.tron.common.arch.Arch;
+import picocli.CommandLine;
+import picocli.CommandLine.Option;
+
+/**
+ * ARM architecture only supports RocksDB,
+ * which does not require manifest rebuilding (manifest rebuilding is a LevelDB-only feature).
+ * This command is not supported but retained for compatibility.
+ **/
+@Slf4j(topic = "archive")
+@CommandLine.Command(name = "archive", description = "A helper to rewrite leveldb manifest.")
+public class DbArchive implements Callable {
+
+ @CommandLine.Spec
+ CommandLine.Model.CommandSpec spec;
+ @Option(names = {"-d", "--database-directory"},
+ defaultValue = "output-directory/database",
+ description = "java-tron database directory. Default: ${DEFAULT-VALUE}")
+ private String databaseDirectory;
+
+ @Option(names = {"-b", "--batch-size"},
+ defaultValue = "80000",
+ description = "deal manifest batch size. Default: ${DEFAULT-VALUE}")
+ private int maxBatchSize;
+
+ @Option(names = {"-m", "--manifest-size"},
+ defaultValue = "0",
+ description = "manifest min size(M) to archive. Default: ${DEFAULT-VALUE}")
+ private int maxManifestSize;
+
+ @Option(names = {"-h", "--help"})
+ private boolean help;
+
+
+ @Override
+ public Integer call() throws Exception {
+ String tips = String.format(
+ "%s architecture only supports RocksDB, which does not require manifest rebuilding "
+ + "(manifest rebuilding is a LevelDB-only feature).",
+ Arch.getOsArch());
+ spec.commandLine().getErr().println(spec.commandLine().getColorScheme().errorText(tips));
+ logger.warn(tips);
+ return 0;
+ }
+
+}
diff --git a/plugins/src/main/java/org/tron/plugins/Db.java b/plugins/src/main/java/common/org/tron/plugins/Db.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/Db.java
rename to plugins/src/main/java/common/org/tron/plugins/Db.java
diff --git a/plugins/src/main/java/org/tron/plugins/DbConvert.java b/plugins/src/main/java/common/org/tron/plugins/DbConvert.java
similarity index 91%
rename from plugins/src/main/java/org/tron/plugins/DbConvert.java
rename to plugins/src/main/java/common/org/tron/plugins/DbConvert.java
index a75b235bbcf..37ea6bdeca4 100644
--- a/plugins/src/main/java/org/tron/plugins/DbConvert.java
+++ b/plugins/src/main/java/common/org/tron/plugins/DbConvert.java
@@ -20,6 +20,7 @@
import org.rocksdb.RocksDBException;
import org.rocksdb.RocksIterator;
import org.rocksdb.Status;
+import org.tron.common.arch.Arch;
import org.tron.plugins.utils.DBUtils;
import org.tron.plugins.utils.FileUtils;
import picocli.CommandLine;
@@ -49,20 +50,19 @@ public class DbConvert implements Callable {
description = "Output path for rocksdb. Default: ${DEFAULT-VALUE}")
private File dest;
- @CommandLine.Option(names = {"--safe"},
- description = "In safe mode, read data from leveldb then put rocksdb."
- + "If not, just change engine.properties from leveldb to rocksdb,"
- + "rocksdb is compatible with leveldb for current version."
- + "This may not be the case in the future."
- + "Default: ${DEFAULT-VALUE}")
- private boolean safe;
-
@CommandLine.Option(names = {"-h", "--help"})
private boolean help;
@Override
public Integer call() throws Exception {
+ if (Arch.isArm64()) {
+ String tips = String.format("This command is not supported on %s architecture.",
+ Arch.getOsArch());
+ spec.commandLine().getErr().println(spec.commandLine().getColorScheme().errorText(tips));
+ logger.error(tips);
+ return 0;
+ }
if (help) {
spec.commandLine().usage(System.out);
return 0;
@@ -95,12 +95,12 @@ public Integer call() throws Exception {
final long time = System.currentTimeMillis();
List services = new ArrayList<>();
files.forEach(f -> services.add(
- new DbConverter(src.getPath(), dest.getPath(), f.getName(), safe)));
+ new DbConverter(src.getPath(), dest.getPath(), f.getName())));
cpList.forEach(f -> services.add(
new DbConverter(
Paths.get(src.getPath(), DBUtils.CHECKPOINT_DB_V2).toString(),
Paths.get(dest.getPath(), DBUtils.CHECKPOINT_DB_V2).toString(),
- f.getName(), safe)));
+ f.getName())));
List fails = ProgressBar.wrap(services.stream(), "convert task").parallel().map(
dbConverter -> {
try {
@@ -140,15 +140,12 @@ static class DbConverter implements Converter {
private long srcDbValueSum = 0L;
private long dstDbValueSum = 0L;
- private boolean safe;
-
- public DbConverter(String srcDir, String dstDir, String name, boolean safe) {
+ public DbConverter(String srcDir, String dstDir, String name) {
this.srcDir = srcDir;
this.dstDir = dstDir;
this.dbName = name;
this.srcDbPath = Paths.get(this.srcDir, name);
this.dstDbPath = Paths.get(this.dstDir, name);
- this.safe = safe;
}
@Override
@@ -178,23 +175,15 @@ public boolean doConvert() throws Exception {
FileUtils.createDirIfNotExists(dstDir);
logger.info("Convert database {} start", this.dbName);
- if (safe) {
- convertLevelToRocks();
- compact();
- } else {
- FileUtils.copyDir(Paths.get(srcDir), Paths.get(dstDir), dbName);
- }
+ convertLevelToRocks();
+ compact();
+
boolean result = check() && createEngine(dstDbPath.toString());
long etime = System.currentTimeMillis();
if (result) {
- if (safe) {
- logger.info("Convert database {} successful end with {} key-value {} minutes",
- this.dbName, this.srcDbKeyCount, (etime - startTime) / 1000.0 / 60);
- } else {
- logger.info("Convert database {} successful end {} minutes",
- this.dbName, (etime - startTime) / 1000.0 / 60);
- }
+ logger.info("Convert database {} successful end with {} key-value {} minutes",
+ this.dbName, this.srcDbKeyCount, (etime - startTime) / 1000.0 / 60);
} else {
logger.info("Convert database {} failure", this.dbName);
@@ -310,9 +299,6 @@ private void compact() throws RocksDBException {
}
private boolean check() throws RocksDBException {
- if (!safe) {
- return true;
- }
try (
RocksDB rocks = DBUtils.newRocksDbReadOnly(this.dstDbPath);
org.rocksdb.ReadOptions r = new org.rocksdb.ReadOptions().setFillCache(false);
diff --git a/plugins/src/main/java/org/tron/plugins/DbCopy.java b/plugins/src/main/java/common/org/tron/plugins/DbCopy.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/DbCopy.java
rename to plugins/src/main/java/common/org/tron/plugins/DbCopy.java
diff --git a/plugins/src/main/java/org/tron/plugins/DbLite.java b/plugins/src/main/java/common/org/tron/plugins/DbLite.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/DbLite.java
rename to plugins/src/main/java/common/org/tron/plugins/DbLite.java
diff --git a/plugins/src/main/java/org/tron/plugins/DbMove.java b/plugins/src/main/java/common/org/tron/plugins/DbMove.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/DbMove.java
rename to plugins/src/main/java/common/org/tron/plugins/DbMove.java
diff --git a/plugins/src/main/java/org/tron/plugins/DbRoot.java b/plugins/src/main/java/common/org/tron/plugins/DbRoot.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/DbRoot.java
rename to plugins/src/main/java/common/org/tron/plugins/DbRoot.java
diff --git a/plugins/src/main/java/org/tron/plugins/Toolkit.java b/plugins/src/main/java/common/org/tron/plugins/Toolkit.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/Toolkit.java
rename to plugins/src/main/java/common/org/tron/plugins/Toolkit.java
diff --git a/plugins/src/main/java/org/tron/plugins/utils/ByteArray.java b/plugins/src/main/java/common/org/tron/plugins/utils/ByteArray.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/utils/ByteArray.java
rename to plugins/src/main/java/common/org/tron/plugins/utils/ByteArray.java
diff --git a/plugins/src/main/java/org/tron/plugins/utils/CryptoUitls.java b/plugins/src/main/java/common/org/tron/plugins/utils/CryptoUitls.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/utils/CryptoUitls.java
rename to plugins/src/main/java/common/org/tron/plugins/utils/CryptoUitls.java
diff --git a/plugins/src/main/java/org/tron/plugins/utils/DBUtils.java b/plugins/src/main/java/common/org/tron/plugins/utils/DBUtils.java
similarity index 94%
rename from plugins/src/main/java/org/tron/plugins/utils/DBUtils.java
rename to plugins/src/main/java/common/org/tron/plugins/utils/DBUtils.java
index f8559d5dba8..507a8ad798e 100644
--- a/plugins/src/main/java/org/tron/plugins/utils/DBUtils.java
+++ b/plugins/src/main/java/common/org/tron/plugins/utils/DBUtils.java
@@ -16,8 +16,9 @@
import org.rocksdb.Options;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
-import org.tron.plugins.comparator.MarketOrderPriceComparatorForLevelDB;
-import org.tron.plugins.comparator.MarketOrderPriceComparatorForRockDB;
+import org.tron.common.arch.Arch;
+import org.tron.common.utils.MarketOrderPriceComparatorForLevelDB;
+import org.tron.common.utils.MarketOrderPriceComparatorForRocksDB;
import org.tron.protos.Protocol;
public class DBUtils {
@@ -65,6 +66,7 @@ static Operator valueOf(byte b) {
public static final String ROCKSDB = "ROCKSDB";
public static DB newLevelDb(Path db) throws IOException {
+ Arch.throwUnsupportedArm64Exception();
File file = db.toFile();
org.iq80.leveldb.Options dbOptions = newDefaultLevelDbOptions();
if (MARKET_PAIR_PRICE_TO_ORDER.equalsIgnoreCase(file.getName())) {
@@ -115,7 +117,7 @@ private static Options newDefaultRocksDbOptions(boolean forBulkLoad) {
public static RocksDB newRocksDb(Path db) throws RocksDBException {
try (Options options = newDefaultRocksDbOptions(false)) {
if (MARKET_PAIR_PRICE_TO_ORDER.equalsIgnoreCase(db.getFileName().toString())) {
- options.setComparator(new MarketOrderPriceComparatorForRockDB(new ComparatorOptions()));
+ options.setComparator(new MarketOrderPriceComparatorForRocksDB(new ComparatorOptions()));
}
return RocksDB.open(options, db.toString());
}
@@ -124,7 +126,7 @@ public static RocksDB newRocksDb(Path db) throws RocksDBException {
public static RocksDB newRocksDbForBulkLoad(Path db) throws RocksDBException {
try (Options options = newDefaultRocksDbOptions(true)) {
if (MARKET_PAIR_PRICE_TO_ORDER.equalsIgnoreCase(db.getFileName().toString())) {
- options.setComparator(new MarketOrderPriceComparatorForRockDB(new ComparatorOptions()));
+ options.setComparator(new MarketOrderPriceComparatorForRocksDB(new ComparatorOptions()));
}
return RocksDB.open(options, db.toString());
}
@@ -134,7 +136,7 @@ public static RocksDB newRocksDbForBulkLoad(Path db) throws RocksDBException {
public static RocksDB newRocksDbReadOnly(Path db) throws RocksDBException {
try (Options options = newDefaultRocksDbOptions(false)) {
if (MARKET_PAIR_PRICE_TO_ORDER.equalsIgnoreCase(db.getFileName().toString())) {
- options.setComparator(new MarketOrderPriceComparatorForRockDB(new ComparatorOptions()));
+ options.setComparator(new MarketOrderPriceComparatorForRocksDB(new ComparatorOptions()));
}
return RocksDB.openReadOnly(options, db.toString());
}
diff --git a/plugins/src/main/java/org/tron/plugins/utils/FileUtils.java b/plugins/src/main/java/common/org/tron/plugins/utils/FileUtils.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/utils/FileUtils.java
rename to plugins/src/main/java/common/org/tron/plugins/utils/FileUtils.java
diff --git a/plugins/src/main/java/common/org/tron/plugins/utils/MarketUtils.java b/plugins/src/main/java/common/org/tron/plugins/utils/MarketUtils.java
new file mode 100644
index 00000000000..9bcfd5e71ce
--- /dev/null
+++ b/plugins/src/main/java/common/org/tron/plugins/utils/MarketUtils.java
@@ -0,0 +1,68 @@
+package org.tron.plugins.utils;
+
+public class MarketUtils {
+
+ public static final int TOKEN_ID_LENGTH = ByteArray
+ .fromString(Long.toString(Long.MAX_VALUE)).length; // 19
+
+
+
+ /**
+ * In order to avoid the difference between the data of same key stored and fetched by hashMap and
+ * levelDB, when creating the price key, we will find the GCD (Greatest Common Divisor) of
+ * sellTokenQuantity and buyTokenQuantity.
+ */
+ public static byte[] createPairPriceKey(byte[] sellTokenId, byte[] buyTokenId,
+ long sellTokenQuantity, long buyTokenQuantity) {
+
+ byte[] sellTokenQuantityBytes;
+ byte[] buyTokenQuantityBytes;
+
+ // cal the GCD
+ long gcd = findGCD(sellTokenQuantity, buyTokenQuantity);
+ if (gcd == 0) {
+ sellTokenQuantityBytes = ByteArray.fromLong(sellTokenQuantity);
+ buyTokenQuantityBytes = ByteArray.fromLong(buyTokenQuantity);
+ } else {
+ sellTokenQuantityBytes = ByteArray.fromLong(sellTokenQuantity / gcd);
+ buyTokenQuantityBytes = ByteArray.fromLong(buyTokenQuantity / gcd);
+ }
+
+ return doCreatePairPriceKey(sellTokenId, buyTokenId,
+ sellTokenQuantityBytes, buyTokenQuantityBytes);
+ }
+
+ public static long findGCD(long number1, long number2) {
+ if (number1 == 0 || number2 == 0) {
+ return 0;
+ }
+ return calGCD(number1, number2);
+ }
+
+ private static long calGCD(long number1, long number2) {
+ if (number2 == 0) {
+ return number1;
+ }
+ return calGCD(number2, number1 % number2);
+ }
+
+
+ private static byte[] doCreatePairPriceKey(byte[] sellTokenId, byte[] buyTokenId,
+ byte[] sellTokenQuantity, byte[] buyTokenQuantity) {
+ byte[] result = new byte[TOKEN_ID_LENGTH + TOKEN_ID_LENGTH
+ + sellTokenQuantity.length + buyTokenQuantity.length];
+
+ System.arraycopy(sellTokenId, 0, result, 0, sellTokenId.length);
+ System.arraycopy(buyTokenId, 0, result, TOKEN_ID_LENGTH, buyTokenId.length);
+ System.arraycopy(sellTokenQuantity, 0, result,
+ TOKEN_ID_LENGTH + TOKEN_ID_LENGTH,
+ sellTokenQuantity.length);
+ System.arraycopy(buyTokenQuantity, 0, result,
+ TOKEN_ID_LENGTH + TOKEN_ID_LENGTH + buyTokenQuantity.length,
+ buyTokenQuantity.length);
+
+ return result;
+ }
+
+
+}
diff --git a/plugins/src/main/java/org/tron/plugins/utils/MerkleRoot.java b/plugins/src/main/java/common/org/tron/plugins/utils/MerkleRoot.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/utils/MerkleRoot.java
rename to plugins/src/main/java/common/org/tron/plugins/utils/MerkleRoot.java
diff --git a/plugins/src/main/java/org/tron/plugins/utils/Sha256Hash.java b/plugins/src/main/java/common/org/tron/plugins/utils/Sha256Hash.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/utils/Sha256Hash.java
rename to plugins/src/main/java/common/org/tron/plugins/utils/Sha256Hash.java
diff --git a/plugins/src/main/java/org/tron/plugins/utils/db/DBInterface.java b/plugins/src/main/java/common/org/tron/plugins/utils/db/DBInterface.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/utils/db/DBInterface.java
rename to plugins/src/main/java/common/org/tron/plugins/utils/db/DBInterface.java
diff --git a/plugins/src/main/java/org/tron/plugins/utils/db/DBIterator.java b/plugins/src/main/java/common/org/tron/plugins/utils/db/DBIterator.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/utils/db/DBIterator.java
rename to plugins/src/main/java/common/org/tron/plugins/utils/db/DBIterator.java
diff --git a/plugins/src/main/java/org/tron/plugins/utils/db/DbTool.java b/plugins/src/main/java/common/org/tron/plugins/utils/db/DbTool.java
similarity index 85%
rename from plugins/src/main/java/org/tron/plugins/utils/db/DbTool.java
rename to plugins/src/main/java/common/org/tron/plugins/utils/db/DbTool.java
index 429025e8f8b..cf4c69505bc 100644
--- a/plugins/src/main/java/org/tron/plugins/utils/db/DbTool.java
+++ b/plugins/src/main/java/common/org/tron/plugins/utils/db/DbTool.java
@@ -18,8 +18,8 @@ public class DbTool {
private static final String KEY_ENGINE = "ENGINE";
private static final String ENGINE_FILE = "engine.properties";
- private static final String FILE_SEPARATOR = File.separator;
private static final String ROCKSDB = "ROCKSDB";
+ private static final String LEVELDB = "LEVELDB";
private static final Map dbMap = Maps.newConcurrentMap();
@@ -162,8 +162,7 @@ public static void close() {
}
private static DbType getDbType(String sourceDir, String dbName) {
- String engineFile = String.format("%s%s%s%s%s", sourceDir, FILE_SEPARATOR,
- dbName, FILE_SEPARATOR, ENGINE_FILE);
+ String engineFile = Paths.get(sourceDir, dbName, ENGINE_FILE).toString();
if (!new File(engineFile).exists()) {
return DbType.LevelDB;
}
@@ -175,13 +174,22 @@ private static DbType getDbType(String sourceDir, String dbName) {
}
}
- private static LevelDBImpl openLevelDb(Path db, String name) throws IOException {
- return new LevelDBImpl(DBUtils.newLevelDb(db), name);
+ public static LevelDBImpl openLevelDb(Path db, String name) throws IOException {
+ LevelDBImpl leveldb = new LevelDBImpl(DBUtils.newLevelDb(db), name);
+ tryInitEngineFile(db, LEVELDB);
+ return leveldb;
}
- private static RocksDBImpl openRocksDb(Path db, String name) throws RocksDBException {
- return new RocksDBImpl(DBUtils.newRocksDb(db), name);
+ public static RocksDBImpl openRocksDb(Path db, String name) throws RocksDBException {
+ RocksDBImpl rocksdb = new RocksDBImpl(DBUtils.newRocksDb(db), name);
+ tryInitEngineFile(db, ROCKSDB);
+ return rocksdb;
}
-
+ private static void tryInitEngineFile(Path db, String engine) {
+ String engineFile = Paths.get(db.toString(), ENGINE_FILE).toString();
+ if (FileUtils.createFileIfNotExists(engineFile)) {
+ FileUtils.writeProperty(engineFile, KEY_ENGINE, engine);
+ }
+ }
}
diff --git a/plugins/src/main/java/org/tron/plugins/utils/db/LevelDBImpl.java b/plugins/src/main/java/common/org/tron/plugins/utils/db/LevelDBImpl.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/utils/db/LevelDBImpl.java
rename to plugins/src/main/java/common/org/tron/plugins/utils/db/LevelDBImpl.java
diff --git a/plugins/src/main/java/org/tron/plugins/utils/db/LevelDBIterator.java b/plugins/src/main/java/common/org/tron/plugins/utils/db/LevelDBIterator.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/utils/db/LevelDBIterator.java
rename to plugins/src/main/java/common/org/tron/plugins/utils/db/LevelDBIterator.java
diff --git a/plugins/src/main/java/org/tron/plugins/utils/db/RockDBIterator.java b/plugins/src/main/java/common/org/tron/plugins/utils/db/RockDBIterator.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/utils/db/RockDBIterator.java
rename to plugins/src/main/java/common/org/tron/plugins/utils/db/RockDBIterator.java
diff --git a/plugins/src/main/java/org/tron/plugins/utils/db/RocksDBImpl.java b/plugins/src/main/java/common/org/tron/plugins/utils/db/RocksDBImpl.java
similarity index 100%
rename from plugins/src/main/java/org/tron/plugins/utils/db/RocksDBImpl.java
rename to plugins/src/main/java/common/org/tron/plugins/utils/db/RocksDBImpl.java
diff --git a/plugins/src/main/java/org/tron/plugins/comparator/MarketOrderPriceComparatorForLevelDB.java b/plugins/src/main/java/org/tron/plugins/comparator/MarketOrderPriceComparatorForLevelDB.java
deleted file mode 100644
index 0879f770e1f..00000000000
--- a/plugins/src/main/java/org/tron/plugins/comparator/MarketOrderPriceComparatorForLevelDB.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package org.tron.plugins.comparator;
-
-import org.iq80.leveldb.DBComparator;
-import org.tron.plugins.utils.MarketUtils;
-
-public class MarketOrderPriceComparatorForLevelDB implements DBComparator {
-
- @Override
- public String name() {
- return "MarketOrderPriceComparator";
- }
-
- @Override
- public byte[] findShortestSeparator(byte[] start, byte[] limit) {
- return new byte[0];
- }
-
- @Override
- public byte[] findShortSuccessor(byte[] key) {
- return new byte[0];
- }
-
- @Override
- public int compare(byte[] o1, byte[] o2) {
- return MarketUtils.comparePriceKey(o1, o2);
- }
-
-}
\ No newline at end of file
diff --git a/plugins/src/main/java/org/tron/plugins/comparator/MarketOrderPriceComparatorForRockDB.java b/plugins/src/main/java/org/tron/plugins/comparator/MarketOrderPriceComparatorForRockDB.java
deleted file mode 100644
index cd718bdd2d7..00000000000
--- a/plugins/src/main/java/org/tron/plugins/comparator/MarketOrderPriceComparatorForRockDB.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package org.tron.plugins.comparator;
-
-import org.rocksdb.ComparatorOptions;
-import org.rocksdb.DirectSlice;
-import org.rocksdb.util.DirectBytewiseComparator;
-import org.tron.plugins.utils.MarketUtils;
-
-public class MarketOrderPriceComparatorForRockDB extends DirectBytewiseComparator {
-
- public MarketOrderPriceComparatorForRockDB(final ComparatorOptions copt) {
- super(copt);
- }
-
- @Override
- public String name() {
- return "MarketOrderPriceComparator";
- }
-
- @Override
- public int compare(final DirectSlice a, final DirectSlice b) {
- return MarketUtils.comparePriceKey(convertDataToBytes(a), convertDataToBytes(b));
- }
-
- /**
- * DirectSlice.data().array will throw UnsupportedOperationException.
- * */
- public byte[] convertDataToBytes(DirectSlice directSlice) {
- int capacity = directSlice.data().capacity();
- byte[] bytes = new byte[capacity];
-
- for (int i = 0; i < capacity; i++) {
- bytes[i] = directSlice.get(i);
- }
-
- return bytes;
- }
-
-}
\ No newline at end of file
diff --git a/plugins/src/main/java/org/tron/plugins/ArchiveManifest.java b/plugins/src/main/java/x86/org/tron/plugins/ArchiveManifest.java
similarity index 98%
rename from plugins/src/main/java/org/tron/plugins/ArchiveManifest.java
rename to plugins/src/main/java/x86/org/tron/plugins/ArchiveManifest.java
index 4d54df6d299..1d7a91027bf 100644
--- a/plugins/src/main/java/org/tron/plugins/ArchiveManifest.java
+++ b/plugins/src/main/java/x86/org/tron/plugins/ArchiveManifest.java
@@ -35,6 +35,7 @@
import org.iq80.leveldb.DB;
import org.iq80.leveldb.Options;
import org.iq80.leveldb.impl.Filename;
+import org.tron.plugins.utils.DBUtils;
import picocli.CommandLine;
import picocli.CommandLine.Option;
@@ -183,7 +184,7 @@ public boolean checkManifest(String dir) throws IOException {
return false;
}
logger.info("CurrentName {}/{},size {} kb.", dir, currentName, current.length() / 1024);
- if ("market_pair_price_to_order".equalsIgnoreCase(this.name)) {
+ if (DBUtils.MARKET_PAIR_PRICE_TO_ORDER.equalsIgnoreCase(this.name)) {
logger.info("Db {} ignored.", this.name);
return false;
}
diff --git a/plugins/src/main/java/org/tron/plugins/DbArchive.java b/plugins/src/main/java/x86/org/tron/plugins/DbArchive.java
similarity index 98%
rename from plugins/src/main/java/org/tron/plugins/DbArchive.java
rename to plugins/src/main/java/x86/org/tron/plugins/DbArchive.java
index e3032731ede..15bb281babf 100644
--- a/plugins/src/main/java/org/tron/plugins/DbArchive.java
+++ b/plugins/src/main/java/x86/org/tron/plugins/DbArchive.java
@@ -19,6 +19,7 @@
import org.iq80.leveldb.DB;
import org.iq80.leveldb.Options;
import org.iq80.leveldb.impl.Filename;
+import org.tron.plugins.utils.DBUtils;
import org.tron.plugins.utils.FileUtils;
import picocli.CommandLine;
import picocli.CommandLine.Option;
@@ -163,7 +164,7 @@ public boolean checkManifest(String dir) throws IOException {
return false;
}
logger.info("CurrentName {}/{},size {} kb.", dir, currentName, current.length() / 1024);
- if ("market_pair_price_to_order".equalsIgnoreCase(this.name)) {
+ if (DBUtils.MARKET_PAIR_PRICE_TO_ORDER.equalsIgnoreCase(this.name)) {
logger.info("Db {} ignored.", this.name);
return false;
}
diff --git a/plugins/src/test/java/org/tron/plugins/DbCopyTest.java b/plugins/src/test/java/org/tron/plugins/DbCopyTest.java
index 9e488a592aa..7548812b799 100644
--- a/plugins/src/test/java/org/tron/plugins/DbCopyTest.java
+++ b/plugins/src/test/java/org/tron/plugins/DbCopyTest.java
@@ -4,12 +4,23 @@
import java.util.UUID;
import org.junit.Assert;
import org.junit.Test;
+import org.rocksdb.RocksDBException;
+import org.tron.plugins.utils.db.DbTool;
import picocli.CommandLine;
public class DbCopyTest extends DbTest {
@Test
- public void testRun() {
+ public void testRunForLevelDB() throws RocksDBException, IOException {
+ init(DbTool.DbType.LevelDB);
+ String[] args = new String[] { "db", "cp", INPUT_DIRECTORY,
+ genarateTmpDir()};
+ Assert.assertEquals(0, cli.execute(args));
+ }
+
+ @Test
+ public void testRunForRocksDB() throws RocksDBException, IOException {
+ init(DbTool.DbType.RocksDB);
String[] args = new String[] { "db", "cp", INPUT_DIRECTORY,
genarateTmpDir()};
Assert.assertEquals(0, cli.execute(args));
diff --git a/plugins/src/test/java/org/tron/plugins/DbLiteTest.java b/plugins/src/test/java/org/tron/plugins/DbLiteTest.java
index b4c66c9820f..b0c7f3b96be 100644
--- a/plugins/src/test/java/org/tron/plugins/DbLiteTest.java
+++ b/plugins/src/test/java/org/tron/plugins/DbLiteTest.java
@@ -67,9 +67,10 @@ public void shutdown() throws InterruptedException {
context.close();
}
- public void init() throws IOException {
+ public void init(String dbType) throws IOException {
dbPath = folder.newFolder().toString();
- Args.setParam(new String[]{"-d", dbPath, "-w", "--p2p-disable", "true"},
+ Args.setParam(new String[]{
+ "-d", dbPath, "-w", "--p2p-disable", "true", "--storage-db-engine", dbType},
"config-localtest.conf");
// allow account root
Args.getInstance().setAllowAccountStateRoot(1);
@@ -85,11 +86,11 @@ public void clear() {
Args.clearParam();
}
- void testTools(String dbType, int checkpointVersion)
+ public void testTools(String dbType, int checkpointVersion)
throws InterruptedException, IOException {
logger.info("dbType {}, checkpointVersion {}", dbType, checkpointVersion);
dbPath = String.format("%s_%s_%d", dbPath, dbType, System.currentTimeMillis());
- init();
+ init(dbType);
final String[] argsForSnapshot =
new String[]{"-o", "split", "-t", "snapshot", "--fn-data-path",
dbPath + File.separator + databaseDir, "--dataset-path",
@@ -101,7 +102,6 @@ void testTools(String dbType, int checkpointVersion)
final String[] argsForMerge =
new String[]{"-o", "merge", "--fn-data-path", dbPath + File.separator + databaseDir,
"--dataset-path", dbPath + File.separator + "history"};
- Args.getInstance().getStorage().setDbEngine(dbType);
Args.getInstance().getStorage().setCheckpointVersion(checkpointVersion);
DbLite.setRecentBlks(3);
// start fullNode
diff --git a/plugins/src/test/java/org/tron/plugins/DbMoveTest.java b/plugins/src/test/java/org/tron/plugins/DbMoveTest.java
index c1bc6b470fc..5b25739f272 100644
--- a/plugins/src/test/java/org/tron/plugins/DbMoveTest.java
+++ b/plugins/src/test/java/org/tron/plugins/DbMoveTest.java
@@ -1,52 +1,41 @@
package org.tron.plugins;
-import static org.iq80.leveldb.impl.Iq80DBFactory.factory;
-
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Paths;
-import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
-import org.junit.AfterClass;
+import org.junit.After;
import org.junit.Assert;
-import org.junit.BeforeClass;
+import org.junit.Rule;
import org.junit.Test;
-import org.tron.plugins.utils.FileUtils;
+import org.junit.rules.TemporaryFolder;
+import org.rocksdb.RocksDBException;
+import org.tron.plugins.utils.DBUtils;
+import org.tron.plugins.utils.db.DbTool;
import picocli.CommandLine;
@Slf4j
public class DbMoveTest {
private static final String OUTPUT_DIRECTORY = "output-directory-toolkit";
- private static final String OUTPUT_DIRECTORY_DATABASE =
- Paths.get(OUTPUT_DIRECTORY,"ori","database").toString();
- private static final String ENGINE = "ENGINE";
- private static final String LEVELDB = "LEVELDB";
- private static final String ACCOUNT = "account";
- private static final String TRANS = "trans";
- private static final String MARKET = "market_pair_price_to_order";
- private static final String ENGINE_FILE = "engine.properties";
+ @Rule
+ public TemporaryFolder temporaryFolder = new TemporaryFolder();
- @BeforeClass
- public static void init() throws IOException {
- File file = new File(OUTPUT_DIRECTORY_DATABASE, ACCOUNT);
- factory.open(file, ArchiveManifest.newDefaultLevelDbOptions()).close();
- FileUtils.writeProperty(file + File.separator + ENGINE_FILE, ENGINE, LEVELDB);
+ private static final String ACCOUNT = "account";
+ private static final String TRANS = "trans";
- file = new File(OUTPUT_DIRECTORY_DATABASE, MARKET);
- factory.open(file, ArchiveManifest.newDefaultLevelDbOptions()).close();
- FileUtils.writeProperty(file + File.separator + ENGINE_FILE, ENGINE, LEVELDB);
- file = new File(OUTPUT_DIRECTORY_DATABASE, TRANS);
- factory.open(file, ArchiveManifest.newDefaultLevelDbOptions()).close();
- FileUtils.writeProperty(file + File.separator + ENGINE_FILE, ENGINE, LEVELDB);
+ private void init(DbTool.DbType dbType, String path) throws IOException, RocksDBException {
+ DbTool.getDB(path, ACCOUNT, dbType).close();
+ DbTool.getDB(path, DBUtils.MARKET_PAIR_PRICE_TO_ORDER, dbType).close();
+ DbTool.getDB(path, TRANS, dbType).close();
}
- @AfterClass
- public static void destroy() {
+ @After
+ public void destroy() {
deleteDir(new File(OUTPUT_DIRECTORY));
}
@@ -74,9 +63,23 @@ private static String getConfig(String config) {
}
@Test
- public void testMv() {
+ public void testMvForLevelDB() throws RocksDBException, IOException {
+ File database = temporaryFolder.newFolder("database");
+ init(DbTool.DbType.LevelDB, Paths.get(database.getPath()).toString());
+ String[] args = new String[] {"db", "mv", "-d",
+ database.getParent(), "-c",
+ getConfig("config.conf")};
+ CommandLine cli = new CommandLine(new Toolkit());
+ Assert.assertEquals(0, cli.execute(args));
+ Assert.assertEquals(2, cli.execute(args));
+ }
+
+ @Test
+ public void testMvForRocksDB() throws RocksDBException, IOException {
+ File database = temporaryFolder.newFolder("database");
+ init(DbTool.DbType.RocksDB, Paths.get(database.getPath()).toString());
String[] args = new String[] {"db", "mv", "-d",
- Paths.get(OUTPUT_DIRECTORY,"ori").toString(), "-c",
+ database.getParent(), "-c",
getConfig("config.conf")};
CommandLine cli = new CommandLine(new Toolkit());
Assert.assertEquals(0, cli.execute(args));
@@ -84,9 +87,10 @@ public void testMv() {
}
@Test
- public void testDuplicate() {
+ public void testDuplicate() throws IOException {
+ File output = temporaryFolder.newFolder();
String[] args = new String[] {"db", "mv", "-d",
- Paths.get(OUTPUT_DIRECTORY,"ori").toString(), "-c",
+ output.getPath(), "-c",
getConfig("config-duplicate.conf")};
CommandLine cli = new CommandLine(new Toolkit());
Assert.assertEquals(2, cli.execute(args));
@@ -107,20 +111,19 @@ public void testDicNotExist() {
}
@Test
- public void testConfNotExist() {
+ public void testConfNotExist() throws IOException {
+ File output = temporaryFolder.newFolder();
String[] args = new String[] {"db", "mv", "-d",
- Paths.get(OUTPUT_DIRECTORY,"ori").toString(), "-c",
+ output.getPath(), "-c",
"config.conf"};
CommandLine cli = new CommandLine(new Toolkit());
Assert.assertEquals(2, cli.execute(args));
}
@Test
- public void testEmpty() {
- File file = new File(OUTPUT_DIRECTORY_DATABASE + File.separator + UUID.randomUUID());
- file.mkdirs();
- file.deleteOnExit();
- String[] args = new String[] {"db", "mv", "-d", file.toString(), "-c",
+ public void testEmpty() throws IOException {
+ File output = temporaryFolder.newFolder();
+ String[] args = new String[] {"db", "mv", "-d", output.getPath(), "-c",
getConfig("config.conf")};
CommandLine cli = new CommandLine(new Toolkit());
diff --git a/plugins/src/test/java/org/tron/plugins/DbRootTest.java b/plugins/src/test/java/org/tron/plugins/DbRootTest.java
index b86688f77d5..9d032a43103 100644
--- a/plugins/src/test/java/org/tron/plugins/DbRootTest.java
+++ b/plugins/src/test/java/org/tron/plugins/DbRootTest.java
@@ -9,10 +9,8 @@
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.rocksdb.RocksDBException;
-import org.tron.plugins.utils.DBUtils;
import org.tron.plugins.utils.db.DBInterface;
import org.tron.plugins.utils.db.DbTool;
-import org.tron.plugins.utils.db.LevelDBImpl;
import picocli.CommandLine;
@Slf4j
@@ -27,8 +25,18 @@ public class DbRootTest {
private static final String EMPTY_DB = "empty";
private static final String ERROR_DB = "error";
+
+ @Test
+ public void testRootForLevelDB() throws RocksDBException, IOException {
+ testRoot(DbTool.DbType.LevelDB);
+ }
+
@Test
- public void testRoot() throws IOException, RocksDBException {
+ public void testRootForRocksDB() throws RocksDBException, IOException {
+ testRoot(DbTool.DbType.RocksDB);
+ }
+
+ public void testRoot(DbTool.DbType dbType) throws IOException, RocksDBException {
File file = folder.newFolder();
@@ -36,8 +44,8 @@ public void testRoot() throws IOException, RocksDBException {
Assert.assertTrue(database.mkdirs());
- try (DBInterface normal = DbTool.getDB(database.toString(), NORMAL_DB, DbTool.DbType.LevelDB);
- DBInterface empty = DbTool.getDB(database.toString(), EMPTY_DB, DbTool.DbType.RocksDB)) {
+ try (DBInterface normal = DbTool.getDB(database.toString(), NORMAL_DB, dbType);
+ DBInterface empty = DbTool.getDB(database.toString(), EMPTY_DB, dbType)) {
for (int i = 0; i < 10; i++) {
normal.put(("" + i).getBytes(), (NORMAL_DB + "-" + i).getBytes());
}
@@ -53,8 +61,7 @@ public void testRoot() throws IOException, RocksDBException {
"--db", EMPTY_DB};
Assert.assertEquals(0, cli.execute(args));
- try (DBInterface errorDb = new LevelDBImpl(
- DBUtils.newLevelDb(Paths.get(database.toString(), ERROR_DB)), ERROR_DB)) {
+ try (DBInterface errorDb = DbTool.getDB(database.toString(), ERROR_DB, dbType)) {
for (int i = 0; i < 10; i++) {
errorDb.put(("" + i).getBytes(), (ERROR_DB + "-" + i).getBytes());
}
diff --git a/plugins/src/test/java/org/tron/plugins/DbTest.java b/plugins/src/test/java/org/tron/plugins/DbTest.java
index 8605fa18d50..9337723e8ff 100644
--- a/plugins/src/test/java/org/tron/plugins/DbTest.java
+++ b/plugins/src/test/java/org/tron/plugins/DbTest.java
@@ -5,42 +5,43 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.UUID;
-import org.iq80.leveldb.DB;
-import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
+import org.rocksdb.RocksDBException;
import org.tron.plugins.utils.ByteArray;
import org.tron.plugins.utils.DBUtils;
import org.tron.plugins.utils.MarketUtils;
+import org.tron.plugins.utils.db.DBInterface;
+import org.tron.plugins.utils.db.DbTool;
import picocli.CommandLine;
public class DbTest {
- String INPUT_DIRECTORY;
+ public String INPUT_DIRECTORY;
private static final String ACCOUNT = "account";
private static final String MARKET = DBUtils.MARKET_PAIR_PRICE_TO_ORDER;
- CommandLine cli = new CommandLine(new Toolkit());
+ public CommandLine cli = new CommandLine(new Toolkit());
String tmpDir = System.getProperty("java.io.tmpdir");
@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
- @Before
- public void init() throws IOException {
+ public void init(DbTool.DbType dbType) throws IOException, RocksDBException {
INPUT_DIRECTORY = temporaryFolder.newFolder().toString();
- initDB(new File(INPUT_DIRECTORY, ACCOUNT));
- initDB(new File(INPUT_DIRECTORY, MARKET));
- initDB(new File(INPUT_DIRECTORY, DBUtils.CHECKPOINT_DB_V2));
+ initDB(INPUT_DIRECTORY, ACCOUNT, dbType);
+ initDB(INPUT_DIRECTORY, MARKET, dbType);
+ initDB(INPUT_DIRECTORY, DBUtils.CHECKPOINT_DB_V2, dbType);
}
- private static void initDB(File file) throws IOException {
- if (DBUtils.CHECKPOINT_DB_V2.equalsIgnoreCase(file.getName())) {
- File dbFile = new File(file, DBUtils.CHECKPOINT_DB_V2);
+ private static void initDB(String sourceDir, String dbName, DbTool.DbType dbType)
+ throws IOException, RocksDBException {
+ if (DBUtils.CHECKPOINT_DB_V2.equalsIgnoreCase(dbName)) {
+ File dbFile = new File(sourceDir, DBUtils.CHECKPOINT_DB_V2);
if (dbFile.mkdirs()) {
for (int i = 0; i < 3; i++) {
- try (DB db = DBUtils.newLevelDb(Paths.get(dbFile.getPath(),
- System.currentTimeMillis() + ""))) {
+ try (DBInterface db = DbTool.getDB(dbFile.getPath(),
+ System.currentTimeMillis() + "", dbType)) {
for (int j = 0; j < 100; j++) {
byte[] bytes = UUID.randomUUID().toString().getBytes();
db.put(bytes, bytes);
@@ -50,8 +51,8 @@ private static void initDB(File file) throws IOException {
}
return;
}
- try (DB db = DBUtils.newLevelDb(file.toPath())) {
- if (MARKET.equalsIgnoreCase(file.getName())) {
+ try (DBInterface db = DbTool.getDB(sourceDir, dbName, dbType)) {
+ if (MARKET.equalsIgnoreCase(dbName)) {
byte[] sellTokenID1 = ByteArray.fromString("100");
byte[] buyTokenID1 = ByteArray.fromString("200");
byte[] pairPriceKey1 = MarketUtils.createPairPriceKey(
diff --git a/plugins/src/test/java/org/tron/plugins/ArchiveManifestTest.java b/plugins/src/test/java/org/tron/plugins/leveldb/ArchiveManifestTest.java
similarity index 69%
rename from plugins/src/test/java/org/tron/plugins/ArchiveManifestTest.java
rename to plugins/src/test/java/org/tron/plugins/leveldb/ArchiveManifestTest.java
index 4fd9e537d05..f5880d82e39 100644
--- a/plugins/src/test/java/org/tron/plugins/ArchiveManifestTest.java
+++ b/plugins/src/test/java/org/tron/plugins/leveldb/ArchiveManifestTest.java
@@ -1,6 +1,4 @@
-package org.tron.plugins;
-
-import static org.iq80.leveldb.impl.Iq80DBFactory.factory;
+package org.tron.plugins.leveldb;
import java.io.BufferedReader;
import java.io.BufferedWriter;
@@ -14,47 +12,41 @@
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.UUID;
-
import lombok.extern.slf4j.Slf4j;
-import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
+import org.junit.ClassRule;
import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.rocksdb.RocksDBException;
+import org.tron.plugins.ArchiveManifest;
+import org.tron.plugins.utils.DBUtils;
+import org.tron.plugins.utils.db.DbTool;
@Slf4j
public class ArchiveManifestTest {
- private static final String OUTPUT_DIRECTORY = "output-directory/database/archiveManifest";
+ @ClassRule
+ public static final TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ private static String OUTPUT_DIRECTORY;
- private static final String ENGINE = "ENGINE";
- private static final String LEVELDB = "LEVELDB";
- private static final String ROCKSDB = "ROCKSDB";
private static final String ACCOUNT = "account";
private static final String ACCOUNT_ROCKSDB = "account-rocksdb";
- private static final String MARKET = "market_pair_price_to_order";
- private static final String ENGINE_FILE = "engine.properties";
-
@BeforeClass
- public static void init() throws IOException {
- File file = new File(OUTPUT_DIRECTORY,ACCOUNT);
- factory.open(file,ArchiveManifest.newDefaultLevelDbOptions()).close();
- writeProperty(file.toString() + File.separator + ENGINE_FILE,ENGINE,LEVELDB);
-
- file = new File(OUTPUT_DIRECTORY,MARKET);
- factory.open(file,ArchiveManifest.newDefaultLevelDbOptions()).close();
- writeProperty(file.toString() + File.separator + ENGINE_FILE,ENGINE,LEVELDB);
+ public static void init() throws IOException, RocksDBException {
+ OUTPUT_DIRECTORY = temporaryFolder.newFolder("database").toString();
+ File file = new File(OUTPUT_DIRECTORY, ACCOUNT);
+ DbTool.openLevelDb(file.toPath(),ACCOUNT).close();
- file = new File(OUTPUT_DIRECTORY,ACCOUNT_ROCKSDB);
- factory.open(file,ArchiveManifest.newDefaultLevelDbOptions()).close();
- writeProperty(file.toString() + File.separator + ENGINE_FILE,ENGINE,ROCKSDB);
+ file = new File(OUTPUT_DIRECTORY, DBUtils.MARKET_PAIR_PRICE_TO_ORDER);
+ DbTool.openLevelDb(file.toPath(), DBUtils.MARKET_PAIR_PRICE_TO_ORDER).close();
- }
+ file = new File(OUTPUT_DIRECTORY, ACCOUNT_ROCKSDB);
+ DbTool.openRocksDb(file.toPath(), ACCOUNT_ROCKSDB).close();
- @AfterClass
- public static void destroy() {
- deleteDir(new File(OUTPUT_DIRECTORY));
}
@Test
diff --git a/plugins/src/test/java/org/tron/plugins/DbArchiveTest.java b/plugins/src/test/java/org/tron/plugins/leveldb/DbArchiveTest.java
similarity index 71%
rename from plugins/src/test/java/org/tron/plugins/DbArchiveTest.java
rename to plugins/src/test/java/org/tron/plugins/leveldb/DbArchiveTest.java
index 10bed418764..69dca01e4f8 100644
--- a/plugins/src/test/java/org/tron/plugins/DbArchiveTest.java
+++ b/plugins/src/test/java/org/tron/plugins/leveldb/DbArchiveTest.java
@@ -1,6 +1,4 @@
-package org.tron.plugins;
-
-import static org.iq80.leveldb.impl.Iq80DBFactory.factory;
+package org.tron.plugins.leveldb;
import java.io.BufferedReader;
import java.io.BufferedWriter;
@@ -12,48 +10,43 @@
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
-import java.nio.file.Paths;
import java.util.Properties;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
-import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
+import org.junit.ClassRule;
import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.rocksdb.RocksDBException;
+import org.tron.plugins.Toolkit;
+import org.tron.plugins.utils.DBUtils;
+import org.tron.plugins.utils.db.DbTool;
import picocli.CommandLine;
@Slf4j
public class DbArchiveTest {
- private static final String OUTPUT_DIRECTORY = "output-directory/database/dbArchive";
+ @ClassRule
+ public static final TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ private static String OUTPUT_DIRECTORY;
- private static final String ENGINE = "ENGINE";
- private static final String LEVELDB = "LEVELDB";
- private static final String ROCKSDB = "ROCKSDB";
private static final String ACCOUNT = "account";
private static final String ACCOUNT_ROCKSDB = "account-rocksdb";
- private static final String MARKET = "market_pair_price_to_order";
- private static final String ENGINE_FILE = "engine.properties";
@BeforeClass
- public static void init() throws IOException {
- File file = new File(OUTPUT_DIRECTORY,ACCOUNT);
- factory.open(file,ArchiveManifest.newDefaultLevelDbOptions()).close();
- writeProperty(file.toString() + File.separator + ENGINE_FILE,ENGINE,LEVELDB);
+ public static void init() throws IOException, RocksDBException {
+ OUTPUT_DIRECTORY = temporaryFolder.newFolder("database").toString();
+ File file = new File(OUTPUT_DIRECTORY, ACCOUNT);
+ DbTool.openLevelDb(file.toPath(),ACCOUNT).close();
- file = new File(OUTPUT_DIRECTORY,MARKET);
- factory.open(file,ArchiveManifest.newDefaultLevelDbOptions()).close();
- writeProperty(file.toString() + File.separator + ENGINE_FILE,ENGINE,LEVELDB);
+ file = new File(OUTPUT_DIRECTORY, DBUtils.MARKET_PAIR_PRICE_TO_ORDER);
+ DbTool.openLevelDb(file.toPath(), DBUtils.MARKET_PAIR_PRICE_TO_ORDER).close();
- file = new File(OUTPUT_DIRECTORY,ACCOUNT_ROCKSDB);
- factory.open(file,ArchiveManifest.newDefaultLevelDbOptions()).close();
- writeProperty(file.toString() + File.separator + ENGINE_FILE,ENGINE,ROCKSDB);
-
- }
+ file = new File(OUTPUT_DIRECTORY, ACCOUNT_ROCKSDB);
+ DbTool.openRocksDb(file.toPath(), ACCOUNT_ROCKSDB).close();
- @AfterClass
- public static void destroy() {
- deleteDir(new File(OUTPUT_DIRECTORY));
}
@Test
diff --git a/plugins/src/test/java/org/tron/plugins/DbConvertTest.java b/plugins/src/test/java/org/tron/plugins/leveldb/DbConvertTest.java
similarity index 76%
rename from plugins/src/test/java/org/tron/plugins/DbConvertTest.java
rename to plugins/src/test/java/org/tron/plugins/leveldb/DbConvertTest.java
index 150e47c9f65..d24604f0a0b 100644
--- a/plugins/src/test/java/org/tron/plugins/DbConvertTest.java
+++ b/plugins/src/test/java/org/tron/plugins/leveldb/DbConvertTest.java
@@ -1,27 +1,25 @@
-package org.tron.plugins;
+package org.tron.plugins.leveldb;
import java.io.IOException;
import java.util.UUID;
import org.junit.Assert;
import org.junit.Test;
+import org.rocksdb.RocksDBException;
+import org.tron.plugins.DbTest;
+import org.tron.plugins.Toolkit;
+import org.tron.plugins.utils.db.DbTool;
import picocli.CommandLine;
public class DbConvertTest extends DbTest {
@Test
- public void testRun() throws IOException {
+ public void testRun() throws IOException, RocksDBException {
+ init(DbTool.DbType.LevelDB);
String[] args = new String[] { "db", "convert", INPUT_DIRECTORY,
temporaryFolder.newFolder().toString() };
Assert.assertEquals(0, cli.execute(args));
}
- @Test
- public void testRunWithSafe() throws IOException {
- String[] args = new String[] { "db", "convert", INPUT_DIRECTORY,
- temporaryFolder.newFolder().toString(),"--safe" };
- Assert.assertEquals(0, cli.execute(args));
- }
-
@Test
public void testHelp() {
String[] args = new String[] {"db", "convert", "-h"};
diff --git a/plugins/src/test/java/org/tron/plugins/DbLiteLevelDbTest.java b/plugins/src/test/java/org/tron/plugins/leveldb/DbLiteLevelDbTest.java
similarity index 76%
rename from plugins/src/test/java/org/tron/plugins/DbLiteLevelDbTest.java
rename to plugins/src/test/java/org/tron/plugins/leveldb/DbLiteLevelDbTest.java
index 792f93ad197..7666806e2b5 100644
--- a/plugins/src/test/java/org/tron/plugins/DbLiteLevelDbTest.java
+++ b/plugins/src/test/java/org/tron/plugins/leveldb/DbLiteLevelDbTest.java
@@ -1,7 +1,8 @@
-package org.tron.plugins;
+package org.tron.plugins.leveldb;
import java.io.IOException;
import org.junit.Test;
+import org.tron.plugins.DbLiteTest;
public class DbLiteLevelDbTest extends DbLiteTest {
diff --git a/plugins/src/test/java/org/tron/plugins/DbLiteLevelDbV2Test.java b/plugins/src/test/java/org/tron/plugins/leveldb/DbLiteLevelDbV2Test.java
similarity index 76%
rename from plugins/src/test/java/org/tron/plugins/DbLiteLevelDbV2Test.java
rename to plugins/src/test/java/org/tron/plugins/leveldb/DbLiteLevelDbV2Test.java
index ae48e1d66e9..de32ae29c7c 100644
--- a/plugins/src/test/java/org/tron/plugins/DbLiteLevelDbV2Test.java
+++ b/plugins/src/test/java/org/tron/plugins/leveldb/DbLiteLevelDbV2Test.java
@@ -1,7 +1,8 @@
-package org.tron.plugins;
+package org.tron.plugins.leveldb;
import java.io.IOException;
import org.junit.Test;
+import org.tron.plugins.DbLiteTest;
public class DbLiteLevelDbV2Test extends DbLiteTest {
diff --git a/plugins/src/test/java/org/tron/plugins/DbLiteRocksDbTest.java b/plugins/src/test/java/org/tron/plugins/rocksdb/DbLiteRocksDbTest.java
similarity index 76%
rename from plugins/src/test/java/org/tron/plugins/DbLiteRocksDbTest.java
rename to plugins/src/test/java/org/tron/plugins/rocksdb/DbLiteRocksDbTest.java
index e6910b1103a..2f9c92f9679 100644
--- a/plugins/src/test/java/org/tron/plugins/DbLiteRocksDbTest.java
+++ b/plugins/src/test/java/org/tron/plugins/rocksdb/DbLiteRocksDbTest.java
@@ -1,7 +1,8 @@
-package org.tron.plugins;
+package org.tron.plugins.rocksdb;
import java.io.IOException;
import org.junit.Test;
+import org.tron.plugins.DbLiteTest;
public class DbLiteRocksDbTest extends DbLiteTest {
diff --git a/plugins/src/test/java/org/tron/plugins/rocksdb/DbLiteRocksDbV2Test.java b/plugins/src/test/java/org/tron/plugins/rocksdb/DbLiteRocksDbV2Test.java
new file mode 100644
index 00000000000..ab1067fefc3
--- /dev/null
+++ b/plugins/src/test/java/org/tron/plugins/rocksdb/DbLiteRocksDbV2Test.java
@@ -0,0 +1,13 @@
+package org.tron.plugins.rocksdb;
+
+import java.io.IOException;
+import org.junit.Test;
+import org.tron.plugins.DbLiteTest;
+
+public class DbLiteRocksDbV2Test extends DbLiteTest {
+
+ @Test
+ public void testToolsWithRocksDB() throws InterruptedException, IOException {
+ testTools("ROCKSDB", 2);
+ }
+}
diff --git a/plugins/src/test/resources/config.conf b/plugins/src/test/resources/config.conf
index 2bfca7dbdd7..77d15d521eb 100644
--- a/plugins/src/test/resources/config.conf
+++ b/plugins/src/test/resources/config.conf
@@ -1,11 +1,5 @@
storage {
- # Directory for storing persistent data
- db.engine = "LEVELDB",
- db.sync = false,
- db.directory = "database",
- index.directory = "index",
- transHistory.switch = "on",
properties = [
{
name = "account",
diff --git a/settings.gradle b/settings.gradle
index eb304444378..af32bfca702 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -8,4 +8,5 @@ include 'common'
include 'example:actuator-example'
include 'crypto'
include 'plugins'
+include 'platform'
diff --git a/start.sh.simple b/start.sh.simple
new file mode 100644
index 00000000000..72862d9bdfc
--- /dev/null
+++ b/start.sh.simple
@@ -0,0 +1,195 @@
+#!/bin/bash
+#############################################################################
+#
+# GNU LESSER GENERAL PUBLIC LICENSE
+# Version 3, 29 June 2007
+#
+# Copyright (C) [2007] [TRON Foundation], Inc.
+# Everyone is permitted to copy and distribute verbatim copies
+# of this license document, but changing it is not allowed.
+#
+#
+# This version of the GNU Lesser General Public License incorporates
+# the terms and conditions of version 3 of the GNU General Public
+# License, supplemented by the additional permissions listed below.
+#
+# You can find java-tron at https://github.com/tronprotocol/java-tron/
+#
+##############################################################################
+# TRON Full Node Management Simple Script
+#
+# NOTE: This is a simple and concise script to start and stop the java-tron full node,
+# designed for developers to quickly get started and learn.
+# It may not be suitable for production environments.
+#
+# Usage:
+# sh start.sh # Start the java-tron FullNode
+# sh start.sh -s # Stop the java-tron FullNode
+# sh start.sh [options] # Start with additional java-tron options,such as: -c config.conf -d /path_to_data, etc.
+#
+##############################################################################
+
+
+# adjust JVM start
+# Set the minimum and maximum heap size to 9G, adjust as needed
+VM_XMS="9G"
+# Set the maximum heap size to 9G, adjust as needed
+VM_XMX="9G"
+# Set the maximum direct memory size to 1G, adjust as needed
+VM_MAX_DIRECT_MEMORY_SIZE="1G"
+# adjust JVM end
+
+FULL_NODE_JAR="FullNode.jar"
+FULL_START_OPT=()
+PID=""
+MAX_STOP_TIME=60
+JAVACMD=""
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+NC='\033[0m'
+
+log() {
+ local level="$1"; shift
+ local timestamp color=""
+ timestamp=$(date '+%Y-%m-%d %H:%M:%S')
+ case "$level" in
+ INFO) color="$GREEN" ;;
+ WARN) color="$YELLOW" ;;
+ ERROR) color="$RED" ;;
+ esac
+ printf "%b[%s] [%s]:%b %s\n" "$color" "$timestamp" "$level" "$NC" "$*" | tee -a "${SCRIPT_DIR}/start.log"
+}
+
+info() { log INFO "$@"; }
+warn() { log WARN "$@"; }
+error() { log ERROR "$@"; }
+die() { error "$@"; exit 1; }
+
+ulimit -n 65535 || warn "Failed to set ulimit -n 65535"
+
+findJava() {
+ if [ -n "${JAVA_HOME:-}" ]; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ]; then
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ [ -x "$JAVACMD" ] || die "JAVA_HOME is invalid: $JAVA_HOME"
+ else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "JAVA_HOME not set and no 'java' in PATH"
+ fi
+ "$JAVACMD" -version > /dev/null 2>&1 || die "Java command not working"
+}
+
+checkPid() {
+ # shellcheck disable=SC2009
+ PID=$(ps -ef |grep $FULL_NODE_JAR |grep -v grep |awk '{print $2}')
+}
+
+
+stopService() {
+ checkPid
+
+ if ! kill -0 "$PID" 2>/dev/null; then
+ info "java-tron is not running."
+ return 0
+ fi
+ info "Stopping java-tron service (PID: $PID)"
+
+ local count=1
+
+ while [ -n "$PID" ] && [ $count -le $MAX_STOP_TIME ]; do
+ kill -TERM "$PID" 2>/dev/null && info "Sent SIGTERM to java-tron (PID: $PID), attempt $count"
+ sleep 1
+ checkPid
+ count=$((count + 1))
+ done
+
+ if [ -n "$PID" ]; then
+ warn "Forcing kill java-tron (PID: $PID) after $MAX_STOP_TIME seconds"
+ kill -KILL "$PID" 2>/dev/null
+ sleep 1
+ checkPid
+ fi
+
+ if [ -n "$PID" ]; then
+ die "Failed to stop the service (PID: $PID)"
+ else
+ info "java-tron stopped"
+ wait_with_info 2 "Cleaning up..."
+ fi
+}
+
+startService() {
+ if [ -n "${FULL_START_OPT[*]}" ]; then
+ info "Starting java-tron service with options: ${FULL_START_OPT[*]}"
+ fi
+ if [ ! -f "$FULL_NODE_JAR" ]; then
+ die "$FULL_NODE_JAR not found in path $SCRIPT_DIR."
+ fi
+
+ nohup "$JAVACMD" \
+ -Xms"$VM_XMS" -Xmx"$VM_XMX" -XX:ReservedCodeCacheSize=256m \
+ -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m \
+ -XX:MaxDirectMemorySize="$VM_MAX_DIRECT_MEMORY_SIZE" \
+ -Xloggc:gc.log -XX:+PrintGCDetails \
+ -XX:+UseG1GC \
+ -XX:MaxGCPauseMillis=40 \
+ -XX:InitiatingHeapOccupancyPercent=45 \
+ -XX:+HeapDumpOnOutOfMemoryError \
+ -jar "$FULL_NODE_JAR" "${FULL_START_OPT[@]}" \
+ >> start.log 2>&1 &
+
+
+ info "Waiting for the service to start..."
+ wait_with_info 5 "Starting..."
+
+ checkPid
+
+ if [ -n "$PID" ]; then
+ info "Started java-tron with PID $PID on $HOSTNAME."
+ else
+ die "Failed to start java-tron, see start.log or logs/tron.log for details."
+ fi
+}
+
+wait_with_info() {
+ local seconds=$1
+ local message=$2
+ for i in $(seq "$seconds" -1 1); do
+ info "$message wait ($i) s"
+ sleep 1
+ done
+}
+
+
+start() {
+ checkPid
+ if [ -n "$PID" ]; then
+ info "java-tron is already running (PID: $PID), to stop the service: sh start.sh -s"
+ return
+ fi
+ findJava
+ startService
+}
+
+while [ -n "$1" ]; do
+ case "$1" in
+ -s)
+ stopService
+ exit 0
+ ;;
+ *)
+ FULL_START_OPT+=("$@")
+ break
+ ;;
+ esac
+done
+
+start
+
+exit 0
\ No newline at end of file