Skip to content

Commit

Permalink
Merge pull request #846 from aionnetwork/rearchitect-repoenhance
Browse files Browse the repository at this point in the history
Small Refactoring in repo, trie and rlp
  • Loading branch information
AlexandraRoatis authored Mar 15, 2019
2 parents 0ff6e59 + 36f6f48 commit a743a9a
Show file tree
Hide file tree
Showing 7 changed files with 115 additions and 110 deletions.
2 changes: 1 addition & 1 deletion modAion/src/org/aion/zero/db/AionRepositoryCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public void flushTo(Repository other, boolean clearStateAfterFlush) {
ContractDetails ctd = entry.getValue();
// TODO: this functionality will be improved with the switch to a
// different ContractDetails implementation
if (ctd != null && ctd instanceof ContractDetailsCacheImpl) {
if (ctd instanceof ContractDetailsCacheImpl) {
ContractDetailsCacheImpl contractDetailsCache = (ContractDetailsCacheImpl) ctd;
contractDetailsCache.commit();

Expand Down
154 changes: 76 additions & 78 deletions modAionImpl/src/org/aion/zero/impl/AionBlockchainImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
import org.aion.vm.BulkExecutor;
import org.aion.vm.ExecutionBatch;
import org.aion.vm.PostExecutionWork;
import org.aion.vm.api.interfaces.IBloomFilter;
import org.aion.vm.exception.VMException;
import org.aion.zero.exceptions.HeaderStructureException;
import org.aion.zero.impl.blockchain.ChainConfiguration;
Expand Down Expand Up @@ -231,7 +232,6 @@ protected AionBlockchainImpl(

this.transactionStore = this.repository.getTransactionStore();


this.minerCoinbase = this.config.getMinerCoinbase();
if (minerCoinbase == null) {
LOG.warn("No miner Coinbase!");
Expand Down Expand Up @@ -645,38 +645,39 @@ && getBlockStore().isBlockExist(block.getHash())) {
if (ret.isSuccessful()) {
if (this.evtMgr != null) {

List<IEvent> evts = new ArrayList<>();
IEvent evtOnBlock = new EventBlock(EventBlock.CALLBACK.ONBLOCK0);
evtOnBlock.setFuncArgs(Collections.singletonList(summary));
this.evtMgr.newEvent(evtOnBlock);
evts.add(evtOnBlock);

IEvent evtTrace = new EventBlock(EventBlock.CALLBACK.ONTRACE0);
String str = String.format("Block chain size: [ %d ]", this.getSizeInternal());
evtTrace.setFuncArgs(Collections.singletonList(str));
this.evtMgr.newEvent(evtTrace);
evts.add(evtTrace);

if (ret == IMPORTED_BEST) {
if (LOG.isTraceEnabled()) {
LOG.trace("IMPORTED_BEST");
}
IEvent evtOnBest = new EventBlock(EventBlock.CALLBACK.ONBEST0);
evtOnBest.setFuncArgs(Arrays.asList(block, summary.getReceipts()));
this.evtMgr.newEvent(evtOnBest);
evts.add(evtOnBest);
}

this.evtMgr.newEvents(evts);
}
}

if (ret == IMPORTED_BEST) {
if (TX_LOG.isDebugEnabled()) {
if (summary != null) {
for (AionTxReceipt receipt : summary.getReceipts()) {
if (receipt != null) {
byte[] transactionHash = receipt.getTransaction().getTransactionHash();
TX_LOG.debug(
"Transaction: "
+ Hex.toHexString(transactionHash)
+ " was sealed into block #"
+ block.getNumber());
}
for (AionTxReceipt receipt : summary.getReceipts()) {
if (receipt != null) {
byte[] transactionHash = receipt.getTransaction().getTransactionHash();
TX_LOG.debug(
"Transaction: "
+ Hex.toHexString(transactionHash)
+ " was sealed into block #"
+ block.getNumber());
}
}
}
Expand Down Expand Up @@ -946,26 +947,23 @@ private boolean needFlushByMemory(double maxMemoryPercents) {
}

private static byte[] calcReceiptsTrie(List<AionTxReceipt> receipts) {
Trie receiptsTrie = new TrieImpl(null);

if (receipts == null || receipts.isEmpty()) {
return HashUtil.EMPTY_TRIE_HASH;
}

Trie receiptsTrie = new TrieImpl(null);
for (int i = 0; i < receipts.size(); i++) {
receiptsTrie.update(RLP.encodeInt(i), receipts.get(i).getReceiptTrieEncoded());
}
return receiptsTrie.getRootHash();
}

private byte[] calcLogBloom(List<AionTxReceipt> receipts) {

Bloom retBloomFilter = new Bloom();

private static byte[] calcLogBloom(List<AionTxReceipt> receipts) {
if (receipts == null || receipts.isEmpty()) {
return retBloomFilter.getBloomFilterBytes();
return new byte[IBloomFilter.SIZE];
}

Bloom retBloomFilter = new Bloom();
for (AionTxReceipt receipt : receipts) {
retBloomFilter.or(receipt.getBloomFilter());
}
Expand Down Expand Up @@ -1117,10 +1115,7 @@ private AionBlockSummary processBlock(AionBlock block) {
return applyBlock(block);
} else {
return new AionBlockSummary(
block,
new HashMap<Address, BigInteger>(),
new ArrayList<AionTxReceipt>(),
new ArrayList<AionTxExecSummary>());
block, new HashMap<>(), new ArrayList<>(), new ArrayList<>());
}
}

Expand All @@ -1138,35 +1133,37 @@ private RetValidPreBlock generatePreBlock(IAionBlock block) {
List<AionTxExecSummary> summaries = new ArrayList<>();
List<AionTransaction> transactions = new ArrayList<>();

ExecutionBatch batch = new ExecutionBatch(block, block.getTransactionsList());
BulkExecutor executor =
new BulkExecutor(
batch,
repository,
track,
false,
true,
block.getNrgLimit(),
LOGGER_VM,
getPostExecutionWorkForGeneratePreBlock());

List<AionTxExecSummary> executionSummaries = null;
try {
executionSummaries = executor.execute();
} catch (VMException e) {
LOG.error("Shutdown due to a VM fatal error.", e);
System.exit(-1);
}
if (!block.getTransactionsList().isEmpty()) {
ExecutionBatch batch = new ExecutionBatch(block, block.getTransactionsList());
BulkExecutor executor =
new BulkExecutor(
batch,
repository,
track,
false,
true,
block.getNrgLimit(),
LOGGER_VM,
getPostExecutionWorkForGeneratePreBlock());

List<AionTxExecSummary> executionSummaries = null;
try {
executionSummaries = executor.execute();
} catch (VMException e) {
LOG.error("Shutdown due to a VM fatal error.", e);
System.exit(-1);
}

for (AionTxExecSummary summary : executionSummaries) {
if (!summary.isRejected()) {
transactions.add(summary.getTransaction());
receipts.add(summary.getReceipt());
summaries.add(summary);
for (AionTxExecSummary summary : executionSummaries) {
if (!summary.isRejected()) {
transactions.add(summary.getTransaction());
receipts.add(summary.getReceipt());
summaries.add(summary);
}
}
}

Map<Address, BigInteger> rewards = addReward(block, summaries);
Map<Address, BigInteger> rewards = addReward(block);

track.flush();

Expand Down Expand Up @@ -1209,31 +1206,33 @@ private AionBlockSummary applyBlock(IAionBlock block) {
List<AionTxReceipt> receipts = new ArrayList<>();
List<AionTxExecSummary> summaries = new ArrayList<>();

ExecutionBatch batch = new ExecutionBatch(block, block.getTransactionsList());
BulkExecutor executor =
new BulkExecutor(
batch,
repository,
track,
false,
true,
block.getNrgLimit(),
LOGGER_VM,
getPostExecutionWorkForApplyBlock());

List<AionTxExecSummary> executionSummaries = null;
try {
executionSummaries = executor.execute();
} catch (VMException e) {
LOG.error("Shutdown due to a VM fatal error.", e);
System.exit(-1);
}
if (!block.getTransactionsList().isEmpty()) {
ExecutionBatch batch = new ExecutionBatch(block, block.getTransactionsList());
BulkExecutor executor =
new BulkExecutor(
batch,
repository,
track,
false,
true,
block.getNrgLimit(),
LOGGER_VM,
getPostExecutionWorkForApplyBlock());

List<AionTxExecSummary> executionSummaries = null;
try {
executionSummaries = executor.execute();
} catch (VMException e) {
LOG.error("Shutdown due to a VM fatal error.", e);
System.exit(-1);
}

for (AionTxExecSummary summary : executionSummaries) {
receipts.add(summary.getReceipt());
summaries.add(summary);
for (AionTxExecSummary summary : executionSummaries) {
receipts.add(summary.getReceipt());
summaries.add(summary);
}
}
Map<Address, BigInteger> rewards = addReward(block, summaries);
Map<Address, BigInteger> rewards = addReward(block);

long totalTime = System.nanoTime() - saveTime;
chainStats.addBlockExecTime(totalTime);
Expand Down Expand Up @@ -1266,8 +1265,7 @@ private static PostExecutionWork getPostExecutionWorkForApplyBlock() {
*
* @param block object containing the header and uncles
*/
private Map<Address, BigInteger> addReward(
IAionBlock block, List<AionTxExecSummary> summaries) {
private Map<Address, BigInteger> addReward(IAionBlock block) {

Map<Address, BigInteger> rewards = new HashMap<>();
BigInteger minerReward =
Expand Down Expand Up @@ -1311,14 +1309,13 @@ public synchronized void storeBlock(AionBlock block, List<AionTxReceipt> receipt

repository.commitBlock(block.getHeader());

if (LOG.isDebugEnabled())
if (LOG.isDebugEnabled()) {
LOG.debug(
"Block saved: number: {}, hash: {}, TD: {}",
block.getNumber(),
block.getShortHash(),
totalDifficulty);

if (LOG.isDebugEnabled()) {
LOG.debug("block added to the blockChain: index: [{}]", block.getNumber());
}

Expand Down Expand Up @@ -1539,7 +1536,8 @@ private byte[] getStartHash(long blockNumber, int qty) {
// * @return {@link A0BlockHeader}'s list or empty list if none found
// */
// @Override
// public List<A0BlockHeader> getListOfHeadersStartFrom(BlockIdentifierImpl identifier, int skip,
// public List<A0BlockHeader> getListOfHeadersStartFrom(BlockIdentifierImpl identifier, int
// skip,
// int limit,
// boolean reverse) {
//
Expand Down
7 changes: 4 additions & 3 deletions modMcf/src/org/aion/mcf/trie/TrieImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,10 @@ public void update(byte[] key, byte[] value) {
if (value.length == 0) {
throw new IllegalArgumentException("The value should not be empty.");
}
synchronized (cache) {
byte[] k = binToNibbles(key);

byte[] k = binToNibbles(key);

synchronized (cache) {
if (isEmptyNode(root)) {
cache.markRemoved(getRootHash());
}
Expand Down Expand Up @@ -466,7 +467,7 @@ private Object putToCache(Object node) {
return this.cache.put(node);
}

private boolean isEmptyNode(Object node) {
private static boolean isEmptyNode(Object node) {
Value n = new Value(node);
return (node == null
|| (n.isString() && (n.asString().isEmpty() || n.get(0).isNull()))
Expand Down
4 changes: 2 additions & 2 deletions modMcf/src/org/aion/mcf/vm/types/Bloom.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
/** Utility class for creating/operating bloom. */
public class Bloom implements IBloomFilter {

public byte[] data = new byte[256];
public byte[] data = new byte[IBloomFilter.SIZE];

public Bloom() {}

Expand All @@ -24,7 +24,7 @@ public static Bloom create(byte[] toBloom) {
int mov3 = (((toBloom[4] & 0xff) & 7) << 8) + ((toBloom[5]) & 0xff);

// # bits: 8 * 256 = 2048
byte[] data = new byte[256];
byte[] data = new byte[IBloomFilter.SIZE];
Bloom bloom = new Bloom(data);

ByteUtil.setBit(data, mov1, 1);
Expand Down
22 changes: 13 additions & 9 deletions modRlp/src/main/java/org/aion/rlp/RLP.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ public class RLP {
*/
private static final int OFFSET_LONG_LIST = 0xf7;

private static final byte[] BYTES_SHORT_ITEM = new byte[] {(byte) OFFSET_SHORT_ITEM};
private static final byte[] BYTES_SHORT_LIST = new byte[] {(byte) OFFSET_SHORT_LIST};

// DECODING

public static int decodeInt(byte[] data, int index) {
Expand Down Expand Up @@ -261,7 +264,10 @@ private static void fullTraverse(
} catch (Exception e) {
throw new RuntimeException(
"RLP wrong encoding ("
+ Hex.toHexString(msgData, startPos, endPos - startPos > 1024 ? 1024 : endPos - startPos)
+ Hex.toHexString(
msgData,
startPos,
endPos - startPos > 1024 ? 1024 : endPos - startPos)
+ ")",
e);
} catch (OutOfMemoryError e) {
Expand Down Expand Up @@ -404,7 +410,7 @@ public static byte[] encodeLength(int length, int offset) {

public static byte[] encodeByte(byte singleByte) {
if ((singleByte & 0xFF) == 0) {
return new byte[] {(byte) OFFSET_SHORT_ITEM};
return BYTES_SHORT_ITEM;
} else if ((singleByte & 0xFF) <= 0x7F) {
return new byte[] {singleByte};
} else {
Expand Down Expand Up @@ -472,7 +478,7 @@ public static byte[] encodeBigInteger(BigInteger srcBigInteger) {
public static byte[] encodeElement(byte[] srcData) {

if (isNullOrZeroArray(srcData)) {
return new byte[] {(byte) OFFSET_SHORT_ITEM};
return BYTES_SHORT_ITEM;
} else if (isSingleZero(srcData)) {
return srcData;
} else if (srcData.length == 1 && (srcData[0] & 0xFF) < 0x80) {
Expand Down Expand Up @@ -542,14 +548,12 @@ public static int calcElementPrefixSize(byte[] srcData) {
public static byte[] encodeListHeader(int size) {

if (size == 0) {
return new byte[] {(byte) OFFSET_SHORT_LIST};
return BYTES_SHORT_LIST;
}

byte[] header;
if (size < SIZE_THRESHOLD) {

header = new byte[1];
header[0] = (byte) (OFFSET_SHORT_LIST + size);
header = new byte[] {(byte) (OFFSET_SHORT_LIST + size)};
} else {
// length of length = BX
// prefix = [BX, [length]]
Expand Down Expand Up @@ -580,7 +584,7 @@ public static byte[] encodeLongElementHeader(int length) {
if (length < SIZE_THRESHOLD) {

if (length == 0) {
return new byte[] {(byte) 0x80};
return BYTES_SHORT_ITEM;
} else {
return new byte[] {(byte) (0x80 + length)};
}
Expand Down Expand Up @@ -609,7 +613,7 @@ public static byte[] encodeLongElementHeader(int length) {
public static byte[] encodeList(byte[]... elements) {

if (elements == null) {
return new byte[] {(byte) OFFSET_SHORT_LIST};
return BYTES_SHORT_LIST;
}

int totalLength = 0;
Expand Down
Loading

0 comments on commit a743a9a

Please sign in to comment.