Skip to content
This repository has been archived by the owner on Dec 5, 2024. It is now read-only.

Commit

Permalink
Use null safe method to convert bytes to hexString
Browse files Browse the repository at this point in the history
This commit replaces use of
`org.spongycastle.util.encoders.Hex.toHexString()` (Not null safe) with
`org.ethereum.util.ByteUtil.toHexString()` (null safe) while logging.
This covers only logging in the implementation(`/src/main`) and doesn't
cover any logging in tests(`/src/tests`)

Issue #1032
  • Loading branch information
kishansagathiya committed May 9, 2018
1 parent 4cdc799 commit 1c831ee
Show file tree
Hide file tree
Showing 28 changed files with 149 additions and 130 deletions.
3 changes: 2 additions & 1 deletion ethereumj-core/src/main/java/org/ethereum/core/Block.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@

import static org.ethereum.crypto.HashUtil.sha3;
import static org.ethereum.datasource.MemSizeEstimator.ByteArrayEstimator;
import static org.ethereum.util.ByteUtil.toHexString;

/**
* The block in Ethereum is the collection of relevant pieces of information
Expand Down Expand Up @@ -69,7 +70,7 @@ private Block() {
}

public Block(byte[] rawData) {
logger.debug("new from [" + Hex.toHexString(rawData) + "]");
logger.debug("new from [" + toHexString(rawData) + "]");
this.rlpEncoded = rawData;
}

Expand Down
37 changes: 19 additions & 18 deletions ethereumj-core/src/main/java/org/ethereum/core/BlockchainImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
import static org.ethereum.core.Denomination.SZABO;
import static org.ethereum.core.ImportResult.*;
import static org.ethereum.crypto.HashUtil.sha3;
import static org.ethereum.util.ByteUtil.toHexString;

/**
* The Ethereum blockchain is in many ways similar to the Bitcoin blockchain,
Expand Down Expand Up @@ -268,7 +269,7 @@ public TransactionInfo getTransactionInfo(byte[] hash) {
}
}
if (txInfo == null) {
logger.warn("Can't find block from main chain for transaction " + Hex.toHexString(hash));
logger.warn("Can't find block from main chain for transaction " + toHexString(hash));
return null;
}

Expand Down Expand Up @@ -410,15 +411,15 @@ public synchronized ImportResult tryToConnect(final Block block) {

if (logger.isDebugEnabled())
logger.debug("Try connect block hash: {}, number: {}",
Hex.toHexString(block.getHash()).substring(0, 6),
toHexString(block.getHash()).substring(0, 6),
block.getNumber());

if (blockStore.getMaxNumber() >= block.getNumber() &&
blockStore.isBlockExist(block.getHash())) {

if (logger.isDebugEnabled())
logger.debug("Block already exist hash: {}, number: {}",
Hex.toHexString(block.getHash()).substring(0, 6),
toHexString(block.getHash()).substring(0, 6),
block.getNumber());

// retry of well known block
Expand Down Expand Up @@ -582,22 +583,22 @@ public synchronized BlockSummary addImpl(Repository repo, final Block block) {
// Sanity checks

if (!FastByteComparisons.equal(block.getReceiptsRoot(), calcReceiptsTrie(receipts))) {
logger.warn("Block's given Receipt Hash doesn't match: {} != {}", Hex.toHexString(block.getReceiptsRoot()), Hex.toHexString(calcReceiptsTrie(receipts)));
logger.warn("Block's given Receipt Hash doesn't match: {} != {}", toHexString(block.getReceiptsRoot()), toHexString(calcReceiptsTrie(receipts)));
logger.warn("Calculated receipts: " + receipts);
repo.rollback();
summary = null;
}

if (!FastByteComparisons.equal(block.getLogBloom(), calcLogBloom(receipts))) {
logger.warn("Block's given logBloom Hash doesn't match: {} != {}", Hex.toHexString(block.getLogBloom()), Hex.toHexString(calcLogBloom(receipts)));
logger.warn("Block's given logBloom Hash doesn't match: {} != {}", toHexString(block.getLogBloom()), toHexString(calcLogBloom(receipts)));
repo.rollback();
summary = null;
}

if (!FastByteComparisons.equal(block.getStateRoot(), repo.getRoot())) {

stateLogger.warn("BLOCK: State conflict or received invalid block. block: {} worldstate {} mismatch", block.getNumber(), Hex.toHexString(repo.getRoot()));
stateLogger.warn("Conflict block dump: {}", Hex.toHexString(block.getEncoded()));
stateLogger.warn("BLOCK: State conflict or received invalid block. block: {} worldstate {} mismatch", block.getNumber(), toHexString(repo.getRoot()));
stateLogger.warn("Conflict block dump: {}", toHexString(block.getEncoded()));

// track.rollback();
// repository.rollback();
Expand All @@ -612,7 +613,7 @@ public synchronized BlockSummary addImpl(Repository repo, final Block block) {

if (config.exitOnBlockConflict() && !byTest) {
adminInfo.lostConsensus();
System.out.println("CONFLICT: BLOCK #" + block.getNumber() + ", dump: " + Hex.toHexString(block.getEncoded()));
System.out.println("CONFLICT: BLOCK #" + block.getNumber() + ", dump: " + toHexString(block.getEncoded()));
System.exit(1);
} else {
summary = null;
Expand Down Expand Up @@ -718,8 +719,8 @@ private boolean isValid(Repository repo, Block block) {
isValid = isValid(block.getHeader());

// Sanity checks
String trieHash = Hex.toHexString(block.getTxTrieRoot());
String trieListHash = Hex.toHexString(calcTxTrie(block.getTransactionsList()));
String trieHash = toHexString(block.getTxTrieRoot());
String trieListHash = toHexString(calcTxTrie(block.getTransactionsList()));


if (!trieHash.equals(trieListHash)) {
Expand Down Expand Up @@ -760,8 +761,8 @@ private boolean isValid(Repository repo, Block block) {
}

public boolean validateUncles(Block block) {
String unclesHash = Hex.toHexString(block.getHeader().getUnclesHash());
String unclesListHash = Hex.toHexString(HashUtil.sha3(block.getHeader().getUnclesEncoded(block.getUncleList())));
String unclesHash = toHexString(block.getHeader().getUnclesHash());
String unclesListHash = toHexString(HashUtil.sha3(block.getHeader().getUnclesEncoded(block.getUncleList())));

if (!unclesHash.equals(unclesListHash)) {
logger.warn("Block's given Uncle Hash doesn't match: {} != {}", unclesHash, unclesListHash);
Expand Down Expand Up @@ -792,18 +793,18 @@ public boolean validateUncles(Block block) {

ByteArrayWrapper uncleHash = new ByteArrayWrapper(uncle.getHash());
if (ancestors.contains(uncleHash)) {
logger.warn("Uncle is direct ancestor: " + Hex.toHexString(uncle.getHash()));
logger.warn("Uncle is direct ancestor: " + toHexString(uncle.getHash()));
return false;
}

if (usedUncles.contains(uncleHash)) {
logger.warn("Uncle is not unique: " + Hex.toHexString(uncle.getHash()));
logger.warn("Uncle is not unique: " + toHexString(uncle.getHash()));
return false;
}

Block uncleParent = blockStore.getBlockByHash(uncle.getParentHash());
if (!ancestors.contains(new ByteArrayWrapper(uncleParent.getHash()))) {
logger.warn("Uncle has no common parent: " + Hex.toHexString(uncle.getHash()));
logger.warn("Uncle has no common parent: " + toHexString(uncle.getHash()));
return false;
}
}
Expand Down Expand Up @@ -890,12 +891,12 @@ private BlockSummary applyBlock(Repository track, Block block) {
}

stateLogger.info("block: [{}] executed tx: [{}] \n state: [{}]", block.getNumber(), i,
Hex.toHexString(track.getRoot()));
toHexString(track.getRoot()));

stateLogger.info("[{}] ", receipt.toString());

if (stateLogger.isInfoEnabled())
stateLogger.info("tx[{}].receipt: [{}] ", i, Hex.toHexString(receipt.getEncoded()));
stateLogger.info("tx[{}].receipt: [{}] ", i, toHexString(receipt.getEncoded()));

// TODO
// if (block.getNumber() >= config.traceStartBlock())
Expand All @@ -911,7 +912,7 @@ private BlockSummary applyBlock(Repository track, Block block) {

stateLogger.info("applied reward for block: [{}] \n state: [{}]",
block.getNumber(),
Hex.toHexString(track.getRoot()));
toHexString(track.getRoot()));


// TODO
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,11 @@
import org.ethereum.vm.program.invoke.ProgramInvokeFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static org.ethereum.util.ByteUtil.toHexString;

/**
* Keeps logic providing pending state management
*
Expand Down Expand Up @@ -199,7 +200,7 @@ private void fireTxUpdate(TransactionReceipt txReceipt, PendingTransactionState
if (logger.isDebugEnabled()) {
logger.debug(String.format("PendingTransactionUpdate: (Tot: %3s) %12s : %s %8s %s [%s]",
getPendingTransactions().size(),
state, Hex.toHexString(txReceipt.getTransaction().getSender()).substring(0, 8),
state, toHexString(txReceipt.getTransaction().getSender()).substring(0, 8),
ByteUtil.byteArrayToLong(txReceipt.getTransaction().getNonce()),
block.getShortDescr(), txReceipt.getError()));
}
Expand Down Expand Up @@ -351,7 +352,7 @@ private void clearOutdated(final long blockNumber) {
logger.trace(
"Clear outdated pending transaction, block.number: [{}] hash: [{}]",
tx.getBlockNumber(),
Hex.toHexString(tx.getHash())
toHexString(tx.getHash())
);

pendingTransactions.removeAll(outdated);
Expand All @@ -364,7 +365,7 @@ private void clearPending(Block block, List<TransactionReceipt> receipts) {

if (pendingTransactions.remove(pend)) {
try {
logger.trace("Clear pending transaction, hash: [{}]", Hex.toHexString(tx.getHash()));
logger.trace("Clear pending transaction, hash: [{}]", toHexString(tx.getHash()));
TransactionReceipt receipt;
if (receipts != null) {
receipt = receipts.get(i);
Expand Down Expand Up @@ -404,7 +405,7 @@ private void updateState(Block block) {

private TransactionReceipt executeTx(Transaction tx) {

logger.trace("Apply pending state tx: {}", Hex.toHexString(tx.getHash()));
logger.trace("Apply pending state tx: {}", toHexString(tx.getHash()));

Block best = getBestBlock();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
import org.ethereum.vm.program.invoke.ProgramInvokeFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;

import java.math.BigInteger;
import java.util.List;
Expand All @@ -45,6 +44,7 @@
import static org.ethereum.util.ByteUtil.toHexString;
import static org.ethereum.vm.VMUtils.saveProgramTraceFile;
import static org.ethereum.vm.VMUtils.zipAndEncode;
import static org.ethereum.util.ByteUtil.toHexString;

/**
* @author Roman Mandeleil
Expand Down Expand Up @@ -218,7 +218,7 @@ private void call() {
if (!localCall && m_endGas.compareTo(spendingGas) < 0) {
// no refund
// no endowment
execError("Out of Gas calling precompiled contract 0x" + Hex.toHexString(targetAddress) +
execError("Out of Gas calling precompiled contract 0x" + toHexString(targetAddress) +
", required: " + spendingGas + ", left: " + m_endGas);
m_endGas = BigInteger.ZERO;
return;
Expand All @@ -230,7 +230,7 @@ private void call() {
Pair<Boolean, byte[]> out = precompiledContract.execute(tx.getData());

if (!out.getLeft()) {
execError("Error executing precompiled contract 0x" + Hex.toHexString(targetAddress));
execError("Error executing precompiled contract 0x" + toHexString(targetAddress));
m_endGas = BigInteger.ZERO;
return;
}
Expand Down Expand Up @@ -262,7 +262,7 @@ private void create() {

AccountState existingAddr = cacheTrack.getAccountState(newContractAddress);
if (existingAddr != null && existingAddr.isContractExist(blockchainConfig)) {
execError("Trying to create a contract with existing contract address: 0x" + Hex.toHexString(newContractAddress));
execError("Trying to create a contract with existing contract address: 0x" + toHexString(newContractAddress));
m_endGas = BigInteger.ZERO;
return;
}
Expand Down Expand Up @@ -426,12 +426,12 @@ public TransactionExecutionSummary finalization() {

// Refund for gas leftover
track.addBalance(tx.getSender(), summary.getLeftover().add(summary.getRefund()));
logger.info("Pay total refund to sender: [{}], refund val: [{}]", Hex.toHexString(tx.getSender()), summary.getRefund());
logger.info("Pay total refund to sender: [{}], refund val: [{}]", toHexString(tx.getSender()), summary.getRefund());

// Transfer fees to miner
track.addBalance(coinbase, summary.getFee());
touchedAccounts.add(coinbase);
logger.info("Pay fees to miner: [{}], feesEarned: [{}]", Hex.toHexString(coinbase), summary.getFee());
logger.info("Pay fees to miner: [{}], feesEarned: [{}]", toHexString(coinbase), summary.getFee());

if (result != null) {
logs = result.getLogInfoList();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import org.iq80.leveldb.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
Expand All @@ -39,6 +38,7 @@
import java.util.concurrent.locks.ReentrantReadWriteLock;

import static org.fusesource.leveldbjni.JniDBFactory.factory;
import static org.ethereum.util.ByteUtil.toHexString;

/**
* @author Roman Mandeleil
Expand Down Expand Up @@ -186,15 +186,15 @@ public String getName() {
public byte[] get(byte[] key) {
resetDbLock.readLock().lock();
try {
if (logger.isTraceEnabled()) logger.trace("~> LevelDbDataSource.get(): " + name + ", key: " + Hex.toHexString(key));
if (logger.isTraceEnabled()) logger.trace("~> LevelDbDataSource.get(): " + name + ", key: " + toHexString(key));
try {
byte[] ret = db.get(key);
if (logger.isTraceEnabled()) logger.trace("<~ LevelDbDataSource.get(): " + name + ", key: " + Hex.toHexString(key) + ", " + (ret == null ? "null" : ret.length));
if (logger.isTraceEnabled()) logger.trace("<~ LevelDbDataSource.get(): " + name + ", key: " + toHexString(key) + ", " + (ret == null ? "null" : ret.length));
return ret;
} catch (DBException e) {
logger.warn("Exception. Retrying again...", e);
byte[] ret = db.get(key);
if (logger.isTraceEnabled()) logger.trace("<~ LevelDbDataSource.get(): " + name + ", key: " + Hex.toHexString(key) + ", " + (ret == null ? "null" : ret.length));
if (logger.isTraceEnabled()) logger.trace("<~ LevelDbDataSource.get(): " + name + ", key: " + toHexString(key) + ", " + (ret == null ? "null" : ret.length));
return ret;
}
} finally {
Expand All @@ -206,9 +206,9 @@ public byte[] get(byte[] key) {
public void put(byte[] key, byte[] value) {
resetDbLock.readLock().lock();
try {
if (logger.isTraceEnabled()) logger.trace("~> LevelDbDataSource.put(): " + name + ", key: " + Hex.toHexString(key) + ", " + (value == null ? "null" : value.length));
if (logger.isTraceEnabled()) logger.trace("~> LevelDbDataSource.put(): " + name + ", key: " + toHexString(key) + ", " + (value == null ? "null" : value.length));
db.put(key, value);
if (logger.isTraceEnabled()) logger.trace("<~ LevelDbDataSource.put(): " + name + ", key: " + Hex.toHexString(key) + ", " + (value == null ? "null" : value.length));
if (logger.isTraceEnabled()) logger.trace("<~ LevelDbDataSource.put(): " + name + ", key: " + toHexString(key) + ", " + (value == null ? "null" : value.length));
} finally {
resetDbLock.readLock().unlock();
}
Expand All @@ -218,9 +218,9 @@ public void put(byte[] key, byte[] value) {
public void delete(byte[] key) {
resetDbLock.readLock().lock();
try {
if (logger.isTraceEnabled()) logger.trace("~> LevelDbDataSource.delete(): " + name + ", key: " + Hex.toHexString(key));
if (logger.isTraceEnabled()) logger.trace("~> LevelDbDataSource.delete(): " + name + ", key: " + toHexString(key));
db.delete(key);
if (logger.isTraceEnabled()) logger.trace("<~ LevelDbDataSource.delete(): " + name + ", key: " + Hex.toHexString(key));
if (logger.isTraceEnabled()) logger.trace("<~ LevelDbDataSource.delete(): " + name + ", key: " + toHexString(key));
} finally {
resetDbLock.readLock().unlock();
}
Expand Down
Loading

0 comments on commit 1c831ee

Please sign in to comment.