Skip to content

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
and in all toString() methods.

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 11, 2018
1 parent 4cdc799 commit 654e0ab
Show file tree
Hide file tree
Showing 61 changed files with 269 additions and 240 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
import java.util.*;

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

/**
* Utility class to retrieve property values from the ethereumj.conf files
Expand Down Expand Up @@ -810,7 +811,7 @@ public boolean isFastSyncEnabled() {
public byte[] getFastSyncPivotBlockHash() {
if (!config.hasPath("sync.fast.pivotBlockHash")) return null;
byte[] ret = Hex.decode(config.getString("sync.fast.pivotBlockHash"));
if (ret.length != 32) throw new RuntimeException("Invalid block hash length: " + Hex.toHexString(ret));
if (ret.length != 32) throw new RuntimeException("Invalid block hash length: " + toHexString(ret));
return ret;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,11 @@
import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;

import org.spongycastle.util.encoders.Hex;

import java.math.BigInteger;

import static org.ethereum.crypto.HashUtil.*;
import static org.ethereum.util.FastByteComparisons.equal;
import static org.ethereum.util.ByteUtil.toHexString;

public class AccountState {

Expand Down Expand Up @@ -151,8 +150,8 @@ public boolean isEmpty() {
public String toString() {
String ret = " Nonce: " + this.getNonce().toString() + "\n" +
" Balance: " + getBalance() + "\n" +
" State Root: " + Hex.toHexString(this.getStateRoot()) + "\n" +
" Code Hash: " + Hex.toHexString(this.getCodeHash());
" State Root: " + toHexString(this.getStateRoot()) + "\n" +
" Code Hash: " + toHexString(this.getCodeHash());
return ret;
}
}
5 changes: 3 additions & 2 deletions 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 Expand Up @@ -304,7 +305,7 @@ public String toString() {
parseRLP();

toStringBuff.setLength(0);
toStringBuff.append(Hex.toHexString(this.getEncoded())).append("\n");
toStringBuff.append(toHexString(this.getEncoded())).append("\n");
toStringBuff.append("BlockData [ ");
toStringBuff.append(header.toString());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

import java.util.Arrays;
import java.util.List;
import static org.ethereum.util.ByteUtil.toHexString;

/**
* <p>Wraps {@link BlockHeader}</p>
Expand Down Expand Up @@ -90,7 +91,7 @@ public boolean sentBy(byte[] nodeId) {
public String toString() {
return "BlockHeaderWrapper {" +
"header=" + header +
", nodeId=" + Hex.toHexString(nodeId) +
", nodeId=" + toHexString(nodeId) +
'}';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@
*/
package org.ethereum.core;

import org.ethereum.util.ByteUtil;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;
import org.spongycastle.util.encoders.Hex;

import java.math.BigInteger;
import java.util.Arrays;

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


/**
* Block identifier holds block hash and number <br>
Expand Down Expand Up @@ -75,7 +75,7 @@ public byte[] getEncoded() {
@Override
public String toString() {
return "BlockIdentifier {" +
"hash=" + Hex.toHexString(hash) +
"hash=" + toHexString(hash) +
", number=" + number +
'}';
}
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
5 changes: 3 additions & 2 deletions ethereumj-core/src/main/java/org/ethereum/core/Bloom.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@
package org.ethereum.core;

import org.ethereum.util.ByteUtil;
import org.spongycastle.util.encoders.Hex;

import java.util.Arrays;

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

/**
* See http://www.herongyang.com/Java/Bit-String-Set-Bit-to-Byte-Array.html.
*
Expand Down Expand Up @@ -85,7 +86,7 @@ public Bloom copy() {

@Override
public String toString() {
return Hex.toHexString(data);
return toHexString(data);
}

@Override
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
Loading

0 comments on commit 654e0ab

Please sign in to comment.