",
+ state.getMode(),
+ from,
+ size,
+ node.getIdShort());
}
ReqBlocksHeaders rbh = new ReqBlocksHeaders(from, size);
this.p2p.send(node.getIdHash(), node.getIdShort(), rbh);
diff --git a/modAionImpl/src/org/aion/zero/impl/sync/TaskImportBlocks.java b/modAionImpl/src/org/aion/zero/impl/sync/TaskImportBlocks.java
index bb7577a2d2..3e579f5288 100644
--- a/modAionImpl/src/org/aion/zero/impl/sync/TaskImportBlocks.java
+++ b/modAionImpl/src/org/aion/zero/impl/sync/TaskImportBlocks.java
@@ -29,6 +29,11 @@
package org.aion.zero.impl.sync;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
import org.aion.base.util.ByteArrayWrapper;
import org.aion.mcf.core.ImportResult;
import org.aion.p2p.IP2pMgr;
@@ -36,16 +41,12 @@
import org.aion.zero.impl.types.AionBlock;
import org.slf4j.Logger;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.stream.Collectors;
-
/**
- * @author chris
* handle process of importing blocks to repo
- * TODO: targeted send
+ *
+ * TODO: targeted send
+ *
+ * @author chris
*/
final class TaskImportBlocks implements Runnable {
@@ -73,8 +74,7 @@ final class TaskImportBlocks implements Runnable {
final BlockingQueue downloadedBlocks,
final Map importedBlockHashes,
final Map peerStates,
- final Logger log
- ) {
+ final Logger log) {
this.p2p = p2p;
this.chain = _chain;
this.start = _start;
@@ -99,18 +99,56 @@ public void run() {
List batch = bw.getBlocks().stream()
.filter(b -> importedBlockHashes.get(ByteArrayWrapper.wrap(b.getHash())) == null)
+ .filter(b -> !chain.isPruneRestricted(b.getNumber()))
.collect(Collectors.toList());
PeerState state = peerStates.get(bw.getNodeIdHash());
if (state == null) {
- log.warn("This is not supposed to happen, but the peer is sending us blocks without ask");
+ log.warn(
+ "This is not supposed to happen, but the peer is sending us blocks without ask");
+ }
+
+ ImportResult importResult = ImportResult.IMPORTED_NOT_BEST;
+
+ // importing last block in batch to see if we can skip batch
+ if (state != null && state.getMode() == PeerState.Mode.FORWARD && !batch.isEmpty()) {
+ AionBlock b = batch.get(batch.size() - 1);
+
+ try {
+ importResult = importBlock(b, bw.getDisplayId(), state);
+ } catch (Throwable e) {
+ log.error(" {}", e.toString());
+ if (e.getMessage() != null && e.getMessage().contains("No space left on device")) {
+ log.error("Shutdown due to lack of disk space.");
+ System.exit(0);
+ }
+ continue;
+ }
+
+ switch (importResult) {
+ case IMPORTED_BEST:
+ case IMPORTED_NOT_BEST:
+ case EXIST:
+ {
+ importedBlockHashes.put(ByteArrayWrapper.wrap(b.getHash()), true);
+
+ long lastBlock = batch.get(batch.size() - 1).getNumber();
+
+ forwardModeUpdate(state, lastBlock, importResult, b.getNumber());
+
+ // since last import worked skipping the batch
+ batch.clear();
+ log.info("Forward skip.");
+ break;
+ }
+ default:
+ break;
+ }
}
for (AionBlock b : batch) {
- long t1 = System.currentTimeMillis();
- ImportResult importResult;
try {
- importResult = this.chain.tryToConnect(b);
+ importResult = importBlock(b, bw.getDisplayId(), state);
} catch (Throwable e) {
log.error(" {}", e.toString());
if (e.getMessage() != null && e.getMessage().contains("No space left on device")) {
@@ -119,14 +157,7 @@ public void run() {
}
continue;
}
- long t2 = System.currentTimeMillis();
- log.info("",
- bw.getDisplayId(),
- b.getShortHash(),
- b.getNumber(),
- b.getTransactionsList().size(),
- importResult,
- t2 - t1);
+
switch (importResult) {
case IMPORTED_BEST:
case IMPORTED_NOT_BEST:
@@ -154,14 +185,9 @@ public void run() {
// we found the fork point
state.setMode(PeerState.Mode.FORWARD);
state.setBase(lastBlock);
-
+ state.resetRepeated();
} else if (mode == PeerState.Mode.FORWARD) {
- // continue
- state.setBase(lastBlock);
- // if the imported best block, switch back to normal mode
- if (importResult == ImportResult.IMPORTED_BEST) {
- state.setMode(PeerState.Mode.NORMAL);
- }
+ forwardModeUpdate(state, lastBlock, importResult, b.getNumber());
}
break;
case NO_PARENT:
@@ -176,6 +202,20 @@ public void run() {
break;
}
}
+
+ // if any block results in NO_PARENT, all subsequent blocks will too
+ if (importResult == ImportResult.NO_PARENT) {
+ log.debug("Stopped importing batch due to NO_PARENT result.");
+ break;
+ }
+ }
+
+ if (state != null
+ && state.getMode() == PeerState.Mode.FORWARD
+ && importResult == ImportResult.EXIST) {
+ // increment the repeat count every time
+ // we finish a batch of imports with EXIST
+ state.incRepeated();
}
if (state != null) {
@@ -185,4 +225,46 @@ public void run() {
this.statis.update(this.chain.getBestBlock().getNumber());
}
}
+
+ private ImportResult importBlock(AionBlock b, String displayId, PeerState state) {
+ ImportResult importResult;
+ long t1 = System.currentTimeMillis();
+ importResult = this.chain.tryToConnect(b);
+ long t2 = System.currentTimeMillis();
+ log.info(
+ "",
+ displayId,
+ (state != null ? state.getMode() : PeerState.Mode.NORMAL),
+ b.getShortHash(),
+ b.getNumber(),
+ b.getTransactionsList().size(),
+ importResult,
+ t2 - t1);
+ return importResult;
+ }
+
+ private void forwardModeUpdate(PeerState state, long lastBlock, ImportResult importResult, long blockNumber) {
+ // continue
+ state.setBase(lastBlock);
+ // if the imported best block, switch back to normal mode
+ if (importResult == ImportResult.IMPORTED_BEST) {
+ state.setMode(PeerState.Mode.NORMAL);
+ // switch peers to NORMAL otherwise they may never switch back
+ for (PeerState peerState : peerStates.values()) {
+ if (peerState.getMode() != PeerState.Mode.NORMAL) {
+ peerState.setMode(PeerState.Mode.NORMAL);
+ peerState.setBase(blockNumber);
+ peerState.resetLastHeaderRequest();
+ }
+ }
+ }
+ // if the maximum number of repeats is passed
+ // then the peer is stuck endlessly importing old blocks
+ // otherwise it would have found an IMPORTED block already
+ if (state.getRepeated() >= state.getMaxRepeats()) {
+ state.setMode(PeerState.Mode.NORMAL);
+ state.setBase(chain.getBestBlock().getNumber());
+ state.resetLastHeaderRequest();
+ }
+ }
}
diff --git a/modAionImpl/src/org/aion/zero/impl/sync/TaskShowStatus.java b/modAionImpl/src/org/aion/zero/impl/sync/TaskShowStatus.java
index 01aae5e311..ea62e0b755 100644
--- a/modAionImpl/src/org/aion/zero/impl/sync/TaskShowStatus.java
+++ b/modAionImpl/src/org/aion/zero/impl/sync/TaskShowStatus.java
@@ -1,42 +1,35 @@
/*
* Copyright (c) 2017-2018 Aion foundation.
*
- * This file is part of the aion network project.
+ * This file is part of the aion network project.
*
- * The aion network project 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 any later version.
+ * The aion network project 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 any later version.
*
- * The aion network project 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.
+ * The aion network project 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 the aion network project source files.
- * If not, see .
+ * You should have received a copy of the GNU General Public License
+ * along with the aion network project source files.
+ * If not, see .
*
- * The aion network project leverages useful source code from other
- * open source projects. We greatly appreciate the effort that was
- * invested in these projects and we thank the individual contributors
- * for their work. For provenance information and contributors
- * please see .
- *
- * Contributors to the aion source files in decreasing order of code volume:
- * Aion foundation.
+ * Contributors:
+ * Aion foundation.
*/
package org.aion.zero.impl.sync;
-import org.aion.base.util.Hex;
-import org.aion.zero.impl.AionBlockchainImpl;
-import org.aion.zero.impl.types.AionBlock;
-import org.slf4j.Logger;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicBoolean;
+import org.aion.base.util.Hex;
+import org.aion.zero.impl.AionBlockchainImpl;
+import org.aion.zero.impl.types.AionBlock;
+import org.slf4j.Logger;
/**
* The thread print out sync status
@@ -55,22 +48,22 @@ final class TaskShowStatus implements Runnable {
private final SyncStatics statics;
- private final Logger log;
-
private final boolean printReport;
private final String reportFolder;
+ private final Logger p2pLOG;
+
TaskShowStatus(final AtomicBoolean _start, int _interval, final AionBlockchainImpl _chain,
- final NetworkStatus _networkStatus, final SyncStatics _statics, final Logger _log,
- final boolean _printReport, final String _reportFolder) {
+ final NetworkStatus _networkStatus, final SyncStatics _statics,
+ final boolean _printReport, final String _reportFolder, final Logger _log) {
this.start = _start;
this.interval = _interval;
this.chain = _chain;
this.networkStatus = _networkStatus;
this.statics = _statics;
- this.log = _log;
this.printReport = _printReport;
this.reportFolder = _reportFolder;
+ this.p2pLOG = _log;
}
@Override
@@ -78,24 +71,26 @@ public void run() {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while (this.start.get()) {
AionBlock selfBest = this.chain.getBestBlock();
- String selfTd = this.chain.getTotalDifficulty().toString(10);
+ String selfTd = selfBest.getCumulativeDifficulty().toString(10);
- String status = "";
+ + "/" + this.networkStatus.getTargetBestBlockHash() + "";
- // print to std output
- // thread to dump sync status enabled by sync mgr
- System.out.println(status);
+ p2pLOG.info(status);
// print to report file
if (printReport) {
try {
- Files.write(Paths.get(reportFolder, System.currentTimeMillis() + "-sync-report.out"),
- status.getBytes());
+ Files.write(
+ Paths.get(reportFolder, System.currentTimeMillis() + "-sync-report.out"),
+ status.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
@@ -104,10 +99,14 @@ public void run() {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
- if (log.isDebugEnabled()) { log.debug(""); }
+ if (p2pLOG.isDebugEnabled()) {
+ p2pLOG.debug("sync-ss shutdown");
+ }
return;
}
}
- if (log.isDebugEnabled()) { log.debug(""); }
+ if (p2pLOG.isDebugEnabled()) {
+ p2pLOG.debug("sync-ss shutdown");
+ }
}
}
diff --git a/modAionImpl/src/org/aion/zero/impl/sync/handler/BlockPropagationHandler.java b/modAionImpl/src/org/aion/zero/impl/sync/handler/BlockPropagationHandler.java
index 28f4e88ac4..dc169ce941 100644
--- a/modAionImpl/src/org/aion/zero/impl/sync/handler/BlockPropagationHandler.java
+++ b/modAionImpl/src/org/aion/zero/impl/sync/handler/BlockPropagationHandler.java
@@ -1,38 +1,37 @@
/*
* Copyright (c) 2017-2018 Aion foundation.
*
- * This file is part of the aion network project.
+ * This file is part of the aion network project.
*
- * The aion network project 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 any later version.
+ * The aion network project 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 any later version.
*
- * The aion network project 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.
+ * The aion network project 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 the aion network project source files.
- * If not, see .
+ * You should have received a copy of the GNU General Public License
+ * along with the aion network project source files.
+ * If not, see .
*
- * The aion network project leverages useful source code from other
- * open source projects. We greatly appreciate the effort that was
- * invested in these projects and we thank the individual contributors
- * for their work. For provenance information and contributors
- * please see .
+ * The aion network project leverages useful source code from other
+ * open source projects. We greatly appreciate the effort that was
+ * invested in these projects and we thank the individual contributors
+ * for their work. For provenance information and contributors
+ * please see .
*
* Contributors to the aion source files in decreasing order of code volume:
- * Aion foundation.
- * team through the ethereumJ library.
- * Ether.Camp Inc. (US) team through Ethereum Harmony.
- * John Tromp through the Equihash solver.
- * Samuel Neves through the BLAKE2 implementation.
- * Zcash project team.
- * Bitcoinj team.
+ * Aion foundation.
+ * team through the ethereumJ library.
+ * Ether.Camp Inc. (US) team through Ethereum Harmony.
+ * John Tromp through the Equihash solver.
+ * Samuel Neves through the BLAKE2 implementation.
+ * Zcash project team.
+ * Bitcoinj team.
*/
-
package org.aion.zero.impl.sync.handler;
import org.aion.base.util.ByteArrayWrapper;
@@ -181,12 +180,13 @@ public PropStatus processIncomingBlock(final int nodeId, final String _displayId
}
// notify higher td peers in order to limit the rebroadcast on delay of res status updating
- if(result.isBest()){
- BigInteger td = blockchain.getTotalDifficulty();
+ if (result.isBest()) {
+ AionBlock bestBlock = blockchain.getBestBlock();
+ BigInteger td = bestBlock.getCumulativeDifficulty();
ResStatus rs = new ResStatus(
- blockchain.getBestBlock().getNumber(),
+ bestBlock.getNumber(),
td.toByteArray(),
- blockchain.getBestBlockHash(),
+ bestBlock.getHash(),
genesis
);
diff --git a/modAionImpl/src/org/aion/zero/impl/sync/handler/BroadcastTxHandler.java b/modAionImpl/src/org/aion/zero/impl/sync/handler/BroadcastTxHandler.java
index 5675ef8bf3..6507fe8708 100644
--- a/modAionImpl/src/org/aion/zero/impl/sync/handler/BroadcastTxHandler.java
+++ b/modAionImpl/src/org/aion/zero/impl/sync/handler/BroadcastTxHandler.java
@@ -181,7 +181,7 @@ private List castRawTx(List broadCastTx) {
@Override
public void shutDown() {
- log.info("BroadcastTxHandler shutdown!");
+ log.info("BroadcastTxHandler shutting down!");
if (ex != null) {
ex.shutdown();
}
diff --git a/modAionImpl/src/org/aion/zero/impl/sync/handler/ReqStatusHandler.java b/modAionImpl/src/org/aion/zero/impl/sync/handler/ReqStatusHandler.java
index 60967a8183..8c1e5b6f55 100644
--- a/modAionImpl/src/org/aion/zero/impl/sync/handler/ReqStatusHandler.java
+++ b/modAionImpl/src/org/aion/zero/impl/sync/handler/ReqStatusHandler.java
@@ -1,38 +1,37 @@
/*
* Copyright (c) 2017-2018 Aion foundation.
*
- * This file is part of the aion network project.
+ * This file is part of the aion network project.
*
- * The aion network project 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 any later version.
+ * The aion network project 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 any later version.
*
- * The aion network project 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.
+ * The aion network project 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 the aion network project source files.
- * If not, see .
+ * You should have received a copy of the GNU General Public License
+ * along with the aion network project source files.
+ * If not, see .
*
- * The aion network project leverages useful source code from other
- * open source projects. We greatly appreciate the effort that was
- * invested in these projects and we thank the individual contributors
- * for their work. For provenance information and contributors
- * please see .
+ * The aion network project leverages useful source code from other
+ * open source projects. We greatly appreciate the effort that was
+ * invested in these projects and we thank the individual contributors
+ * for their work. For provenance information and contributors
+ * please see .
*
* Contributors to the aion source files in decreasing order of code volume:
- * Aion foundation.
- * team through the ethereumJ library.
- * Ether.Camp Inc. (US) team through Ethereum Harmony.
- * John Tromp through the Equihash solver.
- * Samuel Neves through the BLAKE2 implementation.
- * Zcash project team.
- * Bitcoinj team.
+ * Aion foundation.
+ * team through the ethereumJ library.
+ * Ether.Camp Inc. (US) team through Ethereum Harmony.
+ * John Tromp through the Equihash solver.
+ * Samuel Neves through the BLAKE2 implementation.
+ * Zcash project team.
+ * Bitcoinj team.
*/
-
package org.aion.zero.impl.sync.handler;
import org.aion.p2p.Ctrl;
@@ -42,22 +41,23 @@
import org.aion.zero.impl.core.IAionBlockchain;
import org.aion.zero.impl.sync.Act;
import org.aion.zero.impl.sync.msg.ResStatus;
+import org.aion.zero.impl.types.AionBlock;
import org.slf4j.Logger;
/**
* handler for status request from network
- *
+ *
* @author chris
*/
public final class ReqStatusHandler extends Handler {
- private final Logger log;
+ private final Logger log;
- private IAionBlockchain chain;
+ private IAionBlockchain chain;
- private IP2pMgr mgr;
+ private IP2pMgr mgr;
- private byte[] genesisHash;
+ private byte[] genesisHash;
private final int UPDATE_INTERVAL = 500;
@@ -65,25 +65,32 @@ public final class ReqStatusHandler extends Handler {
private volatile long cacheTs = 0;
- public ReqStatusHandler(final Logger _log, final IAionBlockchain _chain, final IP2pMgr _mgr,
- final byte[] _genesisHash) {
- super(Ver.V0, Ctrl.SYNC, Act.REQ_STATUS);
- this.log = _log;
- this.chain = _chain;
- this.mgr = _mgr;
- this.genesisHash = _genesisHash;
- this.cache = new ResStatus(0, new byte[0], new byte[0], _genesisHash);
- }
+ public ReqStatusHandler(
+ final Logger _log,
+ final IAionBlockchain _chain,
+ final IP2pMgr _mgr,
+ final byte[] _genesisHash) {
+ super(Ver.V0, Ctrl.SYNC, Act.REQ_STATUS);
+ this.log = _log;
+ this.chain = _chain;
+ this.mgr = _mgr;
+ this.genesisHash = _genesisHash;
+ this.cache = new ResStatus(0, new byte[0], new byte[0], _genesisHash);
+ }
- @Override
- public void receive(int _nodeIdHashcode, String _displayId, byte[] _msg) {
- long now = System.currentTimeMillis();
+ @Override
+ public void receive(int _nodeIdHashcode, String _displayId, byte[] _msg) {
+ long now = System.currentTimeMillis();
if ((now - cacheTs) > this.UPDATE_INTERVAL) {
synchronized (cache) {
try {
- cache = new ResStatus(this.chain.getBestBlock().getNumber(),
- this.chain.getTotalDifficulty().toByteArray(), this.chain.getBestBlockHash(),
- this.genesisHash);
+ AionBlock bestBlock = chain.getBestBlock();
+ cache =
+ new ResStatus(
+ bestBlock.getNumber(),
+ bestBlock.getCumulativeDifficulty().toByteArray(),
+ bestBlock.getHash(),
+ this.genesisHash);
} catch (Exception e) {
e.printStackTrace();
}
@@ -92,9 +99,7 @@ public void receive(int _nodeIdHashcode, String _displayId, byte[] _msg) {
}
this.mgr.send(_nodeIdHashcode, _displayId, cache);
- this.log.debug("",
- _displayId,
- cache.getBestBlockNumber()
- );
- }
+ this.log.debug(
+ "", _displayId, cache.getBestBlockNumber());
+ }
}
diff --git a/modAionImpl/src/org/aion/zero/impl/types/AionBlock.java b/modAionImpl/src/org/aion/zero/impl/types/AionBlock.java
index 357a75472b..a4ef4a1d60 100644
--- a/modAionImpl/src/org/aion/zero/impl/types/AionBlock.java
+++ b/modAionImpl/src/org/aion/zero/impl/types/AionBlock.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* Copyright (c) 2017-2018 Aion foundation.
*
* This file is part of the aion network project.
@@ -19,9 +19,7 @@
*
* Contributors:
* Aion foundation.
- *
- ******************************************************************************/
-
+ */
package org.aion.zero.impl.types;
import org.aion.base.type.Address;
@@ -59,6 +57,8 @@ public class AionBlock extends AbstractBlock imp
private Trie txsState;
+ private BigInteger td = null;
+
/* Constructors */
private AionBlock() {
}
@@ -228,9 +228,11 @@ public BigInteger getDifficultyBI() {
}
public BigInteger getCumulativeDifficulty() {
- // TODO: currently returning incorrect total difficulty
- parseRLP();
- return new BigInteger(1, this.header.getDifficulty());
+ if (td == null) {
+ return BigInteger.ZERO;
+ } else {
+ return td;
+ }
}
public long getTimestamp() {
@@ -442,4 +444,8 @@ public static AionBlock createBlockFromNetwork(A0BlockHeader header, byte[] body
return block;
}
+
+ public void setCumulativeDifficulty(BigInteger _td){
+ td = _td;
+ }
}
diff --git a/modAionImpl/test/org/aion/db/AionContractDetailsTest.java b/modAionImpl/test/org/aion/db/AionContractDetailsTest.java
index 4222d694fc..5c69f27978 100644
--- a/modAionImpl/test/org/aion/db/AionContractDetailsTest.java
+++ b/modAionImpl/test/org/aion/db/AionContractDetailsTest.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/* ******************************************************************************
* Copyright (c) 2017-2018 Aion foundation.
*
* This file is part of the aion network project.
@@ -34,59 +34,61 @@
******************************************************************************/
package org.aion.db;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
import org.aion.base.db.IByteArrayKeyValueDatabase;
import org.aion.base.db.IContractDetails;
+import org.aion.base.db.IPruneConfig;
import org.aion.base.db.IRepositoryConfig;
import org.aion.base.type.Address;
import org.aion.base.util.ByteUtil;
import org.aion.db.impl.DBVendor;
import org.aion.db.impl.DatabaseFactory;
-import org.aion.db.impl.leveldb.LevelDBConstants;
+import org.aion.mcf.config.CfgPrune;
import org.aion.mcf.vm.types.DataWord;
import org.aion.zero.db.AionContractDetailsImpl;
import org.aion.zero.impl.db.AionRepositoryImpl;
import org.aion.zero.impl.db.ContractDetailsAion;
import org.apache.commons.lang3.RandomUtils;
-import org.junit.Ignore;
import org.junit.Test;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
public class AionContractDetailsTest {
- private static final int IN_MEMORY_STORAGE_LIMIT = 1000000; // CfgAion.inst().getDb().getDetailsInMemoryStorageLimit();
-
- protected IRepositoryConfig repoConfig = new IRepositoryConfig() {
- @Override
- public String getDbPath() {
- return "";
- }
-
- @Override
- public int getPrune() {
- return 0;
- }
-
- @Override
- public IContractDetails contractDetailsImpl() {
- return ContractDetailsAion.createForTesting(0, 1000000).getDetails();
- }
-
- @Override
- public Properties getDatabaseConfig(String db_name) {
- Properties props = new Properties();
- props.setProperty(DatabaseFactory.Props.DB_TYPE, DBVendor.MOCKDB.toValue());
- props.setProperty(DatabaseFactory.Props.ENABLE_HEAP_CACHE, "false");
- return props;
- }
- };
-
- private static IContractDetails deserialize(byte[] rlp, IByteArrayKeyValueDatabase externalStorage) {
+ private static final int IN_MEMORY_STORAGE_LIMIT =
+ 1000000; // CfgAion.inst().getDb().getDetailsInMemoryStorageLimit();
+
+ protected IRepositoryConfig repoConfig =
+ new IRepositoryConfig() {
+ @Override
+ public String getDbPath() {
+ return "";
+ }
+
+ @Override
+ public IPruneConfig getPruneConfig() {
+ return new CfgPrune(false);
+ }
+
+ @Override
+ public IContractDetails contractDetailsImpl() {
+ return ContractDetailsAion.createForTesting(0, 1000000).getDetails();
+ }
+
+ @Override
+ public Properties getDatabaseConfig(String db_name) {
+ Properties props = new Properties();
+ props.setProperty(DatabaseFactory.Props.DB_TYPE, DBVendor.MOCKDB.toValue());
+ props.setProperty(DatabaseFactory.Props.ENABLE_HEAP_CACHE, "false");
+ return props;
+ }
+ };
+
+ private static IContractDetails deserialize(
+ byte[] rlp, IByteArrayKeyValueDatabase externalStorage) {
AionContractDetailsImpl result = new AionContractDetailsImpl();
result.setExternalStorageDataSource(externalStorage);
result.decode(rlp);
@@ -105,10 +107,11 @@ public void test_1() throws Exception {
byte[] key_2 = ByteUtil.hexStringToBytes("222222");
byte[] val_2 = ByteUtil.hexStringToBytes("bbbbbb");
- AionContractDetailsImpl contractDetails = new AionContractDetailsImpl(
- -1, //CfgAion.inst().getDb().getPrune(),
- 1000000 //CfgAion.inst().getDb().getDetailsInMemoryStorageLimit()
- );
+ AionContractDetailsImpl contractDetails =
+ new AionContractDetailsImpl(
+ -1, // CfgAion.inst().getDb().getPrune(),
+ 1000000 // CfgAion.inst().getDb().getDetailsInMemoryStorageLimit()
+ );
contractDetails.setCode(code);
contractDetails.put(new DataWord(key_1), new DataWord(val_1));
contractDetails.put(new DataWord(key_2), new DataWord(val_2));
@@ -117,20 +120,25 @@ public void test_1() throws Exception {
AionContractDetailsImpl contractDetails_ = new AionContractDetailsImpl(data);
- assertEquals(ByteUtil.toHexString(code),
- ByteUtil.toHexString(contractDetails_.getCode()));
+ assertEquals(ByteUtil.toHexString(code), ByteUtil.toHexString(contractDetails_.getCode()));
- assertEquals(ByteUtil.toHexString(val_1),
- ByteUtil.toHexString(contractDetails_.get(new DataWord(key_1)).getNoLeadZeroesData()));
+ assertEquals(
+ ByteUtil.toHexString(val_1),
+ ByteUtil.toHexString(
+ contractDetails_.get(new DataWord(key_1)).getNoLeadZeroesData()));
- assertEquals(ByteUtil.toHexString(val_2),
- ByteUtil.toHexString(contractDetails_.get(new DataWord(key_2)).getNoLeadZeroesData()));
+ assertEquals(
+ ByteUtil.toHexString(val_2),
+ ByteUtil.toHexString(
+ contractDetails_.get(new DataWord(key_2)).getNoLeadZeroesData()));
}
@Test
public void test_2() throws Exception {
- byte[] code = ByteUtil.hexStringToBytes("7c0100000000000000000000000000000000000000000000000000000000600035046333d546748114610065578063430fe5f01461007c5780634d432c1d1461008d578063501385b2146100b857806357eb3b30146100e9578063dbc7df61146100fb57005b6100766004356024356044356102f0565b60006000f35b61008760043561039e565b60006000f35b610098600435610178565b8073ffffffffffffffffffffffffffffffffffffffff1660005260206000f35b6100c96004356024356044356101a0565b8073ffffffffffffffffffffffffffffffffffffffff1660005260206000f35b6100f1610171565b8060005260206000f35b610106600435610133565b8360005282602052816040528073ffffffffffffffffffffffffffffffffffffffff1660605260806000f35b5b60006020819052908152604090208054600182015460028301546003909301549192909173ffffffffffffffffffffffffffffffffffffffff1684565b5b60015481565b5b60026020526000908152604090205473ffffffffffffffffffffffffffffffffffffffff1681565b73ffffffffffffffffffffffffffffffffffffffff831660009081526020819052604081206002015481908302341080156101fe575073ffffffffffffffffffffffffffffffffffffffff8516600090815260208190526040812054145b8015610232575073ffffffffffffffffffffffffffffffffffffffff85166000908152602081905260409020600101548390105b61023b57610243565b3391506102e8565b6101966103ca60003973ffffffffffffffffffffffffffffffffffffffff3381166101965285166101b68190526000908152602081905260408120600201546101d6526101f68490526102169080f073ffffffffffffffffffffffffffffffffffffffff8616600090815260208190526040902060030180547fffffffffffffffffffffffff0000000000000000000000000000000000000000168217905591508190505b509392505050565b73ffffffffffffffffffffffffffffffffffffffff33166000908152602081905260408120548190821461032357610364565b60018054808201909155600090815260026020526040902080547fffffffffffffffffffffffff000000000000000000000000000000000000000016331790555b50503373ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090209081556001810192909255600290910155565b3373ffffffffffffffffffffffffffffffffffffffff166000908152602081905260409020600201555600608061019660043960048051602451604451606451600080547fffffffffffffffffffffffff0000000000000000000000000000000000000000908116909517815560018054909516909317909355600355915561013390819061006390396000f3007c0100000000000000000000000000000000000000000000000000000000600035046347810fe381146100445780637e4a1aa81461005557806383d2421b1461006957005b61004f6004356100ab565b60006000f35b6100636004356024356100fc565b60006000f35b61007460043561007a565b60006000f35b6001543373ffffffffffffffffffffffffffffffffffffffff9081169116146100a2576100a8565b60078190555b50565b73ffffffffffffffffffffffffffffffffffffffff8116600090815260026020526040902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016600117905550565b6001543373ffffffffffffffffffffffffffffffffffffffff9081169116146101245761012f565b600582905560068190555b505056");
+ byte[] code =
+ ByteUtil.hexStringToBytes(
+ "7c0100000000000000000000000000000000000000000000000000000000600035046333d546748114610065578063430fe5f01461007c5780634d432c1d1461008d578063501385b2146100b857806357eb3b30146100e9578063dbc7df61146100fb57005b6100766004356024356044356102f0565b60006000f35b61008760043561039e565b60006000f35b610098600435610178565b8073ffffffffffffffffffffffffffffffffffffffff1660005260206000f35b6100c96004356024356044356101a0565b8073ffffffffffffffffffffffffffffffffffffffff1660005260206000f35b6100f1610171565b8060005260206000f35b610106600435610133565b8360005282602052816040528073ffffffffffffffffffffffffffffffffffffffff1660605260806000f35b5b60006020819052908152604090208054600182015460028301546003909301549192909173ffffffffffffffffffffffffffffffffffffffff1684565b5b60015481565b5b60026020526000908152604090205473ffffffffffffffffffffffffffffffffffffffff1681565b73ffffffffffffffffffffffffffffffffffffffff831660009081526020819052604081206002015481908302341080156101fe575073ffffffffffffffffffffffffffffffffffffffff8516600090815260208190526040812054145b8015610232575073ffffffffffffffffffffffffffffffffffffffff85166000908152602081905260409020600101548390105b61023b57610243565b3391506102e8565b6101966103ca60003973ffffffffffffffffffffffffffffffffffffffff3381166101965285166101b68190526000908152602081905260408120600201546101d6526101f68490526102169080f073ffffffffffffffffffffffffffffffffffffffff8616600090815260208190526040902060030180547fffffffffffffffffffffffff0000000000000000000000000000000000000000168217905591508190505b509392505050565b73ffffffffffffffffffffffffffffffffffffffff33166000908152602081905260408120548190821461032357610364565b60018054808201909155600090815260026020526040902080547fffffffffffffffffffffffff000000000000000000000000000000000000000016331790555b50503373ffffffffffffffffffffffffffffffffffffffff1660009081526020819052604090209081556001810192909255600290910155565b3373ffffffffffffffffffffffffffffffffffffffff166000908152602081905260409020600201555600608061019660043960048051602451604451606451600080547fffffffffffffffffffffffff0000000000000000000000000000000000000000908116909517815560018054909516909317909355600355915561013390819061006390396000f3007c0100000000000000000000000000000000000000000000000000000000600035046347810fe381146100445780637e4a1aa81461005557806383d2421b1461006957005b61004f6004356100ab565b60006000f35b6100636004356024356100fc565b60006000f35b61007460043561007a565b60006000f35b6001543373ffffffffffffffffffffffffffffffffffffffff9081169116146100a2576100a8565b60078190555b50565b73ffffffffffffffffffffffffffffffffffffffff8116600090815260026020526040902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016600117905550565b6001543373ffffffffffffffffffffffffffffffffffffffff9081169116146101245761012f565b600582905560068190555b505056");
Address address = Address.wrap(RandomUtils.nextBytes(Address.ADDRESS_LEN));
byte[] key_0 = ByteUtil.hexStringToBytes("18d63b70aa690ad37cb50908746c9a55");
@@ -197,48 +205,60 @@ public void test_2() throws Exception {
AionContractDetailsImpl contractDetails_ = new AionContractDetailsImpl(data);
- assertEquals(ByteUtil.toHexString(code),
- ByteUtil.toHexString(contractDetails_.getCode()));
+ assertEquals(ByteUtil.toHexString(code), ByteUtil.toHexString(contractDetails_.getCode()));
assertTrue(address.equals(contractDetails_.getAddress()));
- assertEquals(ByteUtil.toHexString(val_1),
+ assertEquals(
+ ByteUtil.toHexString(val_1),
ByteUtil.toHexString(contractDetails_.get(new DataWord(key_1)).getData()));
- assertEquals(ByteUtil.toHexString(val_2),
+ assertEquals(
+ ByteUtil.toHexString(val_2),
ByteUtil.toHexString(contractDetails_.get(new DataWord(key_2)).getData()));
- assertEquals(ByteUtil.toHexString(val_3),
+ assertEquals(
+ ByteUtil.toHexString(val_3),
ByteUtil.toHexString(contractDetails_.get(new DataWord(key_3)).getData()));
- assertEquals(ByteUtil.toHexString(val_4),
+ assertEquals(
+ ByteUtil.toHexString(val_4),
ByteUtil.toHexString(contractDetails_.get(new DataWord(key_4)).getData()));
- assertEquals(ByteUtil.toHexString(val_5),
+ assertEquals(
+ ByteUtil.toHexString(val_5),
ByteUtil.toHexString(contractDetails_.get(new DataWord(key_5)).getData()));
- assertEquals(ByteUtil.toHexString(val_6),
+ assertEquals(
+ ByteUtil.toHexString(val_6),
ByteUtil.toHexString(contractDetails_.get(new DataWord(key_6)).getData()));
- assertEquals(ByteUtil.toHexString(val_7),
+ assertEquals(
+ ByteUtil.toHexString(val_7),
ByteUtil.toHexString(contractDetails_.get(new DataWord(key_7)).getData()));
- assertEquals(ByteUtil.toHexString(val_8),
+ assertEquals(
+ ByteUtil.toHexString(val_8),
ByteUtil.toHexString(contractDetails_.get(new DataWord(key_8)).getData()));
- assertEquals(ByteUtil.toHexString(val_9),
+ assertEquals(
+ ByteUtil.toHexString(val_9),
ByteUtil.toHexString(contractDetails_.get(new DataWord(key_9)).getData()));
- assertEquals(ByteUtil.toHexString(val_10),
+ assertEquals(
+ ByteUtil.toHexString(val_10),
ByteUtil.toHexString(contractDetails_.get(new DataWord(key_10)).getData()));
- assertEquals(ByteUtil.toHexString(val_11),
+ assertEquals(
+ ByteUtil.toHexString(val_11),
ByteUtil.toHexString(contractDetails_.get(new DataWord(key_11)).getData()));
- assertEquals(ByteUtil.toHexString(val_12),
+ assertEquals(
+ ByteUtil.toHexString(val_12),
ByteUtil.toHexString(contractDetails_.get(new DataWord(key_12)).getData()));
- assertEquals(ByteUtil.toHexString(val_13),
+ assertEquals(
+ ByteUtil.toHexString(val_13),
ByteUtil.toHexString(contractDetails_.get(new DataWord(key_13)).getData()));
}
@@ -310,7 +330,6 @@ public void testExternalStorageTransition() {
original.put(key, value);
}
-
original.syncStorage();
assertTrue(!externalStorage.isEmpty());
diff --git a/modAionImpl/test/org/aion/zero/impl/BlockchainDataRecoveryTest.java b/modAionImpl/test/org/aion/zero/impl/BlockchainDataRecoveryTest.java
index 993ba41f6a..86caf7f16c 100644
--- a/modAionImpl/test/org/aion/zero/impl/BlockchainDataRecoveryTest.java
+++ b/modAionImpl/test/org/aion/zero/impl/BlockchainDataRecoveryTest.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* Copyright (c) 2017-2018 Aion foundation.
*
* This file is part of the aion network project.
@@ -17,21 +17,9 @@
* along with the aion network project source files.
* If not, see .
*
- * The aion network project leverages useful source code from other
- * open source projects. We greatly appreciate the effort that was
- * invested in these projects and we thank the individual contributors
- * for their work. For provenance information and contributors
- * please see .
- *
- * Contributors to the aion source files in decreasing order of code volume:
+ * Contributors:
* Aion foundation.
- * team through the ethereumJ library.
- * Ether.Camp Inc. (US) team through Ethereum Harmony.
- * John Tromp through the Equihash solver.
- * Samuel Neves through the BLAKE2 implementation.
- * Zcash project team.
- * Bitcoinj team.
- ******************************************************************************/
+ */
package org.aion.zero.impl;
import org.aion.base.db.IByteArrayKeyValueDatabase;
@@ -98,11 +86,12 @@ public void testRecoverWorldStateWithPartialWorldState() {
AionBlock bestBlock = chain.getBestBlock();
assertThat(bestBlock.getNumber()).isEqualTo(NUMBER_OF_BLOCKS);
- chain.getRepository().flush();
+ AionRepositoryImpl repo = chain.getRepository();
+ repo.flush();
// delete some world state root entries from the database
- TrieImpl trie = (TrieImpl) ((AionRepositoryImpl) chain.getRepository()).getWorldState();
- IByteArrayKeyValueDatabase database = (IByteArrayKeyValueDatabase) trie.getCache().getDb();
+ TrieImpl trie = (TrieImpl) repo.getWorldState();
+ IByteArrayKeyValueDatabase database = repo.getStateDatabase();
for (byte[] key : statesToDelete) {
database.delete(key);
@@ -113,7 +102,7 @@ public void testRecoverWorldStateWithPartialWorldState() {
assertThat(trie.isValidRoot(chain.getBestBlock().getStateRoot())).isFalse();
// call the recovery functionality
- boolean worked = chain.recoverWorldState(chain.getRepository(), bestBlock);
+ boolean worked = chain.recoverWorldState(repo, bestBlock);
// ensure that the blockchain is ok
assertThat(chain.getBestBlockHash()).isEqualTo(bestBlock.getHash());
@@ -148,12 +137,13 @@ public void testRecoverWorldStateWithStartFromGenesis() {
AionBlock bestBlock = chain.getBestBlock();
assertThat(bestBlock.getNumber()).isEqualTo(NUMBER_OF_BLOCKS);
- chain.getRepository().flush();
+ AionRepositoryImpl repo = chain.getRepository();
+ repo.flush();
// System.out.println(Hex.toHexString(chain.getRepository().getRoot()));
// delete some world state root entries from the database
- TrieImpl trie = (TrieImpl) ((AionRepositoryImpl) chain.getRepository()).getWorldState();
- IByteArrayKeyValueDatabase database = (IByteArrayKeyValueDatabase) trie.getCache().getDb();
+ TrieImpl trie = (TrieImpl) repo.getWorldState();
+ IByteArrayKeyValueDatabase database = repo.getStateDatabase();
for (byte[] key : statesToDelete) {
database.delete(key);
@@ -165,7 +155,7 @@ public void testRecoverWorldStateWithStartFromGenesis() {
assertThat(trie.isValidRoot(chain.getBestBlock().getStateRoot())).isFalse();
// call the recovery functionality
- boolean worked = chain.recoverWorldState(chain.getRepository(), bestBlock);
+ boolean worked = chain.recoverWorldState(repo, bestBlock);
// ensure that the blockchain is ok
assertThat(chain.getBestBlockHash()).isEqualTo(bestBlock.getHash());
@@ -200,11 +190,12 @@ public void testRecoverWorldStateWithoutGenesis() {
AionBlock bestBlock = chain.getBestBlock();
assertThat(bestBlock.getNumber()).isEqualTo(NUMBER_OF_BLOCKS);
- chain.getRepository().flush();
+ AionRepositoryImpl repo = chain.getRepository();
+ repo.flush();
// delete some world state root entries from the database
- TrieImpl trie = (TrieImpl) ((AionRepositoryImpl) chain.getRepository()).getWorldState();
- IByteArrayKeyValueDatabase database = (IByteArrayKeyValueDatabase) trie.getCache().getDb();
+ TrieImpl trie = (TrieImpl) repo.getWorldState();
+ IByteArrayKeyValueDatabase database = repo.getStateDatabase();
List statesToDelete = new ArrayList<>();
statesToDelete.addAll(database.keys());
@@ -218,7 +209,7 @@ public void testRecoverWorldStateWithoutGenesis() {
assertThat(trie.isValidRoot(chain.getBestBlock().getStateRoot())).isFalse();
// call the recovery functionality
- boolean worked = chain.recoverWorldState(chain.getRepository(), bestBlock);
+ boolean worked = chain.recoverWorldState(repo, bestBlock);
// ensure that the blockchain is ok
assertThat(chain.getBestBlockHash()).isEqualTo(bestBlock.getHash());
@@ -259,10 +250,10 @@ public void testRecoverIndexWithPartialIndex_MainChain() {
AionBlock bestBlock = chain.getBestBlock();
assertThat(bestBlock.getNumber()).isEqualTo(NUMBER_OF_BLOCKS);
- chain.getRepository().flush();
+ AionRepositoryImpl repo = chain.getRepository();
+ repo.flush();
// delete index entries from the database
- AionRepositoryImpl repo = (AionRepositoryImpl) chain.getRepository();
IByteArrayKeyValueDatabase indexDatabase = repo.getIndexDatabase();
Map deletedInfo = new HashMap<>();
@@ -281,7 +272,7 @@ public void testRecoverIndexWithPartialIndex_MainChain() {
assertThat(repo.isIndexed(bestBlock.getHash(), bestBlock.getNumber())).isFalse();
// call the recovery functionality
- boolean worked = chain.recoverIndexEntry(chain.getRepository(), bestBlock);
+ boolean worked = chain.recoverIndexEntry(repo, bestBlock);
// ensure that the blockchain is ok
assertThat(chain.getBestBlockHash()).isEqualTo(bestBlock.getHash());
@@ -369,10 +360,10 @@ public void testRecoverIndexWithPartialIndex_ShorterSideChain() {
assertThat(bestBlock.getNumber()).isEqualTo(NUMBER_OF_BLOCKS);
assertThat(bestBlock.getHash()).isEqualTo(mainChainBlock.getHash());
- chain.getRepository().flush();
+ AionRepositoryImpl repo = chain.getRepository();
+ repo.flush();
// delete index entries from the database
- AionRepositoryImpl repo = (AionRepositoryImpl) chain.getRepository();
IByteArrayKeyValueDatabase indexDatabase = repo.getIndexDatabase();
Map deletedInfo = new HashMap<>();
@@ -388,8 +379,7 @@ public void testRecoverIndexWithPartialIndex_ShorterSideChain() {
}
// call the recovery functionality for the main chain subsection
- boolean worked = chain
- .recoverIndexEntry(chain.getRepository(), chain.getBlockByHash(mainChainBlock.getParentHash()));
+ boolean worked = chain.recoverIndexEntry(repo, chain.getBlockByHash(mainChainBlock.getParentHash()));
// ensure that the index was corrupted only for the side chain
assertThat(repo.isIndexed(sideChainBlock.getHash(), sideChainBlock.getNumber())).isFalse();
@@ -397,7 +387,7 @@ public void testRecoverIndexWithPartialIndex_ShorterSideChain() {
assertThat(worked).isTrue();
// call the recovery functionality
- worked = chain.recoverIndexEntry(chain.getRepository(), sideChainBlock);
+ worked = chain.recoverIndexEntry(repo, sideChainBlock);
// ensure that the blockchain is ok
assertThat(chain.getBestBlockHash()).isEqualTo(bestBlock.getHash());
@@ -448,10 +438,10 @@ public void testRecoverIndexWithStartFromGenesis() {
AionBlock bestBlock = chain.getBestBlock();
assertThat(bestBlock.getNumber()).isEqualTo(NUMBER_OF_BLOCKS);
- chain.getRepository().flush();
+ AionRepositoryImpl repo = chain.getRepository();
+ repo.flush();
// delete index entries from the database
- AionRepositoryImpl repo = (AionRepositoryImpl) chain.getRepository();
IByteArrayKeyValueDatabase indexDatabase = repo.getIndexDatabase();
Map deletedInfo = new HashMap<>();
@@ -470,7 +460,7 @@ public void testRecoverIndexWithStartFromGenesis() {
assertThat(repo.isIndexed(bestBlock.getHash(), bestBlock.getNumber())).isFalse();
// call the recovery functionality
- boolean worked = chain.recoverIndexEntry(chain.getRepository(), bestBlock);
+ boolean worked = chain.recoverIndexEntry(repo, bestBlock);
// ensure that the blockchain is ok
assertThat(chain.getBestBlockHash()).isEqualTo(bestBlock.getHash());
@@ -519,9 +509,9 @@ public void testRecoverIndexWithoutGenesis() {
AionBlock bestBlock = chain.getBestBlock();
assertThat(bestBlock.getNumber()).isEqualTo(NUMBER_OF_BLOCKS);
- chain.getRepository().flush();
+ AionRepositoryImpl repo = chain.getRepository();
+ repo.flush();
- AionRepositoryImpl repo = (AionRepositoryImpl) chain.getRepository();
IByteArrayKeyValueDatabase indexDatabase = repo.getIndexDatabase();
// deleting the entire index database
@@ -531,7 +521,7 @@ public void testRecoverIndexWithoutGenesis() {
assertThat(repo.isIndexed(bestBlock.getHash(), bestBlock.getNumber())).isFalse();
// call the recovery functionality
- boolean worked = chain.recoverIndexEntry(chain.getRepository(), bestBlock);
+ boolean worked = chain.recoverIndexEntry(repo, bestBlock);
// ensure that the best block is unchanged
assertThat(chain.getBestBlockHash()).isEqualTo(bestBlock.getHash());
@@ -566,10 +556,10 @@ public void testRecoverIndexWithStartFromGenesisWithoutSize() {
AionBlock bestBlock = chain.getBestBlock();
assertThat(bestBlock.getNumber()).isEqualTo(NUMBER_OF_BLOCKS);
- chain.getRepository().flush();
+ AionRepositoryImpl repo = chain.getRepository();
+ repo.flush();
// delete index entries from the database
- AionRepositoryImpl repo = (AionRepositoryImpl) chain.getRepository();
IByteArrayKeyValueDatabase indexDatabase = repo.getIndexDatabase();
Map deletedInfo = new HashMap<>();
@@ -592,7 +582,7 @@ public void testRecoverIndexWithStartFromGenesisWithoutSize() {
assertThat(repo.isIndexed(bestBlock.getHash(), bestBlock.getNumber())).isFalse();
// call the recovery functionality
- boolean worked = chain.recoverIndexEntry(chain.getRepository(), bestBlock);
+ boolean worked = chain.recoverIndexEntry(repo, bestBlock);
// ensure that the blockchain is ok
assertThat(chain.getBestBlockHash()).isEqualTo(bestBlock.getHash());
diff --git a/modAionImpl/test/org/aion/zero/impl/BlockchainForkingTest.java b/modAionImpl/test/org/aion/zero/impl/BlockchainForkingTest.java
index d5e247c35e..0b82a9306b 100644
--- a/modAionImpl/test/org/aion/zero/impl/BlockchainForkingTest.java
+++ b/modAionImpl/test/org/aion/zero/impl/BlockchainForkingTest.java
@@ -39,12 +39,10 @@
import org.aion.crypto.ECKey;
import org.aion.mcf.core.ImportResult;
import org.aion.zero.impl.blockchain.ChainConfiguration;
-import org.aion.zero.impl.db.AionRepositoryImpl;
import org.aion.zero.impl.types.AionBlock;
import org.junit.Test;
import java.math.BigInteger;
-import java.util.Collection;
import java.util.Collections;
import java.util.List;
@@ -136,7 +134,7 @@ public void testInvalidFirstBlockDifficulty() {
higherDifficultyBlock.getHeader().setDifficulty(difficulty.toByteArray());
System.out.println("before any processing: " + new ByteArrayWrapper(bc.getRepository().getRoot()));
- System.out.println("trie: " + ((AionRepositoryImpl) bc.getRepository()).getWorldState().getTrieDump());
+ System.out.println("trie: " + bc.getRepository().getWorldState().getTrieDump());
ImportResult result = bc.tryToConnect(standardBlock);
assertThat(result).isEqualTo(ImportResult.IMPORTED_BEST);
@@ -157,6 +155,12 @@ public void testInvalidFirstBlockDifficulty() {
// the object reference here is intentional
assertThat(bc.getBestBlock() == standardBlock).isTrue();
+
+ // check for correct state rollback
+ assertThat(bc.getRepository().getRoot()).isEqualTo(standardBlock.getStateRoot());
+ assertThat(bc.getTotalDifficulty())
+ .isEqualTo(bc.getRepository().getBlockStore().getTotalDifficultyForHash(standardBlock.getHash()));
+
}
/*-
@@ -226,7 +230,7 @@ public void testSecondBlockHigherDifficultyFork() {
StandaloneBlockchain bc = bundle.bc;
List accs = bundle.privateKeys;
- // generate three blocks, on the third block we get flexiblity
+ // generate three blocks, on the third block we get flexibility
// for what difficulties can occur
BlockContext firstBlock = bc.createNewBlockInternal(
@@ -274,4 +278,96 @@ public void testSecondBlockHigherDifficultyFork() {
assertThat(bc.getBestBlock()).isEqualTo(fastBlockDescendant.block);
}
+
+ /**
+ * Test fork with exception.
+ */
+ @Test
+ public void testSecondBlockHigherDifficultyFork_wExceptionOnFasterBlockAdd() {
+ StandaloneBlockchain.Builder builder = new StandaloneBlockchain.Builder();
+ StandaloneBlockchain.Bundle bundle = builder.withValidatorConfiguration("simple").withDefaultAccounts().build();
+
+ long time = System.currentTimeMillis();
+
+ StandaloneBlockchain bc = bundle.bc;
+
+ // generate three blocks, on the third block we get flexibility
+ // for what difficulties can occur
+
+ BlockContext firstBlock = bc
+ .createNewBlockInternal(bc.getGenesis(), Collections.emptyList(), true, time / 1000L);
+ assertThat(bc.tryToConnectInternal(firstBlock.block, (time += 10))).isEqualTo(ImportResult.IMPORTED_BEST);
+
+ // now connect the second block
+ BlockContext secondBlock = bc
+ .createNewBlockInternal(firstBlock.block, Collections.emptyList(), true, time / 1000L);
+ assertThat(bc.tryToConnectInternal(secondBlock.block, time += 10)).isEqualTo(ImportResult.IMPORTED_BEST);
+
+ // now on the third block, we diverge with one block having higher TD than the other
+ BlockContext fasterSecondBlock = bc
+ .createNewBlockInternal(secondBlock.block, Collections.emptyList(), true, time / 1000L);
+ AionBlock slowerSecondBlock = new AionBlock(fasterSecondBlock.block);
+
+ slowerSecondBlock.getHeader().setTimestamp(time / 1000L + 100);
+
+ assertThat(bc.tryToConnectInternal(fasterSecondBlock.block, time + 100)).isEqualTo(ImportResult.IMPORTED_BEST);
+ assertThat(bc.tryToConnectInternal(slowerSecondBlock, time + 100)).isEqualTo(ImportResult.IMPORTED_NOT_BEST);
+
+ time += 100;
+
+ BlockContext fastBlockDescendant = bc
+ .createNewBlockInternal(fasterSecondBlock.block, Collections.emptyList(), true, time / 1000L);
+ BlockContext slowerBlockDescendant = bc
+ .createNewBlockInternal(slowerSecondBlock, Collections.emptyList(), true, time / 1000L + 100 + 1);
+
+ // increment by another hundred (this is supposed to be when the slower block descendant is completed)
+ time += 100;
+
+ assertThat(fastBlockDescendant.block.getDifficultyBI())
+ .isGreaterThan(slowerBlockDescendant.block.getDifficultyBI());
+ System.out.println("faster block descendant TD: " + fastBlockDescendant.block.getDifficultyBI());
+ System.out.println("slower block descendant TD: " + slowerBlockDescendant.block.getDifficultyBI());
+
+ assertThat(bc.tryToConnectInternal(slowerBlockDescendant.block, time)).isEqualTo(ImportResult.IMPORTED_BEST);
+
+ // corrupt the parent for the fast block descendant
+ bc.getRepository().getStateDatabase().delete(fasterSecondBlock.block.getStateRoot());
+ assertThat(bc.getRepository().isValidRoot(fasterSecondBlock.block.getStateRoot())).isFalse();
+
+ // attempt adding the fastBlockDescendant
+ assertThat(bc.tryToConnectInternal(fastBlockDescendant.block, time)).isEqualTo(ImportResult.INVALID_BLOCK);
+
+ // check for correct state rollback
+ assertThat(bc.getBestBlock()).isEqualTo(slowerBlockDescendant.block);
+ assertThat(bc.getRepository().getRoot()).isEqualTo(slowerBlockDescendant.block.getStateRoot());
+ assertThat(bc.getTotalDifficulty()).isEqualTo(bc.getRepository().getBlockStore()
+ .getTotalDifficultyForHash(slowerBlockDescendant.block
+ .getHash()));
+ }
+
+ @Test
+ public void testRollbackWithAddInvalidBlock() {
+ StandaloneBlockchain.Builder builder = new StandaloneBlockchain.Builder();
+ StandaloneBlockchain.Bundle b = builder.withValidatorConfiguration("simple").build();
+
+ StandaloneBlockchain bc = b.bc;
+ AionBlock block = bc.createNewBlock(bc.getBestBlock(), Collections.emptyList(), true);
+
+ assertThat(bc.tryToConnect(block)).isEqualTo(ImportResult.IMPORTED_BEST);
+
+ // check that the returned block is the first block
+ assertThat(bc.getBestBlock() == block).isTrue();
+
+ AionBlock invalidBlock = bc.createNewBlock(bc.getBestBlock(), Collections.emptyList(), true);
+ invalidBlock.getHeader().setDifficulty(BigInteger.ONE.toByteArray());
+
+ // attempting to add invalid block
+ assertThat(bc.tryToConnect(invalidBlock)).isEqualTo(ImportResult.INVALID_BLOCK);
+
+ // check for correct state rollback
+ assertThat(bc.getBestBlock()).isEqualTo(block);
+ assertThat(bc.getRepository().getRoot()).isEqualTo(block.getStateRoot());
+ assertThat(bc.getTotalDifficulty())
+ .isEqualTo(bc.getRepository().getBlockStore().getTotalDifficultyForHash(block.getHash()));
+ }
}
diff --git a/modAionImpl/test/org/aion/zero/impl/GenesisSpecificationTest.java b/modAionImpl/test/org/aion/zero/impl/GenesisSpecificationTest.java
index 2082f12375..181c940843 100644
--- a/modAionImpl/test/org/aion/zero/impl/GenesisSpecificationTest.java
+++ b/modAionImpl/test/org/aion/zero/impl/GenesisSpecificationTest.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* Copyright (c) 2017-2018 Aion foundation.
*
* This file is part of the aion network project.
@@ -31,7 +31,7 @@
* Samuel Neves through the BLAKE2 implementation.
* Zcash project team.
* Bitcoinj team.
- ******************************************************************************/
+ */
package org.aion.zero.impl;
import static com.google.common.truth.Truth.assertThat;
@@ -78,7 +78,7 @@ public void defaultGenesisBlockTest() throws HeaderStructureException {
assertThat(genesis.getNrgLimit()).isEqualTo(AionGenesis.GENESIS_ENERGY_LIMIT);
assertThat(genesis.getTxTrieRoot()).isEqualTo(HashUtil.EMPTY_TRIE_HASH);
assertThat(genesis.getReceiptsRoot()).isEqualTo(HashUtil.EMPTY_TRIE_HASH);
- assertThat(genesis.getCumulativeDifficulty()).isEqualTo(new BigInteger(1, AionGenesis.GENESIS_DIFFICULTY));
+ assertThat(genesis.getDifficultyBI()).isEqualTo(new BigInteger(1, AionGenesis.GENESIS_DIFFICULTY));
assertThat(genesis.getTransactionsList().isEmpty()).isEqualTo(true);
Map premined = genesis.getPremine();
@@ -128,7 +128,7 @@ public void overrideGenesisBlockTest() throws HeaderStructureException {
assertThat(genesis.getNrgLimit()).isEqualTo(overrideValue.longValue());
assertThat(genesis.getTxTrieRoot()).isEqualTo(HashUtil.EMPTY_TRIE_HASH);
assertThat(genesis.getReceiptsRoot()).isEqualTo(HashUtil.EMPTY_TRIE_HASH);
- assertThat(genesis.getCumulativeDifficulty()).isEqualTo(overrideValue);
+ assertThat(genesis.getDifficultyBI()).isEqualTo(overrideValue);
assertThat(genesis.getTransactionsList().isEmpty()).isEqualTo(true);
assertThat(genesis.getPremine().keySet()).isEqualTo(accountStateSet);
diff --git a/modAionImpl/test/org/aion/zero/impl/MockRepositoryConfig.java b/modAionImpl/test/org/aion/zero/impl/MockRepositoryConfig.java
index 699260162a..15a29ea253 100644
--- a/modAionImpl/test/org/aion/zero/impl/MockRepositoryConfig.java
+++ b/modAionImpl/test/org/aion/zero/impl/MockRepositoryConfig.java
@@ -1,13 +1,14 @@
package org.aion.zero.impl;
+import java.util.Properties;
import org.aion.base.db.IContractDetails;
+import org.aion.base.db.IPruneConfig;
import org.aion.base.db.IRepositoryConfig;
import org.aion.db.impl.DBVendor;
import org.aion.db.impl.DatabaseFactory;
+import org.aion.mcf.config.CfgPrune;
import org.aion.zero.impl.db.ContractDetailsAion;
-import java.util.Properties;
-
public class MockRepositoryConfig implements IRepositoryConfig {
private DBVendor vendor = DBVendor.MOCKDB;
@@ -17,8 +18,8 @@ public String getDbPath() {
}
@Override
- public int getPrune() {
- return 0;
+ public IPruneConfig getPruneConfig() {
+ return new CfgPrune(false);
}
@Override
diff --git a/modAionImpl/test/org/aion/zero/impl/db/AionRepositoryImplTest.java b/modAionImpl/test/org/aion/zero/impl/db/AionRepositoryImplTest.java
index 44f6aa4445..c05c59b414 100644
--- a/modAionImpl/test/org/aion/zero/impl/db/AionRepositoryImplTest.java
+++ b/modAionImpl/test/org/aion/zero/impl/db/AionRepositoryImplTest.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/* ******************************************************************************
* Copyright (c) 2017-2018 Aion foundation.
*
* This file is part of the aion network project.
@@ -34,67 +34,68 @@
******************************************************************************/
package org.aion.zero.impl.db;
-import org.aion.base.db.IByteArrayKeyValueDatabase;
-import org.aion.base.db.IContractDetails;
-import org.aion.base.db.IRepositoryCache;
-import org.aion.base.db.IRepositoryConfig;
+import static com.google.common.truth.Truth.assertThat;
+
+import java.math.BigInteger;
+import java.util.Optional;
+import java.util.Properties;
+import org.aion.base.db.*;
import org.aion.base.type.Address;
import org.aion.base.util.ByteUtil;
-import org.aion.db.impl.DatabaseFactory;
-import org.aion.db.impl.leveldb.LevelDBConstants;
-import org.aion.mcf.core.AccountState;
import org.aion.crypto.HashUtil;
import org.aion.db.impl.DBVendor;
+import org.aion.db.impl.DatabaseFactory;
+import org.aion.mcf.config.CfgPrune;
+import org.aion.mcf.core.AccountState;
import org.aion.mcf.db.IBlockStoreBase;
import org.aion.mcf.vm.types.DataWord;
+import org.aion.zero.db.AionContractDetailsImpl;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
-import org.aion.zero.db.AionContractDetailsImpl;
-import org.aion.zero.impl.db.AionRepositoryImpl;
-import org.aion.zero.impl.db.ContractDetailsAion;
-
-import java.math.BigInteger;
-import java.util.Optional;
-import java.util.Properties;
-
-import static com.google.common.truth.Truth.assertThat;
-
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class AionRepositoryImplTest {
- protected IRepositoryConfig repoConfig = new IRepositoryConfig() {
- @Override
- public String getDbPath() {
- return "";
- }
-
- @Override
- public int getPrune() {
- return 0;
- }
-
- @Override
- public IContractDetails contractDetailsImpl() {
- return ContractDetailsAion.createForTesting(0, 1000000).getDetails();
- }
-
- @Override
- public Properties getDatabaseConfig(String db_name) {
- Properties props = new Properties();
- props.setProperty(DatabaseFactory.Props.DB_TYPE, DBVendor.MOCKDB.toValue());
- props.setProperty(DatabaseFactory.Props.ENABLE_HEAP_CACHE, "false");
- return props;
- }
- };
+ protected IRepositoryConfig repoConfig =
+ new IRepositoryConfig() {
+ @Override
+ public String getDbPath() {
+ return "";
+ }
+
+ @Override
+ public IPruneConfig getPruneConfig() {
+ return new CfgPrune(false);
+ }
+
+ @Override
+ public IContractDetails contractDetailsImpl() {
+ return ContractDetailsAion.createForTesting(0, 1000000).getDetails();
+ }
+
+ @Override
+ public Properties getDatabaseConfig(String db_name) {
+ Properties props = new Properties();
+ props.setProperty(DatabaseFactory.Props.DB_TYPE, DBVendor.MOCKDB.toValue());
+ props.setProperty(DatabaseFactory.Props.ENABLE_HEAP_CACHE, "false");
+ return props;
+ }
+ };
+
+ private static String value1 =
+ "CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3";
+ private static String value2 =
+ "CAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFE";
+ private static String value3 =
+ "BEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEF";
@Test
public void testAccountStateUpdate() {
AionRepositoryImpl repository = AionRepositoryImpl.createForTesting(repoConfig);
byte[] originalRoot = repository.getRoot();
- Address defaultAccount = Address.wrap(ByteUtil.hexStringToBytes("CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3"));
+ Address defaultAccount = Address.wrap(ByteUtil.hexStringToBytes(value1));
IRepositoryCache track = repository.startTracking();
track.addBalance(defaultAccount, BigInteger.valueOf(1));
@@ -112,7 +113,7 @@ public void testAccountAddCodeStorage() {
AionRepositoryImpl repository = AionRepositoryImpl.createForTesting(repoConfig);
IRepositoryCache track = repository.startTracking();
- Address defaultAccount = Address.wrap(ByteUtil.hexStringToBytes("CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3"));
+ Address defaultAccount = Address.wrap(ByteUtil.hexStringToBytes(value1));
track.addBalance(defaultAccount, BigInteger.valueOf(1));
byte[] originalRoot = repository.getRoot();
@@ -133,7 +134,7 @@ public void testAccountStateUpdateStorageRow() {
AionRepositoryImpl repository = AionRepositoryImpl.createForTesting(repoConfig);
IRepositoryCache track = repository.startTracking();
- Address defaultAccount = Address.wrap(ByteUtil.hexStringToBytes("CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3"));
+ Address defaultAccount = Address.wrap(ByteUtil.hexStringToBytes(value1));
track.addBalance(defaultAccount, BigInteger.valueOf(1));
// Consider the original root the one after an account has been added
@@ -144,7 +145,8 @@ public void testAccountStateUpdateStorageRow() {
track.flush();
- byte[] retrievedValue = repository.getStorageValue(defaultAccount, new DataWord(key)).getNoLeadZeroesData();
+ byte[] retrievedValue =
+ repository.getStorageValue(defaultAccount, new DataWord(key)).getNoLeadZeroesData();
assertThat(retrievedValue).isEqualTo(value);
byte[] newRoot = repository.getRoot();
@@ -158,7 +160,7 @@ public void testAccountStateUpdateStorageRowFlush() {
AionRepositoryImpl repository = AionRepositoryImpl.createForTesting(repoConfig);
IRepositoryCache track = repository.startTracking();
- Address defaultAccount = Address.wrap(ByteUtil.hexStringToBytes("CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3"));
+ Address defaultAccount = Address.wrap(ByteUtil.hexStringToBytes(value1));
track.addBalance(defaultAccount, BigInteger.valueOf(1));
// Consider the original root the one after an account has been added
@@ -172,9 +174,7 @@ public void testAccountStateUpdateStorageRowFlush() {
repository.flush();
- /**
- * Verify that the account has been flushed
- */
+ /** Verify that the account has been flushed */
IByteArrayKeyValueDatabase detailsDB = repository.getDetailsDatabase();
Optional serializedDetails = detailsDB.get(defaultAccount.toBytes());
@@ -185,20 +185,18 @@ public void testAccountStateUpdateStorageRowFlush() {
assertThat(details.get(new DataWord(key))).isEqualTo(new DataWord(value));
}
- /**
- * Repo track test suite
- */
-
+ /** Repo track test suite */
/**
- * This test confirms that updates done on the repo track are successfully translated
- * into the root repository.
+ * This test confirms that updates done on the repo track are successfully translated into the
+ * root repository.
*/
@Test
public void testRepoTrackUpdateStorageRow() {
final AionRepositoryImpl repository = AionRepositoryImpl.createForTesting(repoConfig);
- final IRepositoryCache> repoTrack = repository.startTracking();
- final Address defaultAccount = Address.wrap(ByteUtil.hexStringToBytes("CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3CAF3"));
+ final IRepositoryCache> repoTrack =
+ repository.startTracking();
+ final Address defaultAccount = Address.wrap(ByteUtil.hexStringToBytes(value1));
final byte[] key = HashUtil.blake128("hello".getBytes());
final byte[] value = HashUtil.blake128("world".getBytes());
@@ -208,29 +206,24 @@ public void testRepoTrackUpdateStorageRow() {
repoTrack.addStorageRow(defaultAccount, new DataWord(key), new DataWord(value));
- DataWord retrievedStorageValue = repoTrack.getStorageValue(defaultAccount, new DataWord(key));
+ DataWord retrievedStorageValue =
+ repoTrack.getStorageValue(defaultAccount, new DataWord(key));
assertThat(retrievedStorageValue).isEqualTo(new DataWord(value));
// commit changes, then check that the root has updated
repoTrack.flush();
- assertThat(repository.getStorageValue(defaultAccount, new DataWord(key))).isEqualTo(retrievedStorageValue);
+ assertThat(repository.getStorageValue(defaultAccount, new DataWord(key)))
+ .isEqualTo(retrievedStorageValue);
final byte[] newRoot = repository.getRoot();
assertThat(newRoot).isNotEqualTo(originalRoot);
}
- /**
- * Tests behaviour for trie when trying to revert to a previous root without
- * first flushing. Note the behaviour here. Interestingly enough, it seems like
- * the trie must first be flushed, so that the root node is in the caching/db layer.
- *
- * Otherwise the retrieval methods will not be able to find the temporal root value.
- */
@Test
public void testSyncToPreviousRootNoFlush() {
- final Address FIRST_ACC = Address.wrap("CAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFE");
- final Address SECOND_ACC = Address.wrap("BEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEFBEEF");
+ final Address FIRST_ACC = Address.wrap(value2);
+ final Address SECOND_ACC = Address.wrap(value3);
final AionRepositoryImpl repository = AionRepositoryImpl.createForTesting(repoConfig);
byte[] originalRoot = repository.getRoot();
@@ -243,6 +236,10 @@ public void testSyncToPreviousRootNoFlush() {
System.out.println("after first account added");
System.out.println(repository.getWorldState().getTrieDump());
+ // check the update on the repo
+ BigInteger balance = repository.getBalance(FIRST_ACC);
+ assertThat(balance).isEqualTo(BigInteger.ONE);
+
byte[] firstRoot = repository.getRoot();
track = repository.startTracking();
@@ -257,18 +254,21 @@ public void testSyncToPreviousRootNoFlush() {
assertThat(firstRoot).isNotEqualTo(originalRoot);
assertThat(secondRoot).isNotEqualTo(firstRoot);
+ System.out.println("after sync to after first account added");
repository.syncToRoot(firstRoot);
+ assertThat(repository.isValidRoot(firstRoot)).isTrue();
+ System.out.println(repository.getWorldState().getTrieDump());
assertThat(repository.getRoot()).isEqualTo(firstRoot);
- BigInteger balance = repository.getBalance(FIRST_ACC);
+ balance = repository.getBalance(FIRST_ACC);
// notice that the first blocks balance is also zero
- assertThat(balance).isEqualTo(BigInteger.ZERO);
+ assertThat(balance).isEqualTo(BigInteger.ONE);
}
@Test
public void testSyncToPreviousRootWithFlush() {
- final Address FIRST_ACC = Address.wrap("CAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFE");
+ final Address FIRST_ACC = Address.wrap(value2);
AionRepositoryImpl repository = AionRepositoryImpl.createForTesting(repoConfig);
byte[] originalRoot = repository.getRoot();
diff --git a/modAionImpl/test/org/aion/zero/impl/sync/BlockPropagationTest.java b/modAionImpl/test/org/aion/zero/impl/sync/BlockPropagationTest.java
index 5b6fe0d228..96b9eb6e8c 100644
--- a/modAionImpl/test/org/aion/zero/impl/sync/BlockPropagationTest.java
+++ b/modAionImpl/test/org/aion/zero/impl/sync/BlockPropagationTest.java
@@ -1,21 +1,54 @@
+/*
+ * Copyright (c) 2017-2018 Aion foundation.
+ *
+ * This file is part of the aion network project.
+ *
+ * The aion network project 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 any later version.
+ *
+ * The aion network project 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 the aion network project source files.
+ * If not, see .
+ *
+ * Contributors:
+ * Aion foundation.
+ */
package org.aion.zero.impl.sync;
import static com.google.common.truth.Truth.assertThat;
import java.math.BigInteger;
import java.nio.channels.SocketChannel;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.aion.crypto.ECKey;
import org.aion.crypto.ECKeyFac;
import org.aion.crypto.HashUtil;
-import org.aion.p2p.*;
+import org.aion.p2p.Handler;
+import org.aion.p2p.INode;
+import org.aion.p2p.IP2pMgr;
+import org.aion.p2p.IPeerMetric;
+import org.aion.p2p.Msg;
import org.aion.zero.impl.StandaloneBlockchain;
import org.aion.zero.impl.sync.handler.BlockPropagationHandler;
import org.aion.zero.impl.types.AionBlock;
import org.junit.Test;
-/** Unit tests for block propagation */
+/**
+ * Unit tests for block propagation
+ */
public class BlockPropagationTest {
private static class NodeMock implements INode {
@@ -50,7 +83,8 @@ public BigInteger getTotalDifficulty() {
@Override
public void updateStatus(
- long _bestBlockNumber, byte[] _bestBlockHash, BigInteger _totalDifficulty) {}
+ long _bestBlockNumber, byte[] _bestBlockHash, BigInteger _totalDifficulty) {
+ }
@Override
public byte[] getIp() {
@@ -81,6 +115,66 @@ public long getTimestamp() {
public String getBinaryVersion() {
return "";
}
+
+ @Override
+ public void setPort(int _port) {
+ throw new IllegalStateException("not implemented");
+ }
+
+ @Override
+ public void setConnection(String _connection) {
+ throw new IllegalStateException("not implemented");
+ }
+
+ @Override
+ public IPeerMetric getPeerMetric() {
+ throw new IllegalStateException("not implemented");
+ }
+
+ @Override
+ public void refreshTimestamp() {
+ throw new IllegalStateException("not implemented");
+ }
+
+ @Override
+ public void setChannel(SocketChannel _channel) {
+ throw new IllegalStateException("not implemented");
+ }
+
+ @Override
+ public void setId(byte[] _id) {
+ throw new IllegalStateException("not implemented");
+ }
+
+ @Override
+ public void setBinaryVersion(String _revision) {
+ throw new IllegalStateException("not implemented");
+ }
+
+ @Override
+ public boolean getIfFromBootList() {
+ throw new IllegalStateException("not implemented");
+ }
+
+ @Override
+ public byte[] getBestBlockHash() {
+ throw new IllegalStateException("not implemented");
+ }
+
+ @Override
+ public String getConnection() {
+ throw new IllegalStateException("not implemented");
+ }
+
+ @Override
+ public SocketChannel getChannel() {
+ throw new IllegalStateException("not implemented");
+ }
+
+ @Override
+ public void setFromBootList(boolean _ifBoot) {
+ throw new IllegalStateException("not implemented");
+ }
}
private static class P2pMock implements IP2pMgr {
@@ -97,10 +191,12 @@ public Map getActiveNodes() {
}
@Override
- public void shutdown() {}
+ public void shutdown() {
+ }
@Override
- public void run() {}
+ public void run() {
+ }
@Override
public List versions() {
@@ -113,10 +209,12 @@ public int chainId() {
}
@Override
- public void errCheck(int nodeIdHashcode, String _displayId) {}
+ public void errCheck(int nodeIdHashcode, String _displayId) {
+ }
@Override
- public void register(List _hs) {}
+ public void register(List _hs) {
+ }
@Override
public INode getRandom() {
@@ -124,20 +222,51 @@ public INode getRandom() {
}
@Override
- public void send(int _id, String s, Msg _msg) {}
+ public void send(int _id, String _displayId, Msg _msg) {
+ }
@Override
- public boolean isShowLog() {
+ public void closeSocket(SocketChannel _sc, String _reason) {
+ }
+
+ @Override
+ public int getSelfIdHash() {
+ return 0;
+ }
+
+ @Override
+ public void dropActive(int _nodeIdHash, String _reason) {
+ throw new IllegalStateException("not implemented.");
+ }
+
+ @Override
+ public void configChannel(SocketChannel _channel) {
+ throw new IllegalStateException("not implemented.");
+ }
+
+ @Override
+ public int getMaxActiveNodes() {
+ throw new IllegalStateException("not implemented.");
+ }
+
+ @Override
+ public boolean isSyncSeedsOnly() {
return false;
}
@Override
- public void closeSocket(SocketChannel _sc, String _reason) {}
+ public int getMaxTempNodes() { throw new IllegalStateException("not implemented."); }
@Override
- public int getSelfIdHash() {
- return 0;
+ public boolean validateNode(INode _node) {
+ throw new IllegalStateException("not implemented.");
+ }
+
+ @Override
+ public int getSelfNetId() {
+ throw new IllegalStateException("not implemented.");
}
+
}
private static List generateDefaultAccounts() {
@@ -148,19 +277,21 @@ private static List generateDefaultAccounts() {
return accs;
}
- /** Test that we don't propagate back to the sender */
+ /**
+ * Test that we don't propagate back to the sender
+ */
@Test
public void testBlockPropagationReceiver() {
List accounts = generateDefaultAccounts();
StandaloneBlockchain.Bundle bundle =
- new StandaloneBlockchain.Builder()
- .withValidatorConfiguration("simple")
- .withDefaultAccounts(accounts)
- .build();
+ new StandaloneBlockchain.Builder()
+ .withValidatorConfiguration("simple")
+ .withDefaultAccounts(accounts)
+ .build();
AionBlock block =
- bundle.bc.createNewBlock(bundle.bc.getGenesis(), Collections.EMPTY_LIST, true);
+ bundle.bc.createNewBlock(bundle.bc.getGenesis(), Collections.EMPTY_LIST, true);
assertThat(block.getNumber()).isEqualTo(1);
byte[] sender = HashUtil.h256("node1".getBytes());
@@ -170,29 +301,29 @@ public void testBlockPropagationReceiver() {
node.put(1, senderMock);
P2pMock p2pMock =
- new P2pMock(node) {
- @Override
- public void send(int _nodeId, String s, Msg _msg) {
- throw new RuntimeException("should not have called send");
- }
- };
+ new P2pMock(node) {
+ @Override
+ public void send(int _nodeId, String s, Msg _msg) {
+ throw new RuntimeException("should not have called send");
+ }
+ };
StandaloneBlockchain.Bundle anotherBundle =
- new StandaloneBlockchain.Builder()
- .withValidatorConfiguration("simple")
- .withDefaultAccounts(accounts)
- .build();
+ new StandaloneBlockchain.Builder()
+ .withValidatorConfiguration("simple")
+ .withDefaultAccounts(accounts)
+ .build();
BlockPropagationHandler handler =
- new BlockPropagationHandler(
- 1024,
- anotherBundle.bc, // NOTE: not the same blockchain that generated the block
- p2pMock,
- anotherBundle.bc.getBlockHeaderValidator(),
- false);
+ new BlockPropagationHandler(
+ 1024,
+ anotherBundle.bc, // NOTE: not the same blockchain that generated the block
+ p2pMock,
+ anotherBundle.bc.getBlockHeaderValidator(),
+ false);
assertThat(handler.processIncomingBlock(senderMock.getIdHash(), "test", block))
- .isEqualTo(BlockPropagationHandler.PropStatus.CONNECTED);
+ .isEqualTo(BlockPropagationHandler.PropStatus.CONNECTED);
}
// given two peers, and one sends you a new block, propagate to the other
@@ -201,13 +332,13 @@ public void testPropagateBlockToPeer() {
List accounts = generateDefaultAccounts();
StandaloneBlockchain.Bundle bundle =
- new StandaloneBlockchain.Builder()
- .withValidatorConfiguration("simple")
- .withDefaultAccounts(accounts)
- .build();
+ new StandaloneBlockchain.Builder()
+ .withValidatorConfiguration("simple")
+ .withDefaultAccounts(accounts)
+ .build();
AionBlock block =
- bundle.bc.createNewBlock(bundle.bc.getGenesis(), Collections.EMPTY_LIST, true);
+ bundle.bc.createNewBlock(bundle.bc.getGenesis(), Collections.EMPTY_LIST, true);
assertThat(block.getNumber()).isEqualTo(1);
byte[] sender = HashUtil.h256("node1".getBytes());
@@ -222,20 +353,21 @@ public void testPropagateBlockToPeer() {
AtomicInteger times = new AtomicInteger();
P2pMock p2pMock =
- new P2pMock(node) {
- @Override
- public void send(int _nodeId, String s, Msg _msg) {
- if (_nodeId != receiverMock.getIdHash())
- throw new RuntimeException("should only send to receiver");
- times.getAndIncrement();
+ new P2pMock(node) {
+ @Override
+ public void send(int _nodeId, String s, Msg _msg) {
+ if (_nodeId != receiverMock.getIdHash()) {
+ throw new RuntimeException("should only send to receiver");
}
- };
+ times.getAndIncrement();
+ }
+ };
StandaloneBlockchain.Bundle anotherBundle =
- new StandaloneBlockchain.Builder()
- .withValidatorConfiguration("simple")
- .withDefaultAccounts(accounts)
- .build();
+ new StandaloneBlockchain.Builder()
+ .withValidatorConfiguration("simple")
+ .withDefaultAccounts(accounts)
+ .build();
assertThat(bundle.bc.genesis.getHash()).isEqualTo(anotherBundle.bc.genesis.getHash());
assertThat(block.getParentHash()).isEqualTo(bundle.bc.genesis.getHash());
@@ -245,16 +377,16 @@ public void send(int _nodeId, String s, Msg _msg) {
assertThat(bestBlock.getHash()).isEqualTo(anotherBundle.bc.genesis.getHash());
BlockPropagationHandler handler =
- new BlockPropagationHandler(
- 1024,
- anotherBundle.bc, // NOTE: not the same blockchain that generated the block
- p2pMock,
- anotherBundle.bc.getBlockHeaderValidator(),
- false);
+ new BlockPropagationHandler(
+ 1024,
+ anotherBundle.bc, // NOTE: not the same blockchain that generated the block
+ p2pMock,
+ anotherBundle.bc.getBlockHeaderValidator(),
+ false);
// block is processed
assertThat(handler.processIncomingBlock(senderMock.getIdHash(), "test", block))
- .isEqualTo(BlockPropagationHandler.PropStatus.PROP_CONNECTED);
+ .isEqualTo(BlockPropagationHandler.PropStatus.PROP_CONNECTED);
assertThat(times.get()).isEqualTo(1);
}
@@ -263,13 +395,13 @@ public void testIgnoreSameBlock() {
List accounts = generateDefaultAccounts();
StandaloneBlockchain.Bundle bundle =
- new StandaloneBlockchain.Builder()
- .withValidatorConfiguration("simple")
- .withDefaultAccounts(accounts)
- .build();
+ new StandaloneBlockchain.Builder()
+ .withValidatorConfiguration("simple")
+ .withDefaultAccounts(accounts)
+ .build();
AionBlock block =
- bundle.bc.createNewBlock(bundle.bc.getGenesis(), Collections.EMPTY_LIST, true);
+ bundle.bc.createNewBlock(bundle.bc.getGenesis(), Collections.EMPTY_LIST, true);
assertThat(block.getNumber()).isEqualTo(1);
byte[] sender = HashUtil.h256("node1".getBytes());
@@ -284,36 +416,37 @@ public void testIgnoreSameBlock() {
AtomicInteger times = new AtomicInteger();
P2pMock p2pMock =
- new P2pMock(node) {
- @Override
- public void send(int _nodeId, String s, Msg _msg) {
- if (_nodeId != receiverMock.getIdHash())
- throw new RuntimeException("should only send to receiver");
- times.getAndIncrement();
+ new P2pMock(node) {
+ @Override
+ public void send(int _nodeId, String s, Msg _msg) {
+ if (_nodeId != receiverMock.getIdHash()) {
+ throw new RuntimeException("should only send to receiver");
}
- };
+ times.getAndIncrement();
+ }
+ };
StandaloneBlockchain.Bundle anotherBundle =
- new StandaloneBlockchain.Builder()
- .withValidatorConfiguration("simple")
- .withDefaultAccounts(accounts)
- .build();
+ new StandaloneBlockchain.Builder()
+ .withValidatorConfiguration("simple")
+ .withDefaultAccounts(accounts)
+ .build();
assertThat(bundle.bc.genesis.getHash()).isEqualTo(anotherBundle.bc.genesis.getHash());
BlockPropagationHandler handler =
- new BlockPropagationHandler(
- 1024,
- anotherBundle.bc, // NOTE: not the same blockchain that generated the block
- p2pMock,
- anotherBundle.bc.getBlockHeaderValidator(),
- false);
+ new BlockPropagationHandler(
+ 1024,
+ anotherBundle.bc, // NOTE: not the same blockchain that generated the block
+ p2pMock,
+ anotherBundle.bc.getBlockHeaderValidator(),
+ false);
// block is processed
assertThat(handler.processIncomingBlock(senderMock.getIdHash(), "test", block))
- .isEqualTo(BlockPropagationHandler.PropStatus.PROP_CONNECTED);
+ .isEqualTo(BlockPropagationHandler.PropStatus.PROP_CONNECTED);
assertThat(handler.processIncomingBlock(senderMock.getIdHash(), "test", block))
- .isEqualTo(BlockPropagationHandler.PropStatus.DROPPED);
+ .isEqualTo(BlockPropagationHandler.PropStatus.DROPPED);
assertThat(times.get()).isEqualTo(1);
}
@@ -323,13 +456,13 @@ public void testIgnoreSelfBlock() {
List accounts = generateDefaultAccounts();
StandaloneBlockchain.Bundle bundle =
- new StandaloneBlockchain.Builder()
- .withValidatorConfiguration("simple")
- .withDefaultAccounts(accounts)
- .build();
+ new StandaloneBlockchain.Builder()
+ .withValidatorConfiguration("simple")
+ .withDefaultAccounts(accounts)
+ .build();
AionBlock block =
- bundle.bc.createNewBlock(bundle.bc.getGenesis(), Collections.EMPTY_LIST, true);
+ bundle.bc.createNewBlock(bundle.bc.getGenesis(), Collections.EMPTY_LIST, true);
assertThat(block.getNumber()).isEqualTo(1);
byte[] sender = HashUtil.h256("node1".getBytes());
@@ -340,26 +473,26 @@ public void testIgnoreSelfBlock() {
AtomicInteger sendCount = new AtomicInteger();
P2pMock p2pMock =
- new P2pMock(node) {
- @Override
- public void send(int _nodeId, String s, Msg _msg) {
- sendCount.getAndIncrement();
- }
- };
+ new P2pMock(node) {
+ @Override
+ public void send(int _nodeId, String s, Msg _msg) {
+ sendCount.getAndIncrement();
+ }
+ };
StandaloneBlockchain.Bundle anotherBundle =
- new StandaloneBlockchain.Builder()
- .withValidatorConfiguration("simple")
- .withDefaultAccounts(accounts)
- .build();
+ new StandaloneBlockchain.Builder()
+ .withValidatorConfiguration("simple")
+ .withDefaultAccounts(accounts)
+ .build();
BlockPropagationHandler handler =
- new BlockPropagationHandler(
- 1024,
- anotherBundle.bc, // NOTE: not the same blockchain that generated the block
- p2pMock,
- anotherBundle.bc.getBlockHeaderValidator(),
- false);
+ new BlockPropagationHandler(
+ 1024,
+ anotherBundle.bc, // NOTE: not the same blockchain that generated the block
+ p2pMock,
+ anotherBundle.bc.getBlockHeaderValidator(),
+ false);
// pretend that we propagate the new block
handler.propagateNewBlock(block); // send counter incremented
@@ -368,7 +501,7 @@ public void send(int _nodeId, String s, Msg _msg) {
// so our blockchain should view this block as a new block
// therefore if the filter fails, this block will actually be CONNECTED
assertThat(handler.processIncomingBlock(senderMock.getIdHash(), "test", block))
- .isEqualTo(BlockPropagationHandler.PropStatus.DROPPED);
+ .isEqualTo(BlockPropagationHandler.PropStatus.DROPPED);
// we expect the counter to be incremented once (on propagation)
assertThat(sendCount.get()).isEqualTo(1);
diff --git a/modApiServer/build.xml b/modApiServer/build.xml
index 63423de0a7..dfb936a416 100644
--- a/modApiServer/build.xml
+++ b/modApiServer/build.xml
@@ -35,7 +35,7 @@
-
@@ -63,7 +63,7 @@
-
@@ -93,31 +93,4 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/modApiServer/src/org/aion/api/server/Api.java b/modApiServer/src/org/aion/api/server/Api.java
index 743ba51e9e..2dc1402a3b 100644
--- a/modApiServer/src/org/aion/api/server/Api.java
+++ b/modApiServer/src/org/aion/api/server/Api.java
@@ -109,6 +109,14 @@ public Map contract_compileSolidity(final String _contrac
Compiler.Result res = solc.compile(_contract.getBytes(), Compiler.Options.ABI, Compiler.Options.BIN);
if (res.isFailed()) {
LOG.info("contract compile error: [{}]", res.errors);
+
+ /**
+ * Enhance performance by separating the log threads and kernel
+ * TODO: Implement a queue for strings
+ * TODO: Put every LOG message onto the queue
+ * TODO: Use a thread service to process these message
+ */
+
CompiledContr ret = new CompiledContr();
ret.error = res.errors;
compiledContracts.put("compile-error", ret);
diff --git a/modApiServer/src/org/aion/api/server/ApiAion.java b/modApiServer/src/org/aion/api/server/ApiAion.java
index 7f063b9716..4046facdc0 100644
--- a/modApiServer/src/org/aion/api/server/ApiAion.java
+++ b/modApiServer/src/org/aion/api/server/ApiAion.java
@@ -24,6 +24,21 @@
package org.aion.api.server;
+import static org.aion.evtmgr.impl.evt.EventTx.STATE.GETSTATE;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
import org.aion.api.server.nrgprice.NrgOracle;
import org.aion.api.server.types.ArgTxCall;
import org.aion.api.server.types.Fltr;
@@ -42,13 +57,13 @@
import org.aion.evtmgr.impl.es.EventExecuteService;
import org.aion.evtmgr.impl.evt.EventBlock;
import org.aion.evtmgr.impl.evt.EventTx;
-import org.aion.zero.impl.AionBlockchainImpl;
import org.aion.zero.impl.AionGenesis;
import org.aion.zero.impl.BlockContext;
import org.aion.zero.impl.Version;
import org.aion.zero.impl.blockchain.AionPendingStateImpl;
import org.aion.zero.impl.blockchain.IAionChain;
import org.aion.zero.impl.config.CfgAion;
+import org.aion.zero.impl.core.IAionBlockchain;
import org.aion.zero.impl.db.AionBlockStore;
import org.aion.zero.impl.types.AionBlock;
import org.aion.zero.impl.types.AionBlockSummary;
@@ -56,16 +71,6 @@
import org.aion.zero.types.AionTransaction;
import org.aion.zero.types.AionTxReceipt;
-import java.math.BigInteger;
-import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.locks.ReentrantLock;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import static org.aion.evtmgr.impl.evt.EventTx.STATE.GETSTATE;
-
public abstract class ApiAion extends Api {
// these variables get accessed by the api worker threads.
@@ -74,7 +79,7 @@ public abstract class ApiAion extends Api {
// 2. underlying datastructure provides concurrency guarntees
// delegate concurrency to underlying object
- protected NrgOracle nrgOracle;
+ protected static NrgOracle NRG_ORACLE;
protected IAionChain ac; // assumption: blockchainImpl et al. provide concurrency guarantee
// using java.util.concurrent library objects
@@ -658,16 +663,33 @@ protected boolean setReportedHashrate(String hashrate, String clientId) {
return false;
}
+ // Returns a fully initialized NrgOracle object.
+ protected void initNrgOracle(IAionChain _ac) {
+ if (NRG_ORACLE != null) {
+ return;
+ }
+
+ IAionBlockchain bc = (IAionBlockchain)_ac.getBlockchain();
+ long nrgPriceDefault = CfgAion.inst().getApi().getNrg().getNrgPriceDefault();
+ long nrgPriceMax = CfgAion.inst().getApi().getNrg().getNrgPriceMax();
+
+ NrgOracle.Strategy oracleStrategy = NrgOracle.Strategy.SIMPLE;
+ if (CfgAion.inst().getApi().getNrg().isOracleEnabled())
+ oracleStrategy = NrgOracle.Strategy.BLK_PRICE;
+
+ NRG_ORACLE = new NrgOracle(bc, nrgPriceDefault, nrgPriceMax, oracleStrategy);
+ }
+
protected long getRecommendedNrgPrice() {
- if (this.nrgOracle != null)
- return this.nrgOracle.getNrgPrice();
+ if (NRG_ORACLE != null)
+ return NRG_ORACLE.getNrgPrice();
else
return CfgAion.inst().getApi().getNrg().getNrgPriceDefault();
}
// leak the oracle instance. NrgOracle is threadsafe, so safe to do this, but bad design
protected NrgOracle getNrgOracle() {
- return this.nrgOracle;
+ return NRG_ORACLE;
}
protected long getDefaultNrgLimit() {
diff --git a/modApiServer/src/org/aion/api/server/http/ApiWeb3Aion.java b/modApiServer/src/org/aion/api/server/http/ApiWeb3Aion.java
index 1313fd7e7e..f6e07f4d26 100644
--- a/modApiServer/src/org/aion/api/server/http/ApiWeb3Aion.java
+++ b/modApiServer/src/org/aion/api/server/http/ApiWeb3Aion.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/* ******************************************************************************
* Copyright (c) 2017-2018 Aion foundation.
*
* This file is part of the aion network project.
@@ -19,36 +19,79 @@
*
* Contributors:
* Aion foundation.
- *
+ *
******************************************************************************/
package org.aion.api.server.http;
+import static org.aion.base.util.ByteUtil.hexStringToBytes;
+import static org.aion.base.util.ByteUtil.toHexString;
+
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableFutureTask;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.math.RoundingMode;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Map;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.aion.api.server.ApiAion;
-import org.aion.api.server.nrgprice.NrgOracle;
import org.aion.api.server.rpc.RpcError;
import org.aion.api.server.rpc.RpcMsg;
-import org.aion.api.server.types.*;
+import org.aion.api.server.types.ArgFltr;
+import org.aion.api.server.types.ArgTxCall;
+import org.aion.api.server.types.Blk;
+import org.aion.api.server.types.CompiledContr;
+import org.aion.api.server.types.Evt;
+import org.aion.api.server.types.Fltr;
+import org.aion.api.server.types.FltrBlk;
+import org.aion.api.server.types.FltrLg;
+import org.aion.api.server.types.FltrTx;
+import org.aion.api.server.types.NumericalValue;
+import org.aion.api.server.types.SyncInfo;
+import org.aion.api.server.types.Tx;
+import org.aion.api.server.types.TxRecpt;
import org.aion.base.db.IRepository;
import org.aion.base.type.Address;
import org.aion.base.type.Hash256;
import org.aion.base.type.ITransaction;
import org.aion.base.type.ITxReceipt;
-import org.aion.base.util.*;
+import org.aion.base.util.ByteArrayWrapper;
+import org.aion.base.util.ByteUtil;
+import org.aion.base.util.FastByteComparisons;
+import org.aion.base.util.TypeConverter;
+import org.aion.base.util.Utils;
import org.aion.crypto.ECKey;
import org.aion.crypto.HashUtil;
import org.aion.evtmgr.IEventMgr;
import org.aion.evtmgr.IHandler;
import org.aion.evtmgr.impl.callback.EventCallback;
import org.aion.evtmgr.impl.evt.EventTx;
-import org.aion.mcf.config.*;
import org.aion.mcf.account.Keystore;
+import org.aion.mcf.config.CfgApi;
+import org.aion.mcf.config.CfgApiNrg;
+import org.aion.mcf.config.CfgApiRpc;
+import org.aion.mcf.config.CfgApiZmq;
+import org.aion.mcf.config.CfgNet;
import org.aion.mcf.config.CfgNetP2p;
+import org.aion.mcf.config.CfgSync;
+import org.aion.mcf.config.CfgTx;
import org.aion.mcf.core.AccountState;
import org.aion.mcf.core.ImportResult;
import org.aion.mcf.vm.types.DataWord;
@@ -62,7 +105,6 @@
import org.aion.zero.impl.config.CfgAion;
import org.aion.zero.impl.config.CfgConsensusPow;
import org.aion.zero.impl.config.CfgEnergyStrategy;
-import org.aion.zero.impl.core.IAionBlockchain;
import org.aion.zero.impl.db.AionBlockStore;
import org.aion.zero.impl.db.AionRepositoryImpl;
import org.aion.zero.impl.sync.PeerState;
@@ -76,21 +118,6 @@
import org.json.JSONArray;
import org.json.JSONObject;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.math.RoundingMode;
-import java.time.Instant;
-import java.time.ZoneOffset;
-import java.util.*;
-import java.util.HashMap;
-import java.util.concurrent.*;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-import static org.aion.base.util.ByteUtil.hexStringToBytes;
-import static org.aion.base.util.ByteUtil.toHexString;
-
/**
* @author chris lin, ali sharif
* TODO: make implementation pass all spec tests: https://github.com/ethereum/rpc-tests
@@ -172,17 +199,7 @@ public ApiWeb3Aion(final IAionChain _ac) {
isFilterEnabled = CfgAion.inst().getApi().getRpc().isFiltersEnabled();
isSeedMode = CfgAion.inst().getConsensus().isSeed();
-
- // instantiate nrg price oracle
- IAionBlockchain bc = (IAionBlockchain)_ac.getBlockchain();
- long nrgPriceDefault = CfgAion.inst().getApi().getNrg().getNrgPriceDefault();
- long nrgPriceMax = CfgAion.inst().getApi().getNrg().getNrgPriceMax();
-
- NrgOracle.Strategy oracleStrategy = NrgOracle.Strategy.SIMPLE;
- if (CfgAion.inst().getApi().getNrg().isOracleEnabled())
- oracleStrategy = NrgOracle.Strategy.BLK_PRICE;
-
- this.nrgOracle = new NrgOracle(bc, nrgPriceDefault, nrgPriceMax, oracleStrategy);
+ initNrgOracle(_ac);
if (isFilterEnabled) {
evtMgr = this.ac.getAionHub().getEventMgr();
@@ -207,27 +224,24 @@ public ApiWeb3Aion(final IAionChain _ac) {
.maximumSize(1)
.refreshAfterWrite(OPS_RECENT_ENTITY_CACHE_TIME_SECONDS, TimeUnit.SECONDS)
.build(
- new CacheLoader() {
- public ChainHeadView load(Integer key) { // no checked exception
- ChainHeadView view = new ChainHeadView(OPS_RECENT_ENTITY_COUNT).update();
- return view;
- }
+ new CacheLoader<>() {
+ public ChainHeadView load(Integer key) { // no checked exception
+ return new ChainHeadView(OPS_RECENT_ENTITY_COUNT).update();
+ }
- public ListenableFuture reload(final Integer key, ChainHeadView prev) {
- try {
- ListenableFutureTask task = ListenableFutureTask.create(new Callable() {
- public ChainHeadView call() {
- return new ChainHeadView(prev).update();
- }
- });
- cacheUpdateExecutor.execute(task);
- return task;
- } catch (Throwable e) {
- LOG.debug(" reload(final Integer key,
+ ChainHeadView prev) {
+ try {
+ ListenableFutureTask task = ListenableFutureTask
+ .create(() -> new ChainHeadView(prev).update());
+ cacheUpdateExecutor.execute(task);
+ return task;
+ } catch (Throwable e) {
+ LOG.debug("(1), new CacheUpdateThreadFactory());
@@ -246,11 +260,8 @@ public MinerStatsView load(String key) { // no checked exception
public ListenableFuture reload(final String key, MinerStatsView prev) {
try {
- ListenableFutureTask task = ListenableFutureTask.create(new Callable() {
- public MinerStatsView call() {
- return new MinerStatsView(prev).update();
- }
- });
+ ListenableFutureTask task = ListenableFutureTask.create(
+ () -> new MinerStatsView(prev).update());
MinerStatsExecutor.execute(task);
return task;
} catch (Throwable e) {
@@ -271,7 +282,7 @@ public MinerStatsView call() {
/* Return a reference to the AIONBlock without converting values to hex
* Requied for the mining pool implementation
*/
- AionBlock getBlockRaw(int bn) {
+ private AionBlock getBlockRaw(int bn) {
// long bn = this.parseBnOrId(_bnOrId);
AionBlock nb = this.ac.getBlockchain().getBlockByNumber(bn);
if (nb == null) {
@@ -399,7 +410,7 @@ else if (_params instanceof JSONObject) {
Address address = new Address(_address);
String bnOrId = "latest";
- if (_bnOrId != null && !_bnOrId.equals(null))
+ if (_bnOrId != null)
bnOrId = _bnOrId + "";
if (!bnOrId.equalsIgnoreCase("latest")) {
@@ -437,7 +448,7 @@ else if (_params instanceof JSONObject) {
Address address = new Address(_address);
String bnOrId = "latest";
- if (_bnOrId != null && !_bnOrId.equals(null))
+ if (_bnOrId != null)
bnOrId = _bnOrId + "";
DataWord key;
@@ -486,7 +497,7 @@ else if (_params instanceof JSONObject) {
Address address = new Address(_address);
String bnOrId = "latest";
- if (_bnOrId != null && !_bnOrId.equals(null))
+ if (_bnOrId != null)
bnOrId = _bnOrId + "";
if (!bnOrId.equalsIgnoreCase("latest")) {
@@ -573,7 +584,7 @@ else if (_params instanceof JSONObject) {
Address address = new Address(_address);
String bnOrId = "latest";
- if (_bnOrId != null && !_bnOrId.equals(null))
+ if (_bnOrId != null)
bnOrId = _bnOrId + "";
if (!bnOrId.equalsIgnoreCase("latest")) {
@@ -684,7 +695,7 @@ else if (_params instanceof JSONObject) {
ArgTxCall txParams = ArgTxCall.fromJSON(_tx, getNrgOracle(), getDefaultNrgLimit());
String bnOrId = "latest";
- if (_bnOrId != null && !_bnOrId.equals(null))
+ if (_bnOrId != null)
bnOrId = _bnOrId + "";
Long bn = parseBnOrId(bnOrId);
@@ -1138,7 +1149,7 @@ else if (_params instanceof JSONObject) {
int duration = 300;
- if (_duration != null && !_duration.equals(null))
+ if (_duration != null)
duration = new BigInteger(_duration + "").intValueExact();
return new RpcMsg(unlockAccount(_account, _password, duration));
@@ -1517,8 +1528,6 @@ private static JSONObject configNet() {
p2p.put("errorTolerance", configP2p.getErrorTolerance());
p2p.put("maxActiveNodes", configP2p.getMaxActiveNodes());
p2p.put("maxTempNodes", configP2p.getMaxTempNodes());
- p2p.put("showLog", configP2p.getShowLog());
- p2p.put("showStatus", configP2p.getShowStatus());
// end
obj.put("p2p", p2p);
@@ -1698,7 +1707,6 @@ public ChainHeadView(int _qSize) {
}
private JSONObject getJson(AionBlock _b) {
- Map.Entry response;
BigInteger totalDiff = ac.getAionHub().getBlockStore().getTotalDifficultyForHash(_b.getHash());
return Blk.AionBlockOnlyToJson(_b, totalDiff);
}
@@ -1824,7 +1832,7 @@ private JSONObject computeMetrics() {
return metrics;
}
- public ChainHeadView update() {
+ ChainHeadView update() {
// get the latest head
AionBlock blk = getBestBlock();
@@ -1849,7 +1857,7 @@ public ChainHeadView update() {
" blkHash: " + TypeConverter.toJsonHex(blk.getHash()));
*/
- while(FastByteComparisons.equal(hashQueue.peekFirst(), blk.getParentHash()) == false
+ while(!FastByteComparisons.equal(hashQueue.peekFirst(), blk.getParentHash())
&& itr < qSize
&& blk.getNumber() > 2) {
@@ -1900,11 +1908,11 @@ public ChainHeadView update() {
return this;
}
- public JSONObject getResponse() {
+ JSONObject getResponse() {
return response;
}
- public long getViewBestBlock() {
+ long getViewBestBlock() {
return blkObjList.get(hashQueue.peekFirst()).getNumber();
}
}
@@ -2292,7 +2300,7 @@ public RpcMsg stratum_getHeaderByBlockNumber(Object _params) {
JSONObject obj = new JSONObject();
- if (_blockNum != null && !_blockNum.equals(null)) {
+ if (_blockNum != null) {
String bnStr = _blockNum + "";
try {
int bnInt = Integer.decode(bnStr);
@@ -2328,7 +2336,7 @@ private class MinerStatsView {
private int qSize;
private byte[] miner;
- public MinerStatsView(MinerStatsView cv) {
+ MinerStatsView(MinerStatsView cv) {
hashQueue = new LinkedList<>(cv.hashQueue);
blocks = new HashMap<>(cv.blocks);
response = new JSONObject(cv.response, JSONObject.getNames(cv.response));
@@ -2336,7 +2344,7 @@ public MinerStatsView(MinerStatsView cv) {
miner = cv.miner;
}
- public MinerStatsView(int _qSize, byte[] _miner) {
+ MinerStatsView(int _qSize, byte[] _miner) {
hashQueue = new LinkedList<>();
blocks = new HashMap<>();
response = new JSONObject();
@@ -2413,7 +2421,7 @@ private JSONObject buildResponse() {
return o;
}
- public MinerStatsView update() {
+ MinerStatsView update() {
// get the latest head
AionBlock blk = getBestBlock();
@@ -2440,7 +2448,7 @@ public MinerStatsView update() {
" blkHash: " + TypeConverter.toJsonHex(blk.getHash()));
*/
- while(FastByteComparisons.equal(hashQueue.peekFirst(), blk.getParentHash()) == false
+ while(!FastByteComparisons.equal(hashQueue.peekFirst(), blk.getParentHash())
&& itr < qSize
&& blk.getNumber() > 2) {
@@ -2485,7 +2493,7 @@ public MinerStatsView update() {
return this;
}
- public JSONObject getResponse() {
+ JSONObject getResponse() {
return response;
}
}
diff --git a/modApiServer/src/org/aion/api/server/nrgprice/strategy/NrgBlockPriceAveraging.java b/modApiServer/src/org/aion/api/server/nrgprice/strategy/NrgBlockPriceAveraging.java
index c6de9c1fb2..2f34be3ddb 100644
--- a/modApiServer/src/org/aion/api/server/nrgprice/strategy/NrgBlockPriceAveraging.java
+++ b/modApiServer/src/org/aion/api/server/nrgprice/strategy/NrgBlockPriceAveraging.java
@@ -27,6 +27,8 @@
* This class is NOT thread-safe
* Policy: holder class (NrgOracle) should provide any concurrency guarantees it needs to
*
+ * NOT TESTED. DON'T USE.
+ *
* @author ali sharif
*/
public class NrgBlockPriceAveraging extends NrgPriceAdvisor {
diff --git a/modApiServer/src/org/aion/api/server/pb/ApiAion0.java b/modApiServer/src/org/aion/api/server/pb/ApiAion0.java
index 17bd085601..a2ff8f9b4c 100644
--- a/modApiServer/src/org/aion/api/server/pb/ApiAion0.java
+++ b/modApiServer/src/org/aion/api/server/pb/ApiAion0.java
@@ -19,7 +19,7 @@
*
* Contributors:
* Aion foundation.
- *
+ *
******************************************************************************/
package org.aion.api.server.pb;
@@ -50,6 +50,7 @@
import org.aion.api.server.ApiUtil;
import org.aion.api.server.IApiAion;
import org.aion.api.server.pb.Message.Retcode;
+import org.aion.api.server.pb.Message.Servs;
import org.aion.api.server.types.ArgTxCall;
import org.aion.api.server.types.CompiledContr;
import org.aion.api.server.types.EvtContract;
@@ -96,16 +97,16 @@
@SuppressWarnings("Duplicates")
public class ApiAion0 extends ApiAion implements IApiAion {
- public final static byte JAVAAPI_VAR = 2;
- private final static int JAVAAPI_REQHEADER_LEN = 4;
- private final static int TX_HASH_LEN = 32;
- private final static int ACCOUNT_CREATE_LIMIT = 100;
+ public static final byte JAVAAPI_VAR = 2;
+ private static final int JAVAAPI_REQHEADER_LEN = 4;
+ private static final int TX_HASH_LEN = 32;
+ private static final int ACCOUNT_CREATE_LIMIT = 100;
private BlockingQueue pendingStatus;
private BlockingQueue txWait;
private Map> msgIdMapping;
- static public boolean heartBeatMsg(byte[] msg) {
+ public static boolean heartBeatMsg(byte[] msg) {
if (msg == null || msg.length != JAVAAPI_REQHEADER_LEN) {
return false;
}
@@ -129,34 +130,66 @@ protected void onBlock(AionBlockSummary cbs) {
} else {
List txrs = cbs.getReceipts();
if (fltr.getType() == Fltr.Type.EVENT
- && !Optional.ofNullable(txrs).orElse(Collections.emptyList()).isEmpty()) {
+ && !Optional.ofNullable(txrs).orElse(Collections.emptyList()).isEmpty()) {
FltrCt _fltr = (FltrCt) fltr;
for (AionTxReceipt txr : txrs) {
AionTransaction tx = txr.getTransaction();
- Address contractAddress = Optional.ofNullable(tx.getTo())
- .orElse(tx.getContractAddress());
+ Address contractAddress =
+ Optional.ofNullable(tx.getTo()).orElse(tx.getContractAddress());
Integer cnt = 0;
- txr.getLogInfoList().forEach(bi -> bi.getTopics().forEach(lg -> {
- if (_fltr.isFor(contractAddress, ByteUtil.toHexString(lg))) {
- IBlock blk = (cbs).getBlock();
- List txList = blk.getTransactionsList();
- int insideCnt = 0;
- for (AionTransaction t : txList) {
- if (Arrays.equals(t.getHash(), tx.getHash())) {
- break;
- }
- insideCnt++;
- }
-
- EvtContract ec = new EvtContract(bi.getAddress().toBytes(),
- bi.getData(), blk.getHash(), blk.getNumber(), cnt,
- ByteUtil.toHexString(lg), false, insideCnt, tx.getHash());
-
- _fltr.add(ec);
- }
- }));
+ txr.getLogInfoList()
+ .forEach(
+ bi ->
+ bi.getTopics()
+ .forEach(
+ lg -> {
+ if (_fltr.isFor(
+ contractAddress,
+ ByteUtil.toHexString(
+ lg))) {
+ IBlock
+ blk =
+ (cbs)
+ .getBlock();
+ List
+ txList =
+ blk
+ .getTransactionsList();
+ int insideCnt = 0;
+ for (AionTransaction t :
+ txList) {
+ if (Arrays.equals(
+ t.getHash(),
+ tx.getHash())) {
+ break;
+ }
+ insideCnt++;
+ }
+
+ EvtContract ec =
+ new EvtContract(
+ bi.getAddress()
+ .toBytes(),
+ bi
+ .getData(),
+ blk
+ .getHash(),
+ blk
+ .getNumber(),
+ cnt,
+ ByteUtil
+ .toHexString(
+ lg),
+ false,
+ insideCnt,
+ tx
+ .getHash());
+
+ _fltr.add(ec);
+ }
+ }));
}
}
}
@@ -164,41 +197,52 @@ protected void onBlock(AionBlockSummary cbs) {
}
protected void pendingTxReceived(ITransaction _tx) {
- installedFilters.values().forEach((f) -> {
- if (f.getType() == Fltr.Type.TRANSACTION) {
- f.add(new EvtTx(_tx));
- }
- });
+ installedFilters
+ .values()
+ .forEach(
+ (f) -> {
+ if (f.getType() == Fltr.Type.TRANSACTION) {
+ f.add(new EvtTx(_tx));
+ }
+ });
}
protected void pendingTxUpdate(ITxReceipt _txRcpt, EventTx.STATE _state) {
- ByteArrayWrapper txHashW = ByteArrayWrapper.wrap(
- ((AionTxReceipt) _txRcpt).getTransaction().getHash());
+ ByteArrayWrapper txHashW =
+ ByteArrayWrapper.wrap(((AionTxReceipt) _txRcpt).getTransaction().getHash());
if (LOG.isTraceEnabled()) {
- LOG.trace("ApiAion0.onPendingTransactionUpdate - txHash: [{}], state: [{}]", txHashW.toString(), _state.getValue());
+ LOG.trace(
+ "ApiAion0.onPendingTransactionUpdate - txHash: [{}], state: [{}]",
+ txHashW.toString(),
+ _state.getValue());
}
if (getMsgIdMapping().get(txHashW) != null) {
if (pendingStatus.remainingCapacity() == 0) {
pendingStatus.poll();
LOG.warn(
- "ApiAion0.onPendingTransactionUpdate - txPend ingStatus queue full, drop the first message.");
+ "ApiAion0.onPendingTransactionUpdate - txPend ingStatus queue full, drop the first message.");
}
if (LOG.isTraceEnabled()) {
- LOG.trace("ApiAion0.onPendingTransactionUpdate - the pending Tx state : [{}]", _state.getValue());
+ LOG.trace(
+ "ApiAion0.onPendingTransactionUpdate - the pending Tx state : [{}]",
+ _state.getValue());
}
- pendingStatus.add(new TxPendingStatus(txHashW,
+ pendingStatus.add(
+ new TxPendingStatus(
+ txHashW,
getMsgIdMapping().get(txHashW).getValue(),
getMsgIdMapping().get(txHashW).getKey(),
_state.getValue(),
- ByteArrayWrapper.wrap(((AionTxReceipt) _txRcpt).getExecutionResult() == null ? EMPTY_BYTE_ARRAY : ((AionTxReceipt) _txRcpt).getExecutionResult()),
+ ByteArrayWrapper.wrap(
+ ((AionTxReceipt) _txRcpt).getExecutionResult() == null
+ ? EMPTY_BYTE_ARRAY
+ : ((AionTxReceipt) _txRcpt).getExecutionResult()),
((AionTxReceipt) _txRcpt).getError()));
-
-
if (_state.isPending()) {
pendingReceipts.put(txHashW, ((AionTxReceipt) _txRcpt));
} else {
@@ -209,15 +253,19 @@ protected void pendingTxUpdate(ITxReceipt _txRcpt, EventTx.STATE _state) {
if (txWait.remainingCapacity() == 0) {
txWait.poll();
if (LOG.isTraceEnabled()) {
- LOG.trace("ApiAion0.onPendingTransactionUpdate - txWait queue full, drop the first message.");
+ LOG.trace(
+ "ApiAion0.onPendingTransactionUpdate - txWait queue full, drop the first message.");
}
}
// waiting origin Api call status been callback
try {
- txWait.put(new TxWaitingMappingUpdate(txHashW, _state.getValue(), ((AionTxReceipt) _txRcpt)));
+ txWait.put(
+ new TxWaitingMappingUpdate(
+ txHashW, _state.getValue(), ((AionTxReceipt) _txRcpt)));
} catch (InterruptedException e) {
- LOG.error("ApiAion0.onPendingTransactionUpdate txWait.put exception", e.getMessage());
+ LOG.error(
+ "ApiAion0.onPendingTransactionUpdate txWait.put exception", e.getMessage());
}
}
}
@@ -236,15 +284,18 @@ private void cacheBlock(AionBlockSummary cbs) {
private EventExecuteService eesBlkCache;
private final class EpBlkCache implements Runnable {
+
boolean go = true;
+
@Override
public void run() {
while (go) {
try {
IEvent e = eesBlkCache.take();
- if (e.getEventType() == IHandler.TYPE.BLOCK0.getValue() && e.getCallbackType() == EventBlock.CALLBACK.ONBLOCK0.getValue()) {
- cacheBlock((AionBlockSummary)e.getFuncArgs().get(0));
- } else if (e.getEventType() == IHandler.TYPE.POISONPILL.getValue()){
+ if (e.getEventType() == IHandler.TYPE.BLOCK0.getValue()
+ && e.getCallbackType() == EventBlock.CALLBACK.ONBLOCK0.getValue()) {
+ cacheBlock((AionBlockSummary) e.getFuncArgs().get(0));
+ } else if (e.getEventType() == IHandler.TYPE.POISONPILL.getValue()) {
go = false;
}
} catch (Exception e) {
@@ -264,21 +315,26 @@ public ApiAion0(IAionChain ac) {
this.txWait = new LinkedBlockingQueue(MAP_SIZE);
this.msgIdMapping = Collections.synchronizedMap(new LRUMap<>(MAP_SIZE, 100));
+ initNrgOracle(ac);
isFilterEnabled = CfgAion.inst().getApi().getZmq().isFiltersEnabled();
isBlkCacheEnabled = CfgAion.inst().getApi().getZmq().isBlockSummaryCacheEnabled();
if (isBlkCacheEnabled) {
- explorerBlockCache = Collections.synchronizedMap(new LRUMap<>(20)); // use the default loadfactor
- eesBlkCache = new EventExecuteService(100_000, "explorer-blk-cache", Thread.MIN_PRIORITY, LOG);
+ explorerBlockCache =
+ Collections.synchronizedMap(new LRUMap<>(20)); // use the default loadfactor
+ eesBlkCache =
+ new EventExecuteService(
+ 100_000, "explorer-blk-cache", Thread.MIN_PRIORITY, LOG);
Set eventSN = new HashSet<>();
int sn = IHandler.TYPE.BLOCK0.getValue() << 8;
eventSN.add(sn + EventBlock.CALLBACK.ONBLOCK0.getValue());
eesBlkCache.setFilter(eventSN);
eesBlkCache.start(new EpBlkCache());
- IHandler hdrBlk = this.ac.getAionHub().getEventMgr().getHandler(IHandler.TYPE.BLOCK0.getValue());
+ IHandler hdrBlk =
+ this.ac.getAionHub().getEventMgr().getHandler(IHandler.TYPE.BLOCK0.getValue());
if (hdrBlk != null) {
hdrBlk.eventCallback(new EventCallback(eesBlkCache, LOG));
}
@@ -287,13 +343,14 @@ public ApiAion0(IAionChain ac) {
if (isFilterEnabled) {
startES("EpApi");
- IHandler hdrTx = this.ac.getAionHub().getEventMgr().getHandler(IHandler.TYPE.TX0.getValue());
+ IHandler hdrTx =
+ this.ac.getAionHub().getEventMgr().getHandler(IHandler.TYPE.TX0.getValue());
if (hdrTx != null) {
hdrTx.eventCallback(new EventCallback(ees, LOG));
-
}
- IHandler hdrBlk = this.ac.getAionHub().getEventMgr().getHandler(IHandler.TYPE.BLOCK0.getValue());
+ IHandler hdrBlk =
+ this.ac.getAionHub().getEventMgr().getHandler(IHandler.TYPE.BLOCK0.getValue());
if (hdrBlk != null) {
hdrBlk.eventCallback(new EventCallback(ees, LOG));
}
@@ -307,174 +364,237 @@ public byte[] process(byte[] request, byte[] socketId) {
byte[] msgHash = ApiUtil.getApiMsgHash(request);
if (request[0] < this.getApiVersion()) {
- return msgHash == null ? ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_api_version_VALUE)
- : ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_api_version_VALUE, msgHash);
+ return msgHash == null
+ ? ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_api_version_VALUE)
+ : ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_api_version_VALUE, msgHash);
}
short service = (short) request[1];
switch ((short) request[2]) {
- // General Module
- case Message.Funcs.f_protocolVersion_VALUE: {
- if (service != Message.Servs.s_net_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
-
- // TODO : create query API for every module
- Message.rsp_protocolVersion rsp = Message.rsp_protocolVersion.newBuilder()
- .setApi(String.valueOf(this.getApiVersion())).setDb(AionHub.getRepoVersion())
- .setKernel(Version.KERNEL_VERSION).setMiner(EquihashMiner.VERSION)
- .setNet(this.p2pProtocolVersion())
- .setTxpool(this.ac.getAionHub().getPendingState().getVersion())
- .setVm("0.1.0").build();
-
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- }
- case Message.Funcs.f_minerAddress_VALUE: {
+ // General Module
+ case Message.Funcs.f_protocolVersion_VALUE: {
+ if (service != Message.Servs.s_net_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- if (service != Message.Servs.s_wallet_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
+ // TODO : create query API for every module
+ Message.rsp_protocolVersion rsp =
+ Message.rsp_protocolVersion
+ .newBuilder()
+ .setApi(String.valueOf(this.getApiVersion()))
+ .setDb(AionHub.getRepoVersion())
+ .setKernel(Version.KERNEL_VERSION)
+ .setMiner(EquihashMiner.VERSION)
+ .setNet(this.p2pProtocolVersion())
+ .setTxpool(this.ac.getAionHub().getPendingState().getVersion())
+ .setVm("0.1.0")
+ .build();
- String cb = this.getCoinbase();
- if (cb == null) {
- LOG.debug("ApiAion0.process.coinbase - null coinbase");
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_wallet_nullcb_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
}
+ case Message.Funcs.f_minerAddress_VALUE: {
+ if (service != Message.Servs.s_wallet_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- Message.rsp_minerAddress rsp = Message.rsp_minerAddress.newBuilder()
- .setMinerAddr(ByteString.copyFrom(TypeConverter.StringHexToByteArray(cb))).build();
-
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- }
+ String cb = this.getCoinbase();
+ if (cb == null) {
+ LOG.debug("ApiAion0.process.coinbase - null coinbase");
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_wallet_nullcb_VALUE);
+ }
- case Message.Funcs.f_contractDeploy_VALUE: {
+ Message.rsp_minerAddress rsp =
+ Message.rsp_minerAddress
+ .newBuilder()
+ .setMinerAddr(
+ ByteString.copyFrom(
+ TypeConverter.StringHexToByteArray(cb)))
+ .build();
- if (service != Message.Servs.s_tx_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE, msgHash);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
}
- Message.req_contractDeploy req;
- byte[] data = parseMsgReq(request, msgHash);
- ContractCreateResult result;
- try {
- req = Message.req_contractDeploy.parseFrom(data);
- // TODO: the client api should send server binary code directly
- // instead of str format like "0xhex".!
- byte[] bytes = req.getData().toByteArray();
- if (bytes == null || bytes.length <= 4) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_ct_bytecode_VALUE, msgHash);
+ case Message.Funcs.f_contractDeploy_VALUE: {
+ if (service != Message.Servs.s_tx_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE, msgHash);
}
- ArgTxCall params = new ArgTxCall(Address.wrap(req.getFrom().toByteArray()), null,
- Hex.decode(new String(bytes).substring(2)), BigInteger.ZERO, BigInteger.ZERO, req.getNrgLimit(),
- req.getNrgPrice());
-
- LOG.debug("ApiAion0.process.ContractDeploy - ArgsTxCall: [{}] ", params.toString());
-
- result = this.createContract(params);
+ Message.req_contractDeploy req;
+ byte[] data = parseMsgReq(request, msgHash);
+ ContractCreateResult result;
+ try {
+ req = Message.req_contractDeploy.parseFrom(data);
+ // TODO: the client api should send server binary code directly
+ // instead of str format like "0xhex".!
+ byte[] bytes = req.getData().toByteArray();
+ if (bytes == null || bytes.length <= 4) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_ct_bytecode_VALUE, msgHash);
+ }
- if (result != null) {
- getMsgIdMapping().put(ByteArrayWrapper.wrap(result.transId), new AbstractMap.SimpleEntry<>(
- ByteArrayWrapper.wrap(msgHash), ByteArrayWrapper.wrap(socketId)));
- if (LOG.isDebugEnabled()) {
- LOG.debug("ApiAion0.process.ContractDeploy - msgIdMapping.put: [{}] ", ByteArrayWrapper.wrap(result.transId).toString());
+ ArgTxCall params =
+ new ArgTxCall(
+ Address.wrap(req.getFrom().toByteArray()),
+ null,
+ Hex.decode(new String(bytes).substring(2)),
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ req.getNrgLimit(),
+ req.getNrgPrice());
+
+ LOG.debug(
+ "ApiAion0.process.ContractDeploy - ArgsTxCall: [{}] ",
+ params.toString());
+
+ result = this.createContract(params);
+
+ if (result != null) {
+ getMsgIdMapping()
+ .put(
+ ByteArrayWrapper.wrap(result.transId),
+ new AbstractMap.SimpleEntry<>(
+ ByteArrayWrapper.wrap(msgHash),
+ ByteArrayWrapper.wrap(socketId)));
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(
+ "ApiAion0.process.ContractDeploy - msgIdMapping.put: [{}] ",
+ ByteArrayWrapper.wrap(result.transId).toString());
+ }
}
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.ContractDeploy exception [{}] ", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE, msgHash);
}
- } catch (Exception e) {
- LOG.error("ApiAion0.process.ContractDeploy exception [{}] ", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE, msgHash);
- }
-
- Message.rsp_contractDeploy rsp = Message.rsp_contractDeploy.newBuilder()
- .setContractAddress(ByteString.copyFrom(result != null ? result.address.toBytes() : EMPTY_BYTE_ARRAY))
- .setTxHash(ByteString.copyFrom(result != null ? result.transId : EMPTY_BYTE_ARRAY)).build();
-
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_tx_Recved_VALUE, msgHash);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- }
- // Authenication Module
- case Message.Funcs.f_accounts_VALUE: {
+ Message.rsp_contractDeploy rsp =
+ Message.rsp_contractDeploy
+ .newBuilder()
+ .setContractAddress(
+ ByteString.copyFrom(
+ result != null
+ ? result.address.toBytes()
+ : EMPTY_BYTE_ARRAY))
+ .setTxHash(
+ ByteString.copyFrom(
+ result != null
+ ? result.transId
+ : EMPTY_BYTE_ARRAY))
+ .build();
- if (service != Message.Servs.s_wallet_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_tx_Recved_VALUE, msgHash);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
}
- // noinspection unchecked
- List accounts = this.getAccounts();
- ArrayList al = new ArrayList<>();
- for (String s : accounts) {
- al.add(ByteString.copyFrom(TypeConverter.StringHexToByteArray(s)));
- }
- Message.rsp_accounts rsp = Message.rsp_accounts.newBuilder().addAllAccout(al).build();
+ // Authenication Module
+ case Message.Funcs.f_accounts_VALUE: {
+ if (service != Message.Servs.s_wallet_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- }
- case Message.Funcs.f_blockNumber_VALUE: {
+ // noinspection unchecked
+ List accounts = this.getAccounts();
+ ArrayList al = new ArrayList<>();
+ for (String s : accounts) {
+ al.add(ByteString.copyFrom(TypeConverter.StringHexToByteArray(s)));
+ }
+ Message.rsp_accounts rsp =
+ Message.rsp_accounts.newBuilder().addAllAccout(al).build();
- if (service != Message.Servs.s_chain_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
}
+ case Message.Funcs.f_blockNumber_VALUE: {
+ if (service != Message.Servs.s_chain_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- Message.rsp_blockNumber rsp = Message.rsp_blockNumber.newBuilder()
- .setBlocknumber(this.getBestBlock().getNumber()).build();
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- }
- case Message.Funcs.f_unlockAccount_VALUE: {
-
- if (service != Message.Servs.s_wallet_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ Message.rsp_blockNumber rsp =
+ Message.rsp_blockNumber
+ .newBuilder()
+ .setBlocknumber(this.getBestBlock().getNumber())
+ .build();
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
}
+ case Message.Funcs.f_unlockAccount_VALUE: {
+ if (service != Message.Servs.s_wallet_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- boolean result;
- try {
- Message.req_unlockAccount req = Message.req_unlockAccount.parseFrom(data);
- result = this.unlockAccount(Address.wrap(req.getAccount().toByteArray()), req.getPassword(),
- req.getDuration());
- } catch (InvalidProtocolBufferException e) {
- LOG.error("ApiAion0.process.unlockAccount exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ byte[] data = parseMsgReq(request, msgHash);
+ boolean result;
+ try {
+ Message.req_unlockAccount req = Message.req_unlockAccount.parseFrom(data);
+ result =
+ this.unlockAccount(
+ Address.wrap(req.getAccount().toByteArray()),
+ req.getPassword(),
+ req.getDuration());
+ } catch (InvalidProtocolBufferException e) {
+ LOG.error("ApiAion0.process.unlockAccount exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
+
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, (byte) (result ? 0x01 : 0x00));
}
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, (byte) (result ? 0x01 : 0x00));
- }
+ // Transaction Module
+ case Message.Funcs.f_getBalance_VALUE: {
+ if (service != Message.Servs.s_chain_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- // Transaction Module
- case Message.Funcs.f_getBalance_VALUE: {
+ byte[] data = parseMsgReq(request, msgHash);
+ BigInteger balance;
+ try {
+ Message.req_getBalance req = Message.req_getBalance.parseFrom(data);
- if (service != Message.Servs.s_chain_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
+ Address addr = Address.wrap(req.getAddress().toByteArray());
- byte[] data = parseMsgReq(request, msgHash);
- BigInteger balance;
- try {
- Message.req_getBalance req = Message.req_getBalance.parseFrom(data);
+ balance = this.getBalance(addr);
+ } catch (InvalidProtocolBufferException e) {
+ LOG.error("ApiAion0.process.getbalance exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
- Address addr = Address.wrap(req.getAddress().toByteArray());
+ Message.rsp_getBalance rsp =
+ Message.rsp_getBalance
+ .newBuilder()
+ .setBalance(ByteString.copyFrom(balance.toByteArray()))
+ .build();
- balance = this.getBalance(addr);
- } catch (InvalidProtocolBufferException e) {
- LOG.error("ApiAion0.process.getbalance exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
}
-
- Message.rsp_getBalance rsp = Message.rsp_getBalance.newBuilder()
- .setBalance(ByteString.copyFrom(balance.toByteArray())).build();
-
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- }
case Message.Funcs.f_getNonce_VALUE: {
if (service != Message.Servs.s_chain_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Message.Retcode.r_fail_service_call_VALUE);
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Message.Retcode.r_fail_service_call_VALUE);
}
byte[] data = parseMsgReq(request, msgHash);
@@ -487,1334 +607,1831 @@ public byte[] process(byte[] request, byte[] socketId) {
nonce = this.getNonce(addr);
} catch (InvalidProtocolBufferException e) {
LOG.error("ApiAionA0.process.getNonce exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Message.Retcode.r_fail_function_exception_VALUE);
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Message.Retcode.r_fail_function_exception_VALUE);
}
- Message.rsp_getNonce rsp = Message.rsp_getNonce.newBuilder()
- .setNonce(ByteString.copyFrom(nonce.toByteArray())).build();
+ Message.rsp_getNonce rsp =
+ Message.rsp_getNonce
+ .newBuilder()
+ .setNonce(ByteString.copyFrom(nonce.toByteArray()))
+ .build();
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Message.Retcode.r_success_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(
+ getApiVersion(), Message.Retcode.r_success_VALUE);
return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
-
- }
- case Message.Funcs.f_compile_VALUE: {
-
- if (service != Message.Servs.s_tx_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
}
+ case Message.Funcs.f_getNrgPrice_VALUE: {
+ if (service != Servs.s_tx_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- try {
- Message.req_compileSolidity req = Message.req_compileSolidity.parseFrom(data);
- String source = req.getSource();
- if (source == null) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_null_compile_source_VALUE);
- }
-
- @SuppressWarnings("unchecked")
- Map _contrs = this.contract_compileSolidity(source);
- if (_contrs != null && !_contrs.isEmpty()) {
- Message.rsp_compile.Builder b = Message.rsp_compile.newBuilder();
-
- for (Entry entry : _contrs.entrySet()) {
- if (entry.getKey().contains("AionCompileError")) {
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(),
- Retcode.r_fail_compile_contract_VALUE);
- Message.t_Contract tc = Message.t_Contract.newBuilder().setError(entry.getValue().error)
- .build();
- return ApiUtil.combineRetMsg(retHeader,
- b.putConstracts(entry.getKey(), tc).build().toByteArray());
- }
-
- CompiledContr _contr = entry.getValue();
- JSONArray abi = new JSONArray();
- for (Abi.Entry f : _contr.info.abiDefinition) {
- abi.put(f.toJSON());
- }
+ long nrg = this.getRecommendedNrgPrice();
- Message.t_Contract tc = Message.t_Contract.newBuilder().setCode(_contr.code)
- .setAbiDef(ByteString.copyFrom(abi.toString().getBytes())).setSource(_contr.info.source)
- .build();
+ try {
+ Message.rsp_getNrgPrice rsp =
+ Message.rsp_getNrgPrice.newBuilder().setNrgPrice(nrg).build();
- b.putConstracts(entry.getKey(), tc);
- }
- Message.rsp_compile rsp = b.build();
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- } else {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ } catch (Exception e) {
+ LOG.error("ApiAion0.process.getNrgPrice exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
}
-
- } catch (InvalidProtocolBufferException e) {
- LOG.error("ApiAion0.process.compile exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_sendTransaction_VALUE: {
-
- if (service != Message.Servs.s_tx_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE, msgHash);
- }
-
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_sendTransaction req;
- byte[] result;
- try {
- req = Message.req_sendTransaction.parseFrom(data);
-
- ArgTxCall params = new ArgTxCall(Address.wrap(req.getFrom().toByteArray()),
- Address.wrap(req.getTo().toByteArray()), req.getData().toByteArray(),
- new BigInteger(req.getNonce().toByteArray()), new BigInteger(req.getValue().toByteArray()),
- req.getNrg(), req.getNrgPrice());
-
- result = this.sendTransaction(params);
- } catch (InvalidProtocolBufferException e) {
- LOG.error("ApiAion0.process.sendTransaction exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE, msgHash);
}
+ case Message.Funcs.f_compile_VALUE: {
+ if (service != Message.Servs.s_tx_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- if (result == null) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_sendTx_null_rep_VALUE, msgHash);
- }
+ byte[] data = parseMsgReq(request, msgHash);
+ try {
+ Message.req_compileSolidity req =
+ Message.req_compileSolidity.parseFrom(data);
+ String source = req.getSource();
+ if (source == null) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_null_compile_source_VALUE);
+ }
- getMsgIdMapping().put(ByteArrayWrapper.wrap(result), new AbstractMap.SimpleEntry<>(
- ByteArrayWrapper.wrap(msgHash), ByteArrayWrapper.wrap(socketId)));
- if (LOG.isDebugEnabled()) {
- LOG.debug("ApiAion0.process.sendTransaction - msgIdMapping.put: [{}]",
- ByteArrayWrapper.wrap(result).toString());
- }
+ @SuppressWarnings("unchecked")
+ Map _contrs = this.contract_compileSolidity(source);
+ if (_contrs != null && !_contrs.isEmpty()) {
+ Message.rsp_compile.Builder b = Message.rsp_compile.newBuilder();
+
+ for (Entry entry : _contrs.entrySet()) {
+ if (entry.getKey().contains("AionCompileError")) {
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(
+ getApiVersion(),
+ Retcode.r_fail_compile_contract_VALUE);
+ Message.t_Contract tc =
+ Message.t_Contract
+ .newBuilder()
+ .setError(entry.getValue().error)
+ .build();
+ return ApiUtil.combineRetMsg(
+ retHeader,
+ b.putConstracts(entry.getKey(), tc)
+ .build()
+ .toByteArray());
+ }
- Message.rsp_sendTransaction rsp = Message.rsp_sendTransaction.newBuilder()
- .setTxHash(ByteString.copyFrom(result)).build();
+ CompiledContr _contr = entry.getValue();
+ JSONArray abi = new JSONArray();
+ for (Abi.Entry f : _contr.info.abiDefinition) {
+ abi.put(f.toJSON());
+ }
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_tx_Recved_VALUE, msgHash);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- }
- case Message.Funcs.f_getCode_VALUE: {
- if (service != Message.Servs.s_tx_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
+ Message.t_Contract tc =
+ Message.t_Contract
+ .newBuilder()
+ .setCode(_contr.code)
+ .setAbiDef(
+ ByteString.copyFrom(
+ abi.toString().getBytes()))
+ .setSource(_contr.info.source)
+ .build();
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_getCode req;
- try {
- req = Message.req_getCode.parseFrom(data);
- Address to = Address.wrap(req.getAddress().toByteArray());
+ b.putConstracts(entry.getKey(), tc);
+ }
+ Message.rsp_compile rsp = b.build();
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ } else {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
- byte[] code = this.getCode(to);
- if (code == null) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_null_rsp_VALUE);
+ } catch (InvalidProtocolBufferException e) {
+ LOG.error("ApiAion0.process.compile exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
}
-
- Message.rsp_getCode rsp = Message.rsp_getCode.newBuilder().setCode(ByteString.copyFrom(code)).build();
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
-
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getCode exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_getTransactionReceipt_VALUE: {
- if (service != Message.Servs.s_tx_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
}
+ case Message.Funcs.f_sendTransaction_VALUE: {
+ if (service != Message.Servs.s_tx_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE, msgHash);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_getTransactionReceipt req;
- try {
- req = Message.req_getTransactionReceipt.parseFrom(data);
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_sendTransaction req;
+ byte[] result;
+ try {
+ req = Message.req_sendTransaction.parseFrom(data);
+
+ ArgTxCall params =
+ new ArgTxCall(
+ Address.wrap(req.getFrom().toByteArray()),
+ Address.wrap(req.getTo().toByteArray()),
+ req.getData().toByteArray(),
+ new BigInteger(req.getNonce().toByteArray()),
+ new BigInteger(req.getValue().toByteArray()),
+ req.getNrg(),
+ req.getNrgPrice());
+
+ result = this.sendTransaction(params);
+ } catch (InvalidProtocolBufferException e) {
+ LOG.error(
+ "ApiAion0.process.sendTransaction exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE, msgHash);
+ }
- TxRecpt result = this.getTransactionReceipt(req.getTxHash().toByteArray());
if (result == null) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_getTxReceipt_null_recp_VALUE);
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_sendTx_null_rep_VALUE, msgHash);
}
- List logs = new ArrayList<>();
- for (TxRecptLg log : result.logs) {
- List al = new ArrayList<>();
- Collections.addAll(al, log.topics);
-
- Message.t_LgEle msgLog = Message.t_LgEle.newBuilder()
- .setAddress(ByteString.copyFrom(Address.wrap(log.address).toBytes()))
- .setData(ByteString.copyFrom(ByteUtil.hexStringToBytes(log.data))).addAllTopics(al).build();
-
- logs.add(msgLog);
+ getMsgIdMapping()
+ .put(
+ ByteArrayWrapper.wrap(result),
+ new AbstractMap.SimpleEntry<>(
+ ByteArrayWrapper.wrap(msgHash),
+ ByteArrayWrapper.wrap(socketId)));
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(
+ "ApiAion0.process.sendTransaction - msgIdMapping.put: [{}]",
+ ByteArrayWrapper.wrap(result).toString());
}
- Message.rsp_getTransactionReceipt rsp = Message.rsp_getTransactionReceipt.newBuilder()
- .setFrom(ByteString.copyFrom(result.fromAddr.toBytes())).setBlockNumber(result.blockNumber)
- .setBlockHash(ByteString
- .copyFrom(result.blockHash != null ? ByteUtil.hexStringToBytes(result.blockHash)
- : EMPTY_BYTE_ARRAY))
- .setContractAddress(ByteString.copyFrom(
- result.contractAddress != null ? ByteUtil.hexStringToBytes(result.contractAddress)
- : EMPTY_BYTE_ARRAY))
- .setTxIndex(result.transactionIndex)
- .setTxHash(ByteString.copyFrom(
- result.transactionHash != null ? ByteUtil.hexStringToBytes(result.transactionHash)
- : EMPTY_BYTE_ARRAY))
- .setTo(ByteString
- .copyFrom(result.toAddr == null ? EMPTY_BYTE_ARRAY : result.toAddr.toBytes()))
- .setNrgConsumed(result.nrgUsed).setCumulativeNrgUsed(result.cumulativeNrgUsed).addAllLogs(logs)
+ Message.rsp_sendTransaction rsp =
+ Message.rsp_sendTransaction
+ .newBuilder()
+ .setTxHash(ByteString.copyFrom(result))
.build();
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_tx_Recved_VALUE, msgHash);
return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
-
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getTransactionReceipt exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_call_VALUE: {
- if (service != Message.Servs.s_tx_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
}
+ case Message.Funcs.f_getCode_VALUE: {
+ if (service != Message.Servs.s_tx_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_call req;
-
- try {
- req = Message.req_call.parseFrom(data);
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_getCode req;
+ try {
+ req = Message.req_getCode.parseFrom(data);
+ Address to = Address.wrap(req.getAddress().toByteArray());
- Address from = Address.wrap(req.getFrom().toByteArray());
- Address to = Address.wrap(req.getTo().toByteArray());
+ byte[] code = this.getCode(to);
+ if (code == null) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_null_rsp_VALUE);
+ }
- BigInteger value = new BigInteger(req.getValue().toByteArray());
- byte[] d = req.getData().toByteArray();
+ Message.rsp_getCode rsp =
+ Message.rsp_getCode
+ .newBuilder()
+ .setCode(ByteString.copyFrom(code))
+ .build();
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- ArgTxCall params = new ArgTxCall(from, to, d, BigInteger.ZERO, value, req.getNrg(), req.getNrgPrice());
- Message.rsp_call rsp = Message.rsp_call.newBuilder().setResult(ByteString.copyFrom(this.doCall(params)))
- .build();
+ } catch (Exception e) {
+ LOG.error("ApiAion0.process.getCode exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
+ }
+ case Message.Funcs.f_getTransactionReceipt_VALUE: {
+ if (service != Message.Servs.s_tx_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_getTransactionReceipt req;
+ try {
+ req = Message.req_getTransactionReceipt.parseFrom(data);
- } catch (Exception e) {
- LOG.error("ApiAion0.process.call exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_getBlockByNumber_VALUE: {
- if (service != Message.Servs.s_chain_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
+ TxRecpt result = this.getTransactionReceipt(req.getTxHash().toByteArray());
+ if (result == null) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_getTxReceipt_null_recp_VALUE);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_getBlockByNumber req;
+ List logs = new ArrayList<>();
+ for (TxRecptLg log : result.logs) {
+ List al = new ArrayList<>();
+ Collections.addAll(al, log.topics);
+
+ Message.t_LgEle msgLog =
+ Message.t_LgEle
+ .newBuilder()
+ .setAddress(
+ ByteString.copyFrom(
+ Address.wrap(log.address).toBytes()))
+ .setData(
+ ByteString.copyFrom(
+ ByteUtil.hexStringToBytes(log.data)))
+ .addAllTopics(al)
+ .build();
- try {
- req = Message.req_getBlockByNumber.parseFrom(data);
- long num = req.getBlockNumber();
- AionBlock blk = this.getBlock(num);
-
- return createBlockMsg(blk);
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getBlockByNumber exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_getBlockByHash_VALUE: {
- if (service != Message.Servs.s_chain_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
+ logs.add(msgLog);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_getBlockByHash req;
+ Message.rsp_getTransactionReceipt rsp =
+ Message.rsp_getTransactionReceipt
+ .newBuilder()
+ .setFrom(ByteString.copyFrom(result.fromAddr.toBytes()))
+ .setBlockNumber(result.blockNumber)
+ .setBlockHash(
+ ByteString.copyFrom(
+ result.blockHash != null
+ ? ByteUtil.hexStringToBytes(
+ result.blockHash)
+ : EMPTY_BYTE_ARRAY))
+ .setContractAddress(
+ ByteString.copyFrom(
+ result.contractAddress != null
+ ? ByteUtil.hexStringToBytes(
+ result.contractAddress)
+ : EMPTY_BYTE_ARRAY))
+ .setTxIndex(result.transactionIndex)
+ .setTxHash(
+ ByteString.copyFrom(
+ result.transactionHash != null
+ ? ByteUtil.hexStringToBytes(
+ result.transactionHash)
+ : EMPTY_BYTE_ARRAY))
+ .setTo(
+ ByteString.copyFrom(
+ result.toAddr == null
+ ? EMPTY_BYTE_ARRAY
+ : result.toAddr.toBytes()))
+ .setNrgConsumed(result.nrgUsed)
+ .setCumulativeNrgUsed(result.cumulativeNrgUsed)
+ .addAllLogs(logs)
+ .build();
- try {
- req = Message.req_getBlockByHash.parseFrom(data);
- byte[] hash = req.getBlockHash().toByteArray();
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- if (hash == null || hash.length != Hash256.BYTES) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getTransactionReceipt exception: [{}]",
+ e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
}
-
- AionBlock blk = this.getBlockByHash(hash);
- return createBlockMsg(blk);
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getBlockByHash exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_getTransactionByBlockHashAndIndex_VALUE: {
- if (service != Message.Servs.s_chain_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
}
+ case Message.Funcs.f_call_VALUE: {
+ if (service != Message.Servs.s_tx_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_getTransactionByBlockHashAndIndex req;
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_call req;
- try {
- req = Message.req_getTransactionByBlockHashAndIndex.parseFrom(data);
- long txIdx = req.getTxIndex();
- byte[] hash = req.getBlockHash().toByteArray();
+ try {
+ req = Message.req_call.parseFrom(data);
+
+ Address from = Address.wrap(req.getFrom().toByteArray());
+ Address to = Address.wrap(req.getTo().toByteArray());
+
+ BigInteger value = new BigInteger(req.getValue().toByteArray());
+ byte[] d = req.getData().toByteArray();
+
+ ArgTxCall params =
+ new ArgTxCall(
+ from,
+ to,
+ d,
+ BigInteger.ZERO,
+ value,
+ req.getNrg(),
+ req.getNrgPrice());
+ Message.rsp_call rsp =
+ Message.rsp_call
+ .newBuilder()
+ .setResult(ByteString.copyFrom(this.doCall(params)))
+ .build();
- if (txIdx < -1 || hash == null || hash.length != Hash256.BYTES) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
- }
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- AionTransaction tx = this.getTransactionByBlockHashAndIndex(hash, txIdx);
- if (tx == null) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_call_VALUE);
+ } catch (Exception e) {
+ LOG.error("ApiAion0.process.call exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
}
-
- Message.rsp_getTransaction rsp = getRsp_getTransaction(tx);
-
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getTransactionByBlockHashAndIndex exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_getTransactionByBlockNumberAndIndex_VALUE: {
- if (service != Message.Servs.s_chain_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
}
+ case Message.Funcs.f_getBlockByNumber_VALUE: {
+ if (service != Message.Servs.s_chain_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_getTransactionByBlockNumberAndIndex req;
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_getBlockByNumber req;
- try {
- req = Message.req_getTransactionByBlockNumberAndIndex.parseFrom(data);
- long blkNr = req.getBlockNumber();
- long txIdx = req.getTxIndex();
+ try {
+ req = Message.req_getBlockByNumber.parseFrom(data);
+ long num = req.getBlockNumber();
+ AionBlock blk = this.getBlock(num);
- if (blkNr < -1 || txIdx < -1) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ return createBlockMsg(blk);
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getBlockByNumber exception: [{}]",
+ e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
}
-
- AionTransaction tx = this.getTransactionByBlockNumberAndIndex(blkNr, txIdx);
- if (tx == null) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_call_VALUE);
+ }
+ case Message.Funcs.f_getBlockByHash_VALUE: {
+ if (service != Message.Servs.s_chain_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
}
- Message.rsp_getTransaction rsp = getRsp_getTransaction(tx);
-
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getTransactionByBlockNumberAndIndex exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_getBlockTransactionCountByNumber_VALUE: {
- if (service != Message.Servs.s_chain_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_getBlockByHash req;
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_getBlockTransactionCountByNumber req;
+ try {
+ req = Message.req_getBlockByHash.parseFrom(data);
+ byte[] hash = req.getBlockHash().toByteArray();
- try {
- req = Message.req_getBlockTransactionCountByNumber.parseFrom(data);
- long blkNr = req.getBlockNumber();
+ if (hash == null || hash.length != Hash256.BYTES) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ }
- if (blkNr < -1) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ AionBlock blk = this.getBlockByHash(hash);
+ return createBlockMsg(blk);
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getBlockByHash exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
}
-
- long cnt = this.getBlockTransactionCountByNumber(blkNr);
- if (cnt == -1) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_call_VALUE);
+ }
+ case Message.Funcs.f_getTransactionByBlockHashAndIndex_VALUE: {
+ if (service != Message.Servs.s_chain_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
}
- Message.rsp_getBlockTransactionCount rsp = Message.rsp_getBlockTransactionCount.newBuilder()
- .setTxCount((int) cnt).build();
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_getTransactionByBlockHashAndIndex req;
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getBlockTransactionCountByNumber exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_getTransactionCount_VALUE: {
- if (service != Message.Servs.s_chain_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
+ try {
+ req = Message.req_getTransactionByBlockHashAndIndex.parseFrom(data);
+ long txIdx = req.getTxIndex();
+ byte[] hash = req.getBlockHash().toByteArray();
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_getTransactionCount req;
+ if (txIdx < -1 || hash == null || hash.length != Hash256.BYTES) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ }
- try {
- req = Message.req_getTransactionCount.parseFrom(data);
- long blkNr = req.getBlocknumber();
- Address addr = Address.wrap(req.getAddress().toByteArray());
+ AionTransaction tx = this.getTransactionByBlockHashAndIndex(hash, txIdx);
+ if (tx == null) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_call_VALUE);
+ }
- if (blkNr < -1) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
- }
+ Message.rsp_getTransaction rsp = getRsp_getTransaction(tx);
- long cnt = this.getTransactionCount(addr, blkNr);
- if (cnt == -1) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_call_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getTransactionByBlockHashAndIndex exception: [{}]",
+ e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
+ }
+ case Message.Funcs.f_getTransactionByBlockNumberAndIndex_VALUE: {
+ if (service != Message.Servs.s_chain_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
}
- Message.rsp_getTransactionCount rsp = Message.rsp_getTransactionCount.newBuilder().setTxCount((int) cnt)
- .build();
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_getTransactionByBlockNumberAndIndex req;
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ try {
+ req = Message.req_getTransactionByBlockNumberAndIndex.parseFrom(data);
+ long blkNr = req.getBlockNumber();
+ long txIdx = req.getTxIndex();
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getTransactionCount exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_getBlockTransactionCountByHash_VALUE: {
- if (service != Message.Servs.s_chain_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
+ if (blkNr < -1 || txIdx < -1) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_getTransactionCountByHash req;
+ AionTransaction tx = this.getTransactionByBlockNumberAndIndex(blkNr, txIdx);
+ if (tx == null) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_call_VALUE);
+ }
- try {
- req = Message.req_getTransactionCountByHash.parseFrom(data);
- byte[] hash = req.getTxHash().toByteArray();
+ Message.rsp_getTransaction rsp = getRsp_getTransaction(tx);
- if (hash == null || hash.length != Hash256.BYTES) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getTransactionByBlockNumberAndIndex exception: [{}]",
+ e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
}
-
- long cnt = this.getTransactionCountByHash(hash);
- if (cnt == -1) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_call_VALUE);
+ }
+ case Message.Funcs.f_getBlockTransactionCountByNumber_VALUE: {
+ if (service != Message.Servs.s_chain_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
}
- Message.rsp_getTransactionCount rsp = Message.rsp_getTransactionCount.newBuilder().setTxCount((int) cnt)
- .build();
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_getBlockTransactionCountByNumber req;
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ try {
+ req = Message.req_getBlockTransactionCountByNumber.parseFrom(data);
+ long blkNr = req.getBlockNumber();
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getTransactionCount exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_getTransactionByHash_VALUE: {
- if (service != Message.Servs.s_chain_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
+ if (blkNr < -1) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_getTransactionByHash req;
+ long cnt = this.getBlockTransactionCountByNumber(blkNr);
+ if (cnt == -1) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_call_VALUE);
+ }
- try {
- req = Message.req_getTransactionByHash.parseFrom(data);
- byte[] txHash = req.getTxHash().toByteArray();
+ Message.rsp_getBlockTransactionCount rsp =
+ Message.rsp_getBlockTransactionCount
+ .newBuilder()
+ .setTxCount((int) cnt)
+ .build();
- if (txHash == null || txHash.length != this.getTxHashLen()) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getBlockTransactionCountByNumber exception: [{}]",
+ e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
}
-
- AionTransaction tx = this.getTransactionByHash(txHash);
- if (tx == null) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_call_VALUE);
+ }
+ case Message.Funcs.f_getTransactionCount_VALUE: {
+ if (service != Message.Servs.s_chain_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
}
- Message.rsp_getTransaction rsp = getRsp_getTransaction(tx);
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_getTransactionCount req;
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ try {
+ req = Message.req_getTransactionCount.parseFrom(data);
+ long blkNr = req.getBlocknumber();
+ Address addr = Address.wrap(req.getAddress().toByteArray());
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getTransactionCount exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
+ if (blkNr < -1) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ }
- case Message.Funcs.f_getActiveNodes_VALUE: {
- if (service != Message.Servs.s_net_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
+ long cnt = this.getTransactionCount(addr, blkNr);
+ if (cnt == -1) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_call_VALUE);
+ }
- List nodes = new ArrayList<>();
- nodes.addAll(this.ac.getAionHub().getP2pMgr().getActiveNodes().values());
- List pl = new ArrayList<>();
- try {
- for (INode n : nodes) {
- Message.t_Node node = Message.t_Node.newBuilder().setBlockNumber(n.getBestBlockNumber())
- .setNodeId(ByteArrayWrapper.wrap(n.getId()).toString())
- .setRemoteP2PIp(ByteArrayWrapper.wrap(n.getIp()).toString())
- // TODO : api export latency, totalDiff and the
- // blockHash
- // .setLatency((float) n.get)
+ Message.rsp_getTransactionCount rsp =
+ Message.rsp_getTransactionCount
+ .newBuilder()
+ .setTxCount((int) cnt)
.build();
- pl.add(node);
- }
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- Message.rsp_getActiveNodes rsp = Message.rsp_getActiveNodes.newBuilder().addAllNode(pl).build();
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getActiveNodes exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getTransactionCount exception: [{}]",
+ e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
}
- }
+ case Message.Funcs.f_getBlockTransactionCountByHash_VALUE: {
+ if (service != Message.Servs.s_chain_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- case Message.Funcs.f_getStaticNodes_VALUE: {
- if (service != Message.Servs.s_net_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
- List al = Arrays.asList(this.getBootNodes());
- List nl = new ArrayList<>();
- for (String s : al) {
- // TODO : get more node info
- Message.t_Node n = Message.t_Node.newBuilder().setRemoteP2PIp(s).build();
- nl.add(n);
- }
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_getTransactionCountByHash req;
- try {
- Message.rsp_getStaticNodes rsp = Message.rsp_getStaticNodes.newBuilder().addAllNode(nl).build();
+ try {
+ req = Message.req_getTransactionCountByHash.parseFrom(data);
+ byte[] hash = req.getTxHash().toByteArray();
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getStaticNodes exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_getSolcVersion_VALUE: {
- if (service != Message.Servs.s_tx_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
+ if (hash == null || hash.length != Hash256.BYTES) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ }
- String ver = this.solcVersion();
+ long cnt = this.getTransactionCountByHash(hash);
+ if (cnt == -1) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_call_VALUE);
+ }
- try {
- Message.rsp_getSolcVersion rsp = Message.rsp_getSolcVersion.newBuilder().setVer(ver).build();
+ Message.rsp_getTransactionCount rsp =
+ Message.rsp_getTransactionCount
+ .newBuilder()
+ .setTxCount((int) cnt)
+ .build();
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getSolcVersion exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_isSyncing_VALUE: {
- if (service != Message.Servs.s_net_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getTransactionCount exception: [{}]",
+ e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
}
+ case Message.Funcs.f_getTransactionByHash_VALUE: {
+ if (service != Message.Servs.s_chain_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- try {
- Message.rsp_isSyncing rsp = Message.rsp_isSyncing.newBuilder().setSyncing(!this.getSync().done).build();
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_getTransactionByHash req;
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- } catch (Exception e) {
- LOG.error("ApiAion0.process.syncing exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_syncInfo_VALUE: {
- if (service != Message.Servs.s_net_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
+ try {
+ req = Message.req_getTransactionByHash.parseFrom(data);
+ byte[] txHash = req.getTxHash().toByteArray();
- SyncInfo sync = this.getSync();
+ if (txHash == null || txHash.length != this.getTxHashLen()) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ }
- try {
- Message.rsp_syncInfo rsp = Message.rsp_syncInfo.newBuilder().setChainBestBlock(sync.chainBestBlkNumber)
- .setNetworkBestBlock(sync.networkBestBlkNumber).setSyncing(!sync.done)
- .setMaxImportBlocks(24).build();
+ AionTransaction tx = this.getTransactionByHash(txHash);
+ if (tx == null) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_call_VALUE);
+ }
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- } catch (Exception e) {
- LOG.error("ApiAion0.process.syncInfo exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_accountCreate_VALUE: {
- if (service != Message.Servs.s_account_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ Message.rsp_getTransaction rsp = getRsp_getTransaction(tx);
+
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getTransactionCount exception: [{}]",
+ e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
}
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_accountCreate req;
+ case Message.Funcs.f_getActiveNodes_VALUE: {
+ if (service != Message.Servs.s_net_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- try {
- req = Message.req_accountCreate.parseFrom(data);
-
- List addressList = new ArrayList<>();
- List pKeyList = new ArrayList<>();
- for (int i = 0; i < req.getPasswordList().size() && i < ACCOUNT_CREATE_LIMIT; i++) {
-
- String addr = Keystore.create(req.getPassword(i));
- byte[] pKey;
- if (req.getPrivateKey()) {
- pKey = Keystore.getKey(addr, req.getPassword(i)).getPrivKeyBytes();
- if (pKey == null) {
- pKey = ByteArrayWrapper.NULL_BYTE;
- }
+ List nodes = new ArrayList<>(
+ this.ac.getAionHub().getP2pMgr().getActiveNodes().values());
+ List pl = new ArrayList<>();
+ try {
+ for (INode n : nodes) {
+ Message.t_Node node =
+ Message.t_Node
+ .newBuilder()
+ .setBlockNumber(n.getBestBlockNumber())
+ .setNodeId(ByteArrayWrapper.wrap(n.getId()).toString())
+ .setRemoteP2PIp(
+ ByteArrayWrapper.wrap(n.getIp()).toString())
+ // TODO : api export latency, totalDiff and the
+ // blockHash
+ // .setLatency((float) n.get)
+ .build();
- pKeyList.add(ByteString.copyFrom(pKey));
+ pl.add(node);
}
- addressList.add(ByteString.copyFrom(Address.wrap(addr).toBytes()));
+ Message.rsp_getActiveNodes rsp =
+ Message.rsp_getActiveNodes.newBuilder().addAllNode(pl).build();
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getActiveNodes exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
}
+ }
- Message.rsp_accountCreate rsp = Message.rsp_accountCreate.newBuilder().addAllAddress(addressList)
- .addAllPrivateKey(pKeyList).build();
+ case Message.Funcs.f_getStaticNodes_VALUE: {
+ if (service != Message.Servs.s_net_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
+ String[] al = this.getBootNodes();
+ List nl = new ArrayList<>();
+ for (String s : al) {
+ // TODO : get more node info
+ Message.t_Node n = Message.t_Node.newBuilder().setRemoteP2PIp(s).build();
+ nl.add(n);
+ }
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ try {
+ Message.rsp_getStaticNodes rsp =
+ Message.rsp_getStaticNodes.newBuilder().addAllNode(nl).build();
- } catch (Exception e) {
- LOG.error("ApiAion0.process.accountCreate exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getStaticNodes exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
}
- }
+ case Message.Funcs.f_getSolcVersion_VALUE: {
+ if (service != Message.Servs.s_tx_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- case Message.Funcs.f_accountLock_VALUE: {
- if (service != Message.Servs.s_wallet_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
+ String ver = this.solcVersion();
- byte[] data = parseMsgReq(request, msgHash);
+ try {
+ Message.rsp_getSolcVersion rsp =
+ Message.rsp_getSolcVersion.newBuilder().setVer(ver).build();
- if (data == null) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getSolcVersion exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
}
+ case Message.Funcs.f_isSyncing_VALUE: {
+ if (service != Message.Servs.s_net_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- boolean result;
- try {
- Message.req_accountlock req = Message.req_accountlock.parseFrom(data);
- result = this.lockAccount(Address.wrap(req.getAccount().toByteArray()), req.getPassword());
- } catch (InvalidProtocolBufferException e) {
- LOG.error("ApiAion0.process.lockAccount exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ try {
+ Message.rsp_isSyncing rsp =
+ Message.rsp_isSyncing
+ .newBuilder()
+ .setSyncing(!this.getSync().done)
+ .build();
+
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ } catch (Exception e) {
+ LOG.error("ApiAion0.process.syncing exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
}
+ case Message.Funcs.f_syncInfo_VALUE: {
+ if (service != Message.Servs.s_net_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, (byte) (result ? 0x01 : 0x00));
- }
+ SyncInfo sync = this.getSync();
- case Message.Funcs.f_userPrivilege_VALUE: {
+ try {
+ Message.rsp_syncInfo rsp =
+ Message.rsp_syncInfo
+ .newBuilder()
+ .setChainBestBlock(sync.chainBestBlkNumber)
+ .setNetworkBestBlock(sync.networkBestBlkNumber)
+ .setSyncing(!sync.done)
+ .setMaxImportBlocks(24)
+ .build();
- if (service != Message.Servs.s_privilege_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ } catch (Exception e) {
+ LOG.error("ApiAion0.process.syncInfo exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
}
+ case Message.Funcs.f_accountCreate_VALUE: {
+ if (service != Message.Servs.s_account_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_unsupport_api_VALUE);
- }
- case Message.Funcs.f_mining_VALUE: {
- if (service != Message.Servs.s_mine_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_accountCreate req;
- Message.rsp_mining rsp = Message.rsp_mining.newBuilder().setMining(this.isMining()).build();
+ try {
+ req = Message.req_accountCreate.parseFrom(data);
+
+ List addressList = new ArrayList<>();
+ List pKeyList = new ArrayList<>();
+ for (int i = 0;
+ i < req.getPasswordList().size() && i < ACCOUNT_CREATE_LIMIT;
+ i++) {
+
+ String addr = Keystore.create(req.getPassword(i));
+ byte[] pKey;
+ if (req.getPrivateKey()) {
+ pKey = Keystore.getKey(addr, req.getPassword(i)).getPrivKeyBytes();
+ if (pKey == null) {
+ pKey = ByteArrayWrapper.NULL_BYTE;
+ }
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- }
+ pKeyList.add(ByteString.copyFrom(pKey));
+ }
- case Message.Funcs.f_estimateNrg_VALUE: {
- if (service != Message.Servs.s_tx_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE, msgHash);
- }
+ addressList.add(ByteString.copyFrom(Address.wrap(addr).toBytes()));
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_estimateNrg req;
- long result;
- try {
- req = Message.req_estimateNrg.parseFrom(data);
+ Message.rsp_accountCreate rsp =
+ Message.rsp_accountCreate
+ .newBuilder()
+ .addAllAddress(addressList)
+ .addAllPrivateKey(pKeyList)
+ .build();
- ArgTxCall params = new ArgTxCall(Address.wrap(req.getFrom().toByteArray()),
- Address.wrap(req.getTo().toByteArray()), req.getData().toByteArray(), BigInteger.ZERO,
- new BigInteger(req.getValue().toByteArray()), req.getNrg(), req.getNrgPrice());
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- result = this.estimateNrg(params);
- } catch (InvalidProtocolBufferException e) {
- LOG.error("ApiAion0.process.estimateNrg exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE, msgHash);
+ } catch (Exception e) {
+ LOG.error("ApiAion0.process.accountCreate exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
}
- Message.rsp_estimateNrg rsp = Message.rsp_estimateNrg.newBuilder().setNrg(result).build();
+ case Message.Funcs.f_accountLock_VALUE: {
+ if (service != Message.Servs.s_wallet_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- }
+ byte[] data = parseMsgReq(request, msgHash);
- case Message.Funcs.f_exportAccounts_VALUE:
- case Message.Funcs.f_backupAccounts_VALUE: {
- if (service != Message.Servs.s_account_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
- }
+ if (data == null) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_exportAccounts req;
+ boolean result;
+ try {
+ Message.req_accountlock req = Message.req_accountlock.parseFrom(data);
+ result =
+ this.lockAccount(
+ Address.wrap(req.getAccount().toByteArray()),
+ req.getPassword());
+ } catch (InvalidProtocolBufferException e) {
+ LOG.error("ApiAion0.process.lockAccount exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
- try {
- req = Message.req_exportAccounts.parseFrom(data);
- } catch (Exception e) {
- LOG.error("ApiAion0.process.exportAccounts exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, (byte) (result ? 0x01 : 0x00));
}
- Map addrMap = new HashMap<>();
- for (int i = 0; i < req.getKeyFileList().size() && i < ACCOUNT_CREATE_LIMIT; i++) {
- addrMap.put(Address.wrap(req.getKeyFile(i).getAddress().toByteArray()),
- req.getKeyFile(i).getPassword());
+ case Message.Funcs.f_userPrivilege_VALUE: {
+ if (service != Message.Servs.s_privilege_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
+
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_unsupport_api_VALUE);
}
+ case Message.Funcs.f_mining_VALUE: {
+ if (service != Message.Servs.s_mine_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- Map res = ((short) request[2] == Message.Funcs.f_exportAccounts_VALUE)
- ? Keystore.exportAccount(addrMap)
- : Keystore.backupAccount(addrMap);
+ Message.rsp_mining rsp =
+ Message.rsp_mining.newBuilder().setMining(this.isMining()).build();
- List invalidKey = addrMap.keySet().parallelStream()
- .filter(addr -> res.keySet().parallelStream().noneMatch(ad -> ad.equals(addr)))
- .map(match -> ByteString.copyFrom(match.toBytes())).collect(Collectors.toList());
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ }
- List keyBins = res.values().parallelStream().map(key -> ByteString.copyFrom(key.toBytes()))
- .collect(Collectors.toList());
+ case Message.Funcs.f_estimateNrg_VALUE: {
+ if (service != Message.Servs.s_tx_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE, msgHash);
+ }
- Message.rsp_exportAccounts rsp = Message.rsp_exportAccounts.newBuilder().addAllKeyFile(keyBins)
- .addAllFailedKey(invalidKey).build();
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_estimateNrg req;
+ long result;
+ try {
+ req = Message.req_estimateNrg.parseFrom(data);
+
+ ArgTxCall params =
+ new ArgTxCall(
+ Address.wrap(req.getFrom().toByteArray()),
+ Address.wrap(req.getTo().toByteArray()),
+ req.getData().toByteArray(),
+ BigInteger.ZERO,
+ new BigInteger(req.getValue().toByteArray()),
+ req.getNrg(),
+ req.getNrgPrice());
+
+ result = this.estimateNrg(params);
+ } catch (InvalidProtocolBufferException e) {
+ LOG.error("ApiAion0.process.estimateNrg exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE, msgHash);
+ }
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ Message.rsp_estimateNrg rsp =
+ Message.rsp_estimateNrg.newBuilder().setNrg(result).build();
- }
- case Message.Funcs.f_importAccounts_VALUE: {
- if (service != Message.Servs.s_account_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
}
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_importAccounts req;
+ case Message.Funcs.f_exportAccounts_VALUE:
+ case Message.Funcs.f_backupAccounts_VALUE: {
+ if (service != Message.Servs.s_account_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- try {
- req = Message.req_importAccounts.parseFrom(data);
- } catch (Exception e) {
- LOG.error("ApiAion0.process.importAccount exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_exportAccounts req;
- Map importKey = req.getPrivateKeyList().parallelStream()
- .collect(Collectors.toMap(Message.t_PrivateKey::getPrivateKey, Message.t_PrivateKey::getPassword));
+ try {
+ req = Message.req_exportAccounts.parseFrom(data);
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.exportAccounts exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
- if (importKey == null) {
- LOG.error("ApiAion0.process.importAccount exception: [null importKey]");
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
+ Map addrMap = new HashMap<>();
+ for (int i = 0;
+ i < req.getKeyFileList().size() && i < ACCOUNT_CREATE_LIMIT;
+ i++) {
+ addrMap.put(
+ Address.wrap(req.getKeyFile(i).getAddress().toByteArray()),
+ req.getKeyFile(i).getPassword());
+ }
- Set res = Keystore.importAccount(importKey);
- if (res == null) {
- throw new NullPointerException();
- }
+ Map res =
+ ((short) request[2] == Message.Funcs.f_exportAccounts_VALUE)
+ ? Keystore.exportAccount(addrMap)
+ : Keystore.backupAccount(addrMap);
- Message.rsp_importAccounts rsp = Message.rsp_importAccounts.newBuilder().addAllInvalidKey(res).build();
+ List invalidKey =
+ addrMap.keySet()
+ .parallelStream()
+ .filter(
+ addr ->
+ res.keySet()
+ .parallelStream()
+ .noneMatch(ad -> ad.equals(addr)))
+ .map(match -> ByteString.copyFrom(match.toBytes()))
+ .collect(Collectors.toList());
+
+ List keyBins =
+ res.values()
+ .parallelStream()
+ .map(key -> ByteString.copyFrom(key.toBytes()))
+ .collect(Collectors.toList());
+
+ Message.rsp_exportAccounts rsp =
+ Message.rsp_exportAccounts
+ .newBuilder()
+ .addAllKeyFile(keyBins)
+ .addAllFailedKey(invalidKey)
+ .build();
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- }
- case Message.Funcs.f_signedTransaction_VALUE:
- case Message.Funcs.f_rawTransaction_VALUE: {
- if (service != Message.Servs.s_tx_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE, msgHash);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
}
-
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_rawTransaction req;
- byte[] result;
- try {
- req = Message.req_rawTransaction.parseFrom(data);
- byte[] encodedTx = req.getEncodedTx().toByteArray();
- if (encodedTx == null) {
- LOG.error("ApiAion0.process.rawTransaction exception: [null encodedTx]");
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ case Message.Funcs.f_importAccounts_VALUE: {
+ if (service != Message.Servs.s_account_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
}
- result = this.sendTransaction(encodedTx);
- } catch (Exception e) {
- LOG.error("ApiAion0.process.rawTransaction exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE, msgHash);
- }
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_importAccounts req;
- if (result == null) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_sendTx_null_rep_VALUE, msgHash);
- }
+ try {
+ req = Message.req_importAccounts.parseFrom(data);
+ } catch (Exception e) {
+ LOG.error("ApiAion0.process.importAccount exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
- getMsgIdMapping().put(ByteArrayWrapper.wrap(result), new AbstractMap.SimpleEntry<>(
- ByteArrayWrapper.wrap(msgHash), ByteArrayWrapper.wrap(socketId)));
- if (LOG.isDebugEnabled()) {
- LOG.debug("ApiAion0.process.rawTransaction - msgIdMapping.put: [{}]", ByteArrayWrapper.wrap(result).toString());
- }
+ Map importKey =
+ req.getPrivateKeyList()
+ .parallelStream()
+ .collect(
+ Collectors.toMap(
+ Message.t_PrivateKey::getPrivateKey,
+ Message.t_PrivateKey::getPassword));
+
+ if (importKey == null) {
+ LOG.error("ApiAion0.process.importAccount exception: [null importKey]");
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
- Message.rsp_sendTransaction rsp = Message.rsp_sendTransaction.newBuilder()
- .setTxHash(ByteString.copyFrom(result)).build();
+ Set res = Keystore.importAccount(importKey);
+ if (res == null) {
+ throw new NullPointerException();
+ }
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_tx_Recved_VALUE, msgHash);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- }
- case Message.Funcs.f_eventRegister_VALUE: {
- if (service != Message.Servs.s_tx_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ Message.rsp_importAccounts rsp =
+ Message.rsp_importAccounts.newBuilder().addAllInvalidKey(res).build();
+
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
}
+ case Message.Funcs.f_signedTransaction_VALUE:
+ case Message.Funcs.f_rawTransaction_VALUE: {
+ if (service != Message.Servs.s_tx_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE, msgHash);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_eventRegister req;
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_rawTransaction req;
+ byte[] result;
+ try {
+ req = Message.req_rawTransaction.parseFrom(data);
+ byte[] encodedTx = req.getEncodedTx().toByteArray();
+ if (encodedTx == null) {
+ LOG.error(
+ "ApiAion0.process.rawTransaction exception: [null encodedTx]");
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ }
- try {
- req = Message.req_eventRegister.parseFrom(data);
+ result = this.sendTransaction(encodedTx);
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.rawTransaction exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE, msgHash);
+ }
- List evtList = new ArrayList<>(req.getEventsList());
- if (evtList.isEmpty()) {
- LOG.error("ApiNucoNcp.process.eventRegister : [{}]", "empty event list");
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ if (result == null) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_sendTx_null_rep_VALUE, msgHash);
}
- Message.t_FilterCt fltr = req.getFilter();
- List accList = new ArrayList<>();
- fltr.getAddressesList().forEach(a -> accList.add(a.toByteArray()));
+ getMsgIdMapping()
+ .put(
+ ByteArrayWrapper.wrap(result),
+ new AbstractMap.SimpleEntry<>(
+ ByteArrayWrapper.wrap(msgHash),
+ ByteArrayWrapper.wrap(socketId)));
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(
+ "ApiAion0.process.rawTransaction - msgIdMapping.put: [{}]",
+ ByteArrayWrapper.wrap(result).toString());
+ }
- long lv = ByteUtil.byteArrayToLong(socketId);
- FltrCt preFc = (FltrCt) installedFilters.get(lv);
- if (Optional.ofNullable(preFc).isPresent()) {
- preFc.getTopics().forEach(t -> {
- if (!fltr.getTopicsList().contains(t)) {
- evtList.add(t);
- }
- });
+ Message.rsp_sendTransaction rsp =
+ Message.rsp_sendTransaction
+ .newBuilder()
+ .setTxHash(ByteString.copyFrom(result))
+ .build();
+
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_tx_Recved_VALUE, msgHash);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ }
+ case Message.Funcs.f_eventRegister_VALUE: {
+ if (service != Message.Servs.s_tx_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
}
- FltrCt fc = new FltrCt(fltr.getContractAddr().toByteArray(), fltr.getTo(), fltr.getFrom(), evtList,
- accList, fltr.getExpireTime());
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_eventRegister req;
+
+ try {
+ req = Message.req_eventRegister.parseFrom(data);
+
+ List evtList = new ArrayList<>(req.getEventsList());
+ if (evtList.isEmpty()) {
+ LOG.error(
+ "ApiNucoNcp.process.eventRegister : [{}]", "empty event list");
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ }
- installedFilters.put(lv, fc);
+ Message.t_FilterCt fltr = req.getFilter();
+ List accList = new ArrayList<>();
+ fltr.getAddressesList().forEach(a -> accList.add(a.toByteArray()));
+
+ long lv = ByteUtil.byteArrayToLong(socketId);
+ FltrCt preFc = (FltrCt) installedFilters.get(lv);
+ if (Optional.ofNullable(preFc).isPresent()) {
+ preFc.getTopics()
+ .forEach(
+ t -> {
+ if (!fltr.getTopicsList().contains(t)) {
+ evtList.add(t);
+ }
+ });
+ }
- Message.rsp_eventRegister rsp = Message.rsp_eventRegister.newBuilder().setResult(true).build();
+ FltrCt fc =
+ new FltrCt(
+ fltr.getContractAddr().toByteArray(),
+ fltr.getTo(),
+ fltr.getFrom(),
+ evtList,
+ accList,
+ fltr.getExpireTime());
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ installedFilters.put(lv, fc);
- } catch (Exception e) {
- LOG.error("ApiAion0.process.eventRegister exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_eventDeregister_VALUE: {
- if (service != Message.Servs.s_tx_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ Message.rsp_eventRegister rsp =
+ Message.rsp_eventRegister.newBuilder().setResult(true).build();
+
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+
+ } catch (Exception e) {
+ LOG.error("ApiAion0.process.eventRegister exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
}
+ case Message.Funcs.f_eventDeregister_VALUE: {
+ if (service != Message.Servs.s_tx_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_eventDeregister req;
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_eventDeregister req;
- try {
- req = Message.req_eventDeregister.parseFrom(data);
+ try {
+ req = Message.req_eventDeregister.parseFrom(data);
- List evtList = new ArrayList<>(req.getEventsList());
+ List evtList = new ArrayList<>(req.getEventsList());
- byte[] conrtactAddr;
- if (req.getContractAddr() == null) {
- conrtactAddr = null;
- } else {
- conrtactAddr = req.getContractAddr().toByteArray();
- }
+ byte[] conrtactAddr;
+ if (req.getContractAddr() == null) {
+ conrtactAddr = null;
+ } else {
+ conrtactAddr = req.getContractAddr().toByteArray();
+ }
- if (evtList.isEmpty()) {
- LOG.error("ApiAion0.process.eventRegister : [{}]", "empty event list");
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
- }
+ if (evtList.isEmpty()) {
+ LOG.error("ApiAion0.process.eventRegister : [{}]", "empty event list");
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ }
- long lv = ByteUtil.byteArrayToLong(socketId);
- FltrCt preFc = (FltrCt) installedFilters.get(lv);
+ long lv = ByteUtil.byteArrayToLong(socketId);
+ FltrCt preFc = (FltrCt) installedFilters.get(lv);
- boolean changed = false;
- if (Optional.ofNullable(preFc).isPresent() && Arrays.equals(preFc.getContractAddr(), conrtactAddr)) {
- evtList.forEach(ev -> {
- if (preFc.getTopics().contains(ev)) {
- preFc.getTopics().remove(ev);
- }
- });
+ boolean changed = false;
+ if (Optional.ofNullable(preFc).isPresent()
+ && Arrays.equals(preFc.getContractAddr(), conrtactAddr)) {
+ evtList.forEach(
+ ev -> preFc.getTopics().remove(ev));
- installedFilters.put(lv, preFc);
- changed = true;
- }
+ installedFilters.put(lv, preFc);
+ changed = true;
+ }
- Message.rsp_eventRegister rsp = Message.rsp_eventRegister.newBuilder().setResult(changed).build();
+ Message.rsp_eventRegister rsp =
+ Message.rsp_eventRegister.newBuilder().setResult(changed).build();
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- } catch (Exception e) {
- LOG.error("ApiAion0.process.eventDeregister exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_getBlockDetailsByNumber_VALUE: {
- if (service != Message.Servs.s_admin_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.eventDeregister exception: [{}]", e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
}
+ case Message.Funcs.f_getBlockDetailsByNumber_VALUE: {
+ if (service != Message.Servs.s_admin_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_getBlockDetailsByNumber req;
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_getBlockDetailsByNumber req;
- try {
- req = Message.req_getBlockDetailsByNumber.parseFrom(data);
- long latestBlkNum = this.getBestBlock().getNumber();
+ try {
+ req = Message.req_getBlockDetailsByNumber.parseFrom(data);
+ long latestBlkNum = this.getBestBlock().getNumber();
- List blkNum = req.getBlkNumbersList()
- .parallelStream()
- .filter(n -> n <= latestBlkNum)
- .collect(Collectors.toSet())
+ List blkNum =
+ req.getBlkNumbersList()
+ .parallelStream()
+ .filter(n -> n <= latestBlkNum)
+ .collect(Collectors.toSet())
.parallelStream()
.sorted()
.collect(Collectors.toList());
- if (blkNum.size() > 1000) {
- blkNum = blkNum.subList(0, 1000);
- }
-
- List> blks = getBlkAndDifficultyForBlkNumList(blkNum);
+ if (blkNum.size() > 1000) {
+ blkNum = blkNum.subList(0, 1000);
+ }
- if (blks == null) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
- } else {
+ List> blks =
+ getBlkAndDifficultyForBlkNumList(blkNum);
+ if (blks == null) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ } else {
- List bds = getRsp_getBlockDetails(blks);
- Message.rsp_getBlockDetailsByNumber rsp = Message.rsp_getBlockDetailsByNumber.newBuilder()
- .addAllBlkDetails(bds)
- .build();
+ List bds = getRsp_getBlockDetails(blks);
+ Message.rsp_getBlockDetailsByNumber rsp =
+ Message.rsp_getBlockDetailsByNumber
+ .newBuilder()
+ .addAllBlkDetails(bds)
+ .build();
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ }
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getBlockDetailsByNumber exception: [{}]",
+ e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
}
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getBlockDetailsByNumber exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_getBlockSqlByRange_VALUE: {
- if (service != Message.Servs.s_admin_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
}
+ case Message.Funcs.f_getBlockSqlByRange_VALUE: {
+ if (service != Message.Servs.s_admin_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_getBlockSqlByRange req;
-
- try {
- if (LOG.isDebugEnabled()) LOG.debug("BlockSqlByRange: start");
-
- req = Message.req_getBlockSqlByRange.parseFrom(data);
- long latestBlkNum = this.getBestBlock().getNumber();
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_getBlockSqlByRange req;
- Long _blkStart = req.getBlkNumberStart();
- Long _blkEnd = req.getBlkNumberEnd();
+ try {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("BlockSqlByRange: start");
+ }
- // no null check here
+ req = Message.req_getBlockSqlByRange.parseFrom(data);
+ long latestBlkNum = this.getBestBlock().getNumber();
- long blkStart = -1;
- long blkEnd = -1;
+ Long _blkStart = req.getBlkNumberStart();
+ Long _blkEnd = req.getBlkNumberEnd();
- if (_blkStart < 0)
- blkStart = 0;
- else
- blkStart = _blkStart;
+ // no null check here
- if (_blkEnd > latestBlkNum)
- blkEnd = latestBlkNum;
- else
- blkEnd = _blkEnd;
+ long blkStart;
+ long blkEnd;
- if (blkEnd < blkStart)
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ if (_blkStart < 0) {
+ blkStart = 0;
+ } else {
+ blkStart = _blkStart;
+ }
- // truncate the thing
- if (blkEnd - blkStart > 1000) {
- blkStart = blkEnd - 1000 + 1;
+ if (_blkEnd > latestBlkNum) {
+ blkEnd = latestBlkNum;
+ } else {
+ blkEnd = _blkEnd;
+ }
- if (blkStart < 0) blkStart = 0;
- }
+ if (blkEnd < blkStart) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ }
- if (LOG.isDebugEnabled()) LOG.debug("BlockSqlByRange: range " + blkStart + "-" + blkEnd);
+ // truncate the thing
+ if (blkEnd - blkStart > 1000) {
+ blkStart = blkEnd - 1000 + 1;
- Long lastBlockTimestamp = null;
- long listLength = blkEnd - blkStart + 1;
- List bds = new ArrayList<>();
+ if (blkStart < 0) {
+ blkStart = 0;
+ }
+ }
- for (int i = 0; i < listLength; i++) {
- long blkNum = blkStart + i;
- Map.Entry entry = getBlockWithTotalDifficulty(blkNum);
- AionBlock b = entry.getKey();
- BigInteger td = entry.getValue();
- long blocktime = 0;
- if (blkNum != 0 && lastBlockTimestamp == null) {
- lastBlockTimestamp = getBlock(blkNum - 1).getTimestamp();
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("BlockSqlByRange: range " + blkStart + "-" + blkEnd);
}
- if (blkNum == 0)
- blocktime = 0;
- else
- blocktime = b.getTimestamp() - lastBlockTimestamp;
- lastBlockTimestamp = b.getTimestamp();
+ Long lastBlockTimestamp = null;
+ long listLength = blkEnd - blkStart + 1;
+ List bds = new ArrayList<>();
+
+ for (int i = 0; i < listLength; i++) {
+ long blkNum = blkStart + i;
+ Map.Entry entry =
+ getBlockWithTotalDifficulty(blkNum);
+ AionBlock b = entry.getKey();
+ BigInteger td = entry.getValue();
+ long blocktime;
+ if (blkNum != 0 && lastBlockTimestamp == null) {
+ lastBlockTimestamp = getBlock(blkNum - 1).getTimestamp();
+ }
+ if (blkNum == 0) {
+ blocktime = 0;
+ } else {
+ blocktime = b.getTimestamp() - lastBlockTimestamp;
+ }
- String blockSql = generateBlockSqlStatement(b, td, blocktime);
+ lastBlockTimestamp = b.getTimestamp();
- List transactionSql = new ArrayList<>();
+ String blockSql = generateBlockSqlStatement(b, td, blocktime);
- AionBlockSummary bs = null;
- if (explorerBlockCache != null) {
- // remove from cache since after consumed, we're probably not gonna revisit it
- bs = explorerBlockCache.remove(new ByteArrayWrapper(b.getHash()));
- }
+ List transactionSql = new ArrayList<>();
- if (bs != null) {
+ AionBlockSummary bs = null;
+ if (explorerBlockCache != null) {
+ // remove from cache since after consumed, we're probably not gonna
+ // revisit it
+ bs = explorerBlockCache.remove(new ByteArrayWrapper(b.getHash()));
+ }
- if (LOG.isDebugEnabled()) LOG.debug("BlockSqlByRange: cache HIT for #: " + b.getNumber());
+ if (bs != null) {
- Map receipts = new HashMap<>();
- for (AionTxReceipt r : bs.getReceipts()) {
- receipts.put(new ByteArrayWrapper(r.getTransaction().getHash()), r);
- }
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("BlockSqlByRange: cache HIT for #: " + b.getNumber());
+ }
- List txns = b.getTransactionsList();
- for (int j = 0; j < txns.size(); j++) {
- AionTransaction tx = txns.get(j);
- AionTxReceipt r = receipts.get(new ByteArrayWrapper(tx.getHash()));
- if (r == null) {
- if (LOG.isDebugEnabled()) LOG.debug("BlockSqlByRange: transaction not in Block Summary: " + b.getNumber() + "." + j);
- AionTxInfo ti = ((AionBlockchainImpl) this.ac.getAionHub().getBlockchain())
- .getTransactionInfoLite(tx.getHash(), b.getHash());
- r = ti.getReceipt();
+ Map receipts = new HashMap<>();
+ for (AionTxReceipt r : bs.getReceipts()) {
+ receipts.put(
+ new ByteArrayWrapper(r.getTransaction().getHash()), r);
}
- if (r == null) {
- LOG.error("BlockSqlByRange: missing DB transaction: " + ByteUtil.toHexString(tx.getHash()));
+
+ List txns = b.getTransactionsList();
+ for (int j = 0; j < txns.size(); j++) {
+ AionTransaction tx = txns.get(j);
+ AionTxReceipt r =
+ receipts.get(new ByteArrayWrapper(tx.getHash()));
+ if (r == null) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(
+ "BlockSqlByRange: transaction not in Block Summary: "
+ + b.getNumber()
+ + "."
+ + j);
+ }
+ AionTxInfo ti =
+ ((AionBlockchainImpl)
+ this.ac
+ .getAionHub()
+ .getBlockchain())
+ .getTransactionInfoLite(
+ tx.getHash(), b.getHash());
+ r = ti.getReceipt();
+ }
+ if (r == null) {
+ LOG.error(
+ "BlockSqlByRange: missing DB transaction: "
+ + ByteUtil.toHexString(tx.getHash()));
+ } else {
+ transactionSql.add(
+ generateTransactionSqlStatement(
+ b,
+ tx,
+ r.getLogInfoList(),
+ j,
+ r.getEnergyUsed()));
+ }
}
- else {
- transactionSql.add(generateTransactionSqlStatement(b, tx, r.getLogInfoList(), j, r.getEnergyUsed()));
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(
+ "BlockSqlByRange: cache MISS for #: " + b.getNumber());
}
+ List txs = b.getTransactionsList();
+
+ transactionSql =
+ txs.parallelStream()
+ .filter(Objects::nonNull)
+ .map(
+ (AionTransaction tx) -> {
+ AionTxInfo ti =
+ ((AionBlockchainImpl)
+ this.ac
+ .getAionHub()
+ .getBlockchain())
+ .getTransactionInfoLite(
+ tx.getHash(),
+ b.getHash());
+ if (ti == null) {
+ LOG.error(
+ "BlockSqlByRange: missing DB transaction: "
+ + ByteUtil
+ .toHexString(
+ tx
+ .getHash()));
+ return null;
+ } else {
+ return generateTransactionSqlStatement(
+ b,
+ tx,
+ ti.getReceipt()
+ .getLogInfoList(),
+ ti.getIndex(),
+ ti.getReceipt()
+ .getEnergyUsed());
+ }
+ })
+ .filter(Objects::nonNull)
+ .collect(Collectors.toList());
}
- } else {
- if (LOG.isDebugEnabled()) LOG.debug("BlockSqlByRange: cache MISS for #: " + b.getNumber());
- List txs = b.getTransactionsList();
-
- transactionSql = txs.parallelStream()
- .filter(Objects::nonNull)
- .map((AionTransaction tx) -> {
- AionTxInfo ti = ((AionBlockchainImpl) this.ac.getAionHub().getBlockchain())
- .getTransactionInfoLite(tx.getHash(), b.getHash());
- if (ti == null) {
- LOG.error("BlockSqlByRange: missing DB transaction: " + ByteUtil.toHexString(tx.getHash()));
- return null;
- } else {
- return generateTransactionSqlStatement(b, tx, ti.getReceipt().getLogInfoList(), ti.getIndex(), ti.getReceipt().getEnergyUsed());
- }
- }).filter(Objects::nonNull)
- .collect(Collectors.toList());
- }
- Message.t_BlockSql sqlObj =
- Message.t_BlockSql.newBuilder()
- .setBlockNumber(b.getNumber())
- .setBlockHash(ByteUtil.toHexString(b.getHash()))
- .setParentHash(ByteUtil.toHexString(b.getParentHash()))
- .setBlock(blockSql)
- .addAllTx(transactionSql)
- .build();
+ Message.t_BlockSql sqlObj =
+ Message.t_BlockSql
+ .newBuilder()
+ .setBlockNumber(b.getNumber())
+ .setBlockHash(ByteUtil.toHexString(b.getHash()))
+ .setParentHash(ByteUtil.toHexString(b.getParentHash()))
+ .setBlock(blockSql)
+ .addAllTx(transactionSql)
+ .build();
- bds.add(sqlObj);
- }
+ bds.add(sqlObj);
+ }
- Message.rsp_getBlockSqlByRange rsp =
- Message.rsp_getBlockSqlByRange.newBuilder()
- .addAllBlkSql(bds)
- .build();
+ Message.rsp_getBlockSqlByRange rsp =
+ Message.rsp_getBlockSqlByRange
+ .newBuilder()
+ .addAllBlkSql(bds)
+ .build();
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getBlockDetailsByNumber exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_getBlockDetailsByRange_VALUE: {
- if (service != Message.Servs.s_admin_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getBlockDetailsByNumber exception: [{}]",
+ e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
}
+ case Message.Funcs.f_getBlockDetailsByRange_VALUE: {
+ if (service != Message.Servs.s_admin_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_getBlockDetailsByRange req;
-
- try {
- if (LOG.isDebugEnabled()) LOG.debug("getBlockDetailsByRange: start");
-
- req = Message.req_getBlockDetailsByRange.parseFrom(data);
- long latestBlkNum = this.getBestBlock().getNumber();
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_getBlockDetailsByRange req;
- Long _blkStart = req.getBlkNumberStart();
- Long _blkEnd = req.getBlkNumberEnd();
+ try {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("getBlockDetailsByRange: start");
+ }
- // no null check here
+ req = Message.req_getBlockDetailsByRange.parseFrom(data);
+ long latestBlkNum = this.getBestBlock().getNumber();
- long blkStart = -1;
- long blkEnd = -1;
+ Long _blkStart = req.getBlkNumberStart();
+ Long _blkEnd = req.getBlkNumberEnd();
- if (_blkStart < 0)
- blkStart = 0;
- else
- blkStart = _blkStart;
+ // no null check here
- // blocks requested in the future. return empty result
- if (blkStart > latestBlkNum) {
- Message.rsp_getBlockDetailsByRange rsp =
- Message.rsp_getBlockDetailsByRange.newBuilder()
- .addAllBlkDetails(new ArrayList<>())
- .build();
+ long blkStart;
+ long blkEnd;
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- }
+ if (_blkStart < 0) {
+ blkStart = 0;
+ } else {
+ blkStart = _blkStart;
+ }
- if (_blkEnd > latestBlkNum)
- blkEnd = latestBlkNum;
- else
- blkEnd = _blkEnd;
+ // blocks requested in the future. return empty result
+ if (blkStart > latestBlkNum) {
+ Message.rsp_getBlockDetailsByRange rsp =
+ Message.rsp_getBlockDetailsByRange
+ .newBuilder()
+ .addAllBlkDetails(new ArrayList<>())
+ .build();
- if (blkEnd < blkStart)
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ }
- // truncate at the beginning of range
- if (blkEnd - blkStart > 1000) {
- blkStart = blkEnd - 1000 + 1;
+ if (_blkEnd > latestBlkNum) {
+ blkEnd = latestBlkNum;
+ } else {
+ blkEnd = _blkEnd;
+ }
- if (blkStart < 0) blkStart = 0;
- }
+ if (blkEnd < blkStart) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ }
- if (LOG.isDebugEnabled()) LOG.debug("getBlockDetailsByRange: range " + blkStart + "-" + blkEnd);
+ // truncate at the beginning of range
+ if (blkEnd - blkStart > 1000) {
+ blkStart = blkEnd - 1000 + 1;
- Long lastBlockTimestamp = null;
- long listLength = blkEnd - blkStart + 1;
- List bds = new ArrayList<>();
+ if (blkStart < 0) {
+ blkStart = 0;
+ }
+ }
- for (int i = 0; i < listLength; i++) {
- long blkNum = blkStart + i;
- Map.Entry entry = getBlockWithTotalDifficulty(blkNum);
- AionBlock b = entry.getKey();
- BigInteger td = entry.getValue();
- long blocktime = 0;
- if (b.getNumber() > 0 && lastBlockTimestamp == null)
- lastBlockTimestamp = getBlockByHash(b.getParentHash()).getTimestamp();
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("getBlockDetailsByRange: range " + blkStart + "-" + blkEnd);
+ }
- if (lastBlockTimestamp != null)
- blocktime = b.getTimestamp() - lastBlockTimestamp;
+ Long lastBlockTimestamp = null;
+ long listLength = blkEnd - blkStart + 1;
+ List bds = new ArrayList<>();
+
+ for (int i = 0; i < listLength; i++) {
+ long blkNum = blkStart + i;
+ Map.Entry entry =
+ getBlockWithTotalDifficulty(blkNum);
+ AionBlock b = entry.getKey();
+ BigInteger td = entry.getValue();
+ long blocktime = 0;
+ if (b.getNumber() > 0 && lastBlockTimestamp == null) {
+ lastBlockTimestamp =
+ getBlockByHash(b.getParentHash()).getTimestamp();
+ }
- lastBlockTimestamp = b.getTimestamp();
+ if (lastBlockTimestamp != null) {
+ blocktime = b.getTimestamp() - lastBlockTimestamp;
+ }
- Message.t_BlockDetail.Builder blockDetails = getBlockDetailsObj(b, td, blocktime);
+ lastBlockTimestamp = b.getTimestamp();
- List txDetails = new ArrayList<>();
+ Message.t_BlockDetail.Builder blockDetails =
+ getBlockDetailsObj(b, td, blocktime);
- AionBlockSummary bs = null;
- if (explorerBlockCache != null) {
- // remove from cache since after consumed, we're probably not gonna revisit it
- bs = explorerBlockCache.remove(new ByteArrayWrapper(b.getHash()));
- }
+ List txDetails = new ArrayList<>();
- if (bs != null) {
+ AionBlockSummary bs = null;
+ if (explorerBlockCache != null) {
+ // remove from cache since after consumed, we're probably not gonna
+ // revisit it
+ bs = explorerBlockCache.remove(new ByteArrayWrapper(b.getHash()));
+ }
- if (LOG.isDebugEnabled()) LOG.debug("getBlockDetailsByRange: cache HIT for #: " + b.getNumber());
+ if (bs != null) {
- Map receipts = new HashMap<>();
- for (AionTxReceipt r : bs.getReceipts()) {
- receipts.put(new ByteArrayWrapper(r.getTransaction().getHash()), r);
- }
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(
+ "getBlockDetailsByRange: cache HIT for #: "
+ + b.getNumber());
+ }
- List txns = b.getTransactionsList();
- for (int j = 0; j < txns.size(); j++) {
- AionTransaction tx = txns.get(j);
- AionTxReceipt r = receipts.get(new ByteArrayWrapper(tx.getHash()));
- if (r == null) {
- if (LOG.isDebugEnabled()) LOG.debug("getBlockDetailsByRange: transaction not in Block Summary: " + b.getNumber() + "." + j);
- AionTxInfo ti = ((AionBlockchainImpl) this.ac.getAionHub().getBlockchain())
- .getTransactionInfoLite(tx.getHash(), b.getHash());
- r = ti.getReceipt();
+ Map receipts = new HashMap<>();
+ for (AionTxReceipt r : bs.getReceipts()) {
+ receipts.put(
+ new ByteArrayWrapper(r.getTransaction().getHash()), r);
}
- if (r == null) {
- LOG.error("getBlockDetailsByRange: missing DB transaction: " + ByteUtil.toHexString(tx.getHash()));
+
+ List txns = b.getTransactionsList();
+ for (int j = 0; j < txns.size(); j++) {
+ AionTransaction tx = txns.get(j);
+ AionTxReceipt r =
+ receipts.get(new ByteArrayWrapper(tx.getHash()));
+ if (r == null) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(
+ "getBlockDetailsByRange: transaction not in Block Summary: "
+ + b.getNumber()
+ + "."
+ + j);
+ }
+ AionTxInfo ti =
+ ((AionBlockchainImpl)
+ this.ac
+ .getAionHub()
+ .getBlockchain())
+ .getTransactionInfoLite(
+ tx.getHash(), b.getHash());
+ r = ti.getReceipt();
+ }
+ if (r == null) {
+ LOG.error(
+ "getBlockDetailsByRange: missing DB transaction: "
+ + ByteUtil.toHexString(tx.getHash()));
+ } else {
+ txDetails.add(
+ getTxDetailsObj(
+ tx,
+ r.getLogInfoList(),
+ j,
+ r.getEnergyUsed(),
+ r.getError()));
+ }
}
- else {
- txDetails.add(getTxDetailsObj(tx, r.getLogInfoList(), j, r.getEnergyUsed(), r.getError()));
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(
+ "getBlockDetailsByRange: cache MISS for #: "
+ + b.getNumber());
}
+ List txs = b.getTransactionsList();
+
+ txDetails =
+ txs.parallelStream()
+ .filter(Objects::nonNull)
+ .map(
+ (AionTransaction tx) -> {
+ AionTxInfo ti =
+ ((AionBlockchainImpl)
+ this.ac
+ .getAionHub()
+ .getBlockchain())
+ .getTransactionInfoLite(
+ tx.getHash(),
+ b.getHash());
+ if (ti == null) {
+ LOG.error(
+ "getBlockDetailsByRange: missing DB transaction: "
+ + ByteUtil
+ .toHexString(
+ tx
+ .getHash()));
+ return null;
+ } else {
+ return getTxDetailsObj(
+ tx,
+ ti.getReceipt()
+ .getLogInfoList(),
+ ti.getIndex(),
+ ti.getReceipt()
+ .getEnergyUsed(),
+ ti.getReceipt().getError());
+ }
+ })
+ .filter(Objects::nonNull)
+ .collect(Collectors.toList());
}
- } else {
- if (LOG.isDebugEnabled()) LOG.debug("getBlockDetailsByRange: cache MISS for #: " + b.getNumber());
- List txs = b.getTransactionsList();
-
- txDetails = txs.parallelStream()
- .filter(Objects::nonNull)
- .map((AionTransaction tx) -> {
- AionTxInfo ti = ((AionBlockchainImpl) this.ac.getAionHub().getBlockchain())
- .getTransactionInfoLite(tx.getHash(), b.getHash());
- if (ti == null) {
- LOG.error("getBlockDetailsByRange: missing DB transaction: " + ByteUtil.toHexString(tx.getHash()));
- return null;
- } else {
- return getTxDetailsObj(tx, ti.getReceipt().getLogInfoList(), ti.getIndex(), ti.getReceipt().getEnergyUsed(), ti.getReceipt().getError());
- }
- }).filter(Objects::nonNull)
- .collect(Collectors.toList());
- }
- bds.add(blockDetails.addAllTx(txDetails).build());
- }
+ bds.add(blockDetails.addAllTx(txDetails).build());
+ }
- Message.rsp_getBlockDetailsByRange rsp =
- Message.rsp_getBlockDetailsByRange.newBuilder()
- .addAllBlkDetails(bds)
- .build();
+ Message.rsp_getBlockDetailsByRange rsp =
+ Message.rsp_getBlockDetailsByRange
+ .newBuilder()
+ .addAllBlkDetails(bds)
+ .build();
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getBlockDetailsByNumber exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_getBlockDetailsByLatest_VALUE: {
- if (service != Message.Servs.s_admin_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getBlockDetailsByNumber exception: [{}]",
+ e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
}
+ case Message.Funcs.f_getBlockDetailsByLatest_VALUE: {
+ if (service != Message.Servs.s_admin_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_getBlockDetailsByLatest req;
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_getBlockDetailsByLatest req;
- try {
- req = Message.req_getBlockDetailsByLatest.parseFrom(data);
+ try {
+ req = Message.req_getBlockDetailsByLatest.parseFrom(data);
- // clip the requested count up to 1000
- Long count = req.getCount();
- if (count > 1000) {
- count = 1000L;
- }
+ // clip the requested count up to 1000
+ Long count = req.getCount();
+ if (count > 1000) {
+ count = 1000L;
+ }
- // clip start block to 0 at the bottom
- Long endBlock = this.getBestBlock().getNumber();
- Long startBlock = (endBlock - count + 1) >= 0 ? (endBlock - count + 1) : 0;
+ // clip start block to 0 at the bottom
+ Long endBlock = this.getBestBlock().getNumber();
+ Long startBlock = (endBlock - count + 1) >= 0 ? (endBlock - count + 1) : 0;
- List blkNum = LongStream.rangeClosed(startBlock, endBlock)
- .boxed().collect(Collectors.toList());
+ List blkNum =
+ LongStream.rangeClosed(startBlock, endBlock)
+ .boxed()
+ .collect(Collectors.toList());
- List> blks = getBlkAndDifficultyForBlkNumList(blkNum);
+ List> blks =
+ getBlkAndDifficultyForBlkNumList(blkNum);
- if (blks == null) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
- } else {
- List bds = getRsp_getBlockDetails(blks);
- Message.rsp_getBlockDetailsByLatest rsp = Message.rsp_getBlockDetailsByLatest.newBuilder()
- .addAllBlkDetails(bds)
- .build();
+ if (blks == null) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ } else {
+ List bds = getRsp_getBlockDetails(blks);
+ Message.rsp_getBlockDetailsByLatest rsp =
+ Message.rsp_getBlockDetailsByLatest
+ .newBuilder()
+ .addAllBlkDetails(bds)
+ .build();
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ }
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getBlockDetailsByLatest exception: [{}]",
+ e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
}
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getBlockDetailsByLatest exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_getBlocksByLatest_VALUE: {
- if (service != Message.Servs.s_admin_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
}
+ case Message.Funcs.f_getBlocksByLatest_VALUE: {
+ if (service != Message.Servs.s_admin_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_getBlocksByLatest req;
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_getBlocksByLatest req;
- try {
- req = Message.req_getBlocksByLatest.parseFrom(data);
+ try {
+ req = Message.req_getBlocksByLatest.parseFrom(data);
- // clip the requested count up to 1000
- Long count = req.getCount();
- if (count > 1000) {
- count = 1000L;
- }
+ // clip the requested count up to 1000
+ Long count = req.getCount();
+ if (count > 1000) {
+ count = 1000L;
+ }
- // clip start block to 0 at the bottom
- Long endBlock = this.getBestBlock().getNumber();
- Long startBlock = (endBlock - count + 1) >= 0 ? (endBlock - count + 1) : 0;
+ // clip start block to 0 at the bottom
+ Long endBlock = this.getBestBlock().getNumber();
+ Long startBlock = (endBlock - count + 1) >= 0 ? (endBlock - count + 1) : 0;
- List blkNum = LongStream.rangeClosed(startBlock, endBlock)
- .boxed().collect(Collectors.toList());
+ List blkNum =
+ LongStream.rangeClosed(startBlock, endBlock)
+ .boxed()
+ .collect(Collectors.toList());
- List> blks = getBlkAndDifficultyForBlkNumList(blkNum);
+ List> blks =
+ getBlkAndDifficultyForBlkNumList(blkNum);
- if (blks == null) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
- } else {
- List bs = getRsp_getBlocks(blks);
- Message.rsp_getBlocksByLatest rsp = Message.rsp_getBlocksByLatest.newBuilder()
- .addAllBlks(bs)
- .build();
+ if (blks == null) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ } else {
+ List bs = getRsp_getBlocks(blks);
+ Message.rsp_getBlocksByLatest rsp =
+ Message.rsp_getBlocksByLatest
+ .newBuilder()
+ .addAllBlks(bs)
+ .build();
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ }
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getBlocksByLatest exception: [{}]",
+ e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
}
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getBlocksByLatest exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
- }
- }
- case Message.Funcs.f_getAccountDetailsByAddressList_VALUE: {
- if (service != Message.Servs.s_admin_VALUE) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_service_call_VALUE);
}
+ case Message.Funcs.f_getAccountDetailsByAddressList_VALUE: {
+ if (service != Message.Servs.s_admin_VALUE) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_service_call_VALUE);
+ }
- byte[] data = parseMsgReq(request, msgHash);
- Message.req_getAccountDetailsByAddressList req;
-
- try {
- req = Message.req_getAccountDetailsByAddressList.parseFrom(data);
- List num = req.getAddressesList();
+ byte[] data = parseMsgReq(request, msgHash);
+ Message.req_getAccountDetailsByAddressList req;
- if (num.size() > 1000) {
- num = num.subList(0, 1000);
- }
+ try {
+ req = Message.req_getAccountDetailsByAddressList.parseFrom(data);
+ List num = req.getAddressesList();
- List accounts = num.parallelStream()
- .map(a -> {
- BigInteger b = this.getBalance(Address.wrap(a.toByteArray()));
+ if (num.size() > 1000) {
+ num = num.subList(0, 1000);
+ }
- Message.t_AccountDetail.Builder builder = Message.t_AccountDetail.newBuilder();
- if (b != null)
- builder.setBalance(ByteString.copyFrom(b.toByteArray()));
+ List accounts =
+ num.parallelStream()
+ .map(
+ a -> {
+ BigInteger b =
+ this.getBalance(
+ Address.wrap(a.toByteArray()));
+
+ Message.t_AccountDetail.Builder builder =
+ Message.t_AccountDetail.newBuilder();
+ if (b != null) {
+ builder.setBalance(
+ ByteString.copyFrom(
+ b.toByteArray()));
+ }
- builder.setAddress(a);
+ builder.setAddress(a);
- return builder.build(); }
- ).collect(Collectors.toList());
+ return builder.build();
+ })
+ .collect(Collectors.toList());
- if (accounts == null) {
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
- }
+ if (accounts == null) {
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_arguments_VALUE);
+ }
- Message.rsp_getAccountDetailsByAddressList rsp = Message.rsp_getAccountDetailsByAddressList.newBuilder()
- .addAllAccounts(accounts)
- .build();
+ Message.rsp_getAccountDetailsByAddressList rsp =
+ Message.rsp_getAccountDetailsByAddressList
+ .newBuilder()
+ .addAllAccounts(accounts)
+ .build();
- byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
- return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
+ byte[] retHeader =
+ ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
+ return ApiUtil.combineRetMsg(retHeader, rsp.toByteArray());
- } catch (Exception e) {
- LOG.error("ApiAion0.process.getBlockDetailsByNumber exception: [{}]", e.getMessage());
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ } catch (Exception e) {
+ LOG.error(
+ "ApiAion0.process.getBlockDetailsByNumber exception: [{}]",
+ e.getMessage());
+ return ApiUtil.toReturnHeader(
+ getApiVersion(), Retcode.r_fail_function_exception_VALUE);
+ }
}
- }
- // case Message.Funcs.f_eventQuery_VALUE:
- // case Message.Funcs.f_submitWork_VALUE:
- // case Message.Funcs.f_getWork_VALUE:
- default:
- return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_call_VALUE);
+ // case Message.Funcs.f_eventQuery_VALUE:
+ // case Message.Funcs.f_submitWork_VALUE:
+ // case Message.Funcs.f_getWork_VALUE:
+ default:
+ return ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_fail_function_call_VALUE);
}
}
@@ -1828,11 +2445,14 @@ public void shutDown() {
eesBlkCache.shutdown();
}
}
- @Override public Map> getMsgIdMapping() {
+
+ @Override
+ public Map> getMsgIdMapping() {
return this.msgIdMapping;
}
- @Override public TxWaitingMappingUpdate takeTxWait() throws Throwable {
+ @Override
+ public TxWaitingMappingUpdate takeTxWait() throws Throwable {
return txWait.take();
}
@@ -1846,7 +2466,8 @@ private byte[] createBlockMsg(AionBlock blk) {
al.add(ByteString.copyFrom(tx.getHash()));
}
- BigInteger td = this.ac.getBlockchain().getTotalDifficultyByHash(Hash256.wrap(blk.getHash()));
+ BigInteger td =
+ this.ac.getBlockchain().getTotalDifficultyByHash(Hash256.wrap(blk.getHash()));
Message.rsp_getBlock rsp = getRsp_getBlock(blk, al, td);
byte[] retHeader = ApiUtil.toReturnHeader(getApiVersion(), Retcode.r_success_VALUE);
@@ -1855,118 +2476,142 @@ private byte[] createBlockMsg(AionBlock blk) {
}
private Message.rsp_getTransaction getRsp_getTransaction(AionTransaction tx) {
- return Message.rsp_getTransaction.newBuilder()
- .setBlockhash(ByteString.copyFrom(tx.getBlockHash()))
- .setBlocknumber(tx.getBlockNumber())
- .setFrom(ByteString.copyFrom(tx.getFrom().toBytes()))
- .setNrgConsume(tx.getNrgConsume())
- .setNrgPrice(tx.getNrgPrice())
- .setTxHash(ByteString.copyFrom(tx.getHash()))
- .setData(ByteString.copyFrom(tx.getData() == null ? EMPTY_BYTE_ARRAY : tx.getData()))
- .setNonce(ByteString.copyFrom(tx.getNonce()))
- .setTo(ByteString.copyFrom(tx.getTo() == null ? EMPTY_BYTE_ARRAY : tx.getTo().toBytes()))
- .setValue(ByteString.copyFrom(tx.getValue()))
- .setTxIndex((int)tx.getTxIndexInBlock())
- .setTimeStamp(ByteUtil.byteArrayToLong(tx.getTimeStamp()))
- .build();
+ return Message.rsp_getTransaction
+ .newBuilder()
+ .setBlockhash(ByteString.copyFrom(tx.getBlockHash()))
+ .setBlocknumber(tx.getBlockNumber())
+ .setFrom(ByteString.copyFrom(tx.getFrom().toBytes()))
+ .setNrgConsume(tx.getNrgConsume())
+ .setNrgPrice(tx.getNrgPrice())
+ .setTxHash(ByteString.copyFrom(tx.getHash()))
+ .setData(
+ ByteString.copyFrom(tx.getData() == null ? EMPTY_BYTE_ARRAY : tx.getData()))
+ .setNonce(ByteString.copyFrom(tx.getNonce()))
+ .setTo(
+ ByteString.copyFrom(
+ tx.getTo() == null ? EMPTY_BYTE_ARRAY : tx.getTo().toBytes()))
+ .setValue(ByteString.copyFrom(tx.getValue()))
+ .setTxIndex((int) tx.getTxIndexInBlock())
+ .setTimeStamp(ByteUtil.byteArrayToLong(tx.getTimeStamp()))
+ .build();
}
- private Message.rsp_getBlock getRsp_getBlock(AionBlock blk, List al, BigInteger td) {
- return Message.rsp_getBlock.newBuilder()
- .setParentHash(ByteString.copyFrom(blk.getParentHash()))
- .setMinerAddress(ByteString.copyFrom(blk.getCoinbase().toBytes()))
- .setStateRoot(ByteString.copyFrom(blk.getStateRoot()))
- .setTxTrieRoot(ByteString.copyFrom(blk.getTxTrieRoot()))
- .setDifficulty(ByteString.copyFrom(blk.getDifficulty()))
- .setExtraData(ByteString.copyFrom(blk.getExtraData()))
- .setNrgConsumed(blk.getNrgConsumed())
- .setNrgLimit(blk.getNrgLimit())
- .setHash(ByteString.copyFrom(blk.getHash()))
- .setLogsBloom(ByteString.copyFrom(blk.getLogBloom()))
- .setNonce(ByteString.copyFrom(blk.getNonce()))
- .setReceiptTrieRoot(ByteString.copyFrom(blk.getReceiptsRoot()))
- .setTimestamp(blk.getTimestamp()).setBlockNumber(blk.getNumber())
- .setSolution(ByteString.copyFrom(blk.getHeader().getSolution()))
- .addAllTxHash(al)
- .setSize(blk.size())
- .setTotalDifficulty(ByteString.copyFrom(td.toByteArray()))
- .build();
+ private Message.rsp_getBlock getRsp_getBlock(
+ AionBlock blk, List al, BigInteger td) {
+ return Message.rsp_getBlock
+ .newBuilder()
+ .setParentHash(ByteString.copyFrom(blk.getParentHash()))
+ .setMinerAddress(ByteString.copyFrom(blk.getCoinbase().toBytes()))
+ .setStateRoot(ByteString.copyFrom(blk.getStateRoot()))
+ .setTxTrieRoot(ByteString.copyFrom(blk.getTxTrieRoot()))
+ .setDifficulty(ByteString.copyFrom(blk.getDifficulty()))
+ .setExtraData(ByteString.copyFrom(blk.getExtraData()))
+ .setNrgConsumed(blk.getNrgConsumed())
+ .setNrgLimit(blk.getNrgLimit())
+ .setHash(ByteString.copyFrom(blk.getHash()))
+ .setLogsBloom(ByteString.copyFrom(blk.getLogBloom()))
+ .setNonce(ByteString.copyFrom(blk.getNonce()))
+ .setReceiptTrieRoot(ByteString.copyFrom(blk.getReceiptsRoot()))
+ .setTimestamp(blk.getTimestamp())
+ .setBlockNumber(blk.getNumber())
+ .setSolution(ByteString.copyFrom(blk.getHeader().getSolution()))
+ .addAllTxHash(al)
+ .setSize(blk.size())
+ .setTotalDifficulty(ByteString.copyFrom(td.toByteArray()))
+ .build();
}
private List getRsp_getBlocks(List> blks) {
- List bs = blks.parallelStream()
- .filter(Objects::nonNull)
- .map(blk -> {
- AionBlock b = blk.getKey();
- return Message.t_Block.newBuilder()
- .setBlockNumber(b.getNumber())
- .setDifficulty(ByteString.copyFrom(b.getDifficulty()))
- .setExtraData(ByteString.copyFrom(b.getExtraData()))
- .setHash(ByteString.copyFrom(b.getHash()))
- .setLogsBloom(ByteString.copyFrom(b.getLogBloom()))
- .setMinerAddress(ByteString.copyFrom(b.getCoinbase().toBytes()))
- .setNonce(ByteString.copyFrom(b.getNonce()))
- .setNrgConsumed(b.getNrgConsumed())
- .setNrgLimit(b.getNrgLimit())
- .setParentHash(ByteString.copyFrom(b.getParentHash()))
- .setTimestamp(b.getTimestamp())
- .setTxTrieRoot(ByteString.copyFrom(b.getTxTrieRoot()))
- .setReceiptTrieRoot(ByteString.copyFrom(b.getReceiptsRoot()))
- .setStateRoot(ByteString.copyFrom(b.getStateRoot()))
- .setSize(b.getEncoded().length)
- .setSolution(ByteString.copyFrom(b.getHeader().getSolution()))
- .setTotalDifficulty(ByteString.copyFrom(blk.getValue().toByteArray()))
- .build();
- }).collect(Collectors.toList());
+ return blks.parallelStream()
+ .filter(Objects::nonNull)
+ .map(
+ blk -> {
+ AionBlock b = blk.getKey();
- return bs;
+ return Message.t_Block
+ .newBuilder()
+ .setBlockNumber(b.getNumber())
+ .setDifficulty(ByteString.copyFrom(b.getDifficulty()))
+ .setExtraData(ByteString.copyFrom(b.getExtraData()))
+ .setHash(ByteString.copyFrom(b.getHash()))
+ .setLogsBloom(ByteString.copyFrom(b.getLogBloom()))
+ .setMinerAddress(
+ ByteString.copyFrom(b.getCoinbase().toBytes()))
+ .setNonce(ByteString.copyFrom(b.getNonce()))
+ .setNrgConsumed(b.getNrgConsumed())
+ .setNrgLimit(b.getNrgLimit())
+ .setParentHash(ByteString.copyFrom(b.getParentHash()))
+ .setTimestamp(b.getTimestamp())
+ .setTxTrieRoot(ByteString.copyFrom(b.getTxTrieRoot()))
+ .setReceiptTrieRoot(
+ ByteString.copyFrom(b.getReceiptsRoot()))
+ .setStateRoot(ByteString.copyFrom(b.getStateRoot()))
+ .setSize(b.getEncoded().length)
+ .setSolution(
+ ByteString.copyFrom(
+ b.getHeader().getSolution()))
+ .setTotalDifficulty(
+ ByteString.copyFrom(
+ blk.getValue().toByteArray()))
+ .build();
+ })
+ .collect(Collectors.toList());
}
- private Message.t_BlockDetail.Builder getBlockDetailsObj(AionBlock b, BigInteger td, long blocktime) {
-
- Message.t_BlockDetail.Builder builder = Message.t_BlockDetail.newBuilder()
- .setBlockNumber(b.getNumber())
- .setDifficulty(ByteString.copyFrom(b.getDifficulty()))
- .setExtraData(ByteString.copyFrom(b.getExtraData()))
- .setHash(ByteString.copyFrom(b.getHash()))
- .setLogsBloom(ByteString.copyFrom(b.getLogBloom()))
- .setMinerAddress(ByteString.copyFrom(b.getCoinbase().toBytes()))
- .setNonce(ByteString.copyFrom(b.getNonce()))
- .setNrgConsumed(b.getNrgConsumed())
- .setNrgLimit(b.getNrgLimit())
- .setParentHash(ByteString.copyFrom(b.getParentHash()))
- .setTimestamp(b.getTimestamp())
- .setTxTrieRoot(ByteString.copyFrom(b.getTxTrieRoot()))
- .setReceiptTrieRoot(ByteString.copyFrom(b.getReceiptsRoot()))
- .setStateRoot(ByteString.copyFrom(b.getStateRoot()))
- .setSize(b.getEncoded().length)
- .setSolution(ByteString.copyFrom(b.getHeader().getSolution()))
- .setTotalDifficulty(ByteString.copyFrom(td.toByteArray()))
- .setBlockTime(blocktime);
-
- return builder;
+ private Message.t_BlockDetail.Builder getBlockDetailsObj(
+ AionBlock b, BigInteger td, long blocktime) {
+
+ return Message.t_BlockDetail
+ .newBuilder()
+ .setBlockNumber(b.getNumber())
+ .setDifficulty(ByteString.copyFrom(b.getDifficulty()))
+ .setExtraData(ByteString.copyFrom(b.getExtraData()))
+ .setHash(ByteString.copyFrom(b.getHash()))
+ .setLogsBloom(ByteString.copyFrom(b.getLogBloom()))
+ .setMinerAddress(ByteString.copyFrom(b.getCoinbase().toBytes()))
+ .setNonce(ByteString.copyFrom(b.getNonce()))
+ .setNrgConsumed(b.getNrgConsumed())
+ .setNrgLimit(b.getNrgLimit())
+ .setParentHash(ByteString.copyFrom(b.getParentHash()))
+ .setTimestamp(b.getTimestamp())
+ .setTxTrieRoot(ByteString.copyFrom(b.getTxTrieRoot()))
+ .setReceiptTrieRoot(ByteString.copyFrom(b.getReceiptsRoot()))
+ .setStateRoot(ByteString.copyFrom(b.getStateRoot()))
+ .setSize(b.getEncoded().length)
+ .setSolution(ByteString.copyFrom(b.getHeader().getSolution()))
+ .setTotalDifficulty(ByteString.copyFrom(td.toByteArray()))
+ .setBlockTime(blocktime);
}
- private Message.t_TxDetail getTxDetailsObj(AionTransaction t, List _logs, int txIndex, long nrgConsumed, String error) {
+ private Message.t_TxDetail getTxDetailsObj(
+ AionTransaction t, List _logs, int txIndex, long nrgConsumed, String error) {
- List tles = _logs.parallelStream()
- .map(log -> {
- List topics = new ArrayList<>();
- for (int i = 0; i < log.getTopics().size(); i++) {
- topics.add(TypeConverter.toJsonHex(log.getTopics().get(i)));
- }
+ List tles =
+ _logs.parallelStream()
+ .map(
+ log -> {
+ List topics = new ArrayList<>();
+ for (int i = 0; i < log.getTopics().size(); i++) {
+ topics.add(TypeConverter.toJsonHex(log.getTopics().get(i)));
+ }
- return Message.t_LgEle.newBuilder()
+ return Message.t_LgEle
+ .newBuilder()
.setData(ByteString.copyFrom(log.getData()))
- .setAddress(ByteString.copyFrom(log.getAddress().toBytes()))
+ .setAddress(
+ ByteString.copyFrom(log.getAddress().toBytes()))
.addAllTopics(topics)
.build();
- }).filter(Objects::nonNull).collect(Collectors.toList());
+ })
+ .filter(Objects::nonNull)
+ .collect(Collectors.toList());
Address contract = t.getContractAddress();
- Message.t_TxDetail.Builder tdBuilder = Message.t_TxDetail.newBuilder()
+ Message.t_TxDetail.Builder tdBuilder =
+ Message.t_TxDetail
+ .newBuilder()
.setData(ByteString.copyFrom(t.getData()))
.setTo(ByteString.copyFrom(t.getTo().toBytes()))
.setFrom(ByteString.copyFrom(t.getFrom().toBytes()))
@@ -1980,14 +2625,13 @@ private Message.t_TxDetail getTxDetailsObj(AionTransaction t, List