output stringlengths 64 73.2k | input stringlengths 208 73.3k | instruction stringclasses 1 value |
|---|---|---|
#fixed code
public void processMessage(NulsMessage message) throws IOException {
//todo
if (true) {
try {
System.out.println("------receive message:" + Hex.encode(message.serialize()));
} catch (IOException e) {
e.printStackTrace();
}
if (this.status != Peer.HANDSHAKE) {
return;
}
if (checkBroadcastExist(message.getData())) {
return;
}
eventProcessorService.dispatch(message.getData(), this.getHash());
} else {
byte[] networkHeader = new byte[NetworkDataHeader.NETWORK_HEADER_SIZE];
System.arraycopy(message.getData(), 0, networkHeader, 0, NetworkDataHeader.NETWORK_HEADER_SIZE);
NetworkDataHeader header;
BaseNetworkData networkMessage;
try {
header = new NetworkDataHeader(new NulsByteBuffer(networkHeader));
networkMessage = BaseNetworkData.transfer(header.getType(), message.getData());
} catch (NulsException e) {
Log.error("networkMessage transfer error:", e);
this.destroy();
return;
}
if (this.status != Peer.HANDSHAKE && !isHandShakeMessage(networkMessage)) {
return;
}
asynExecute(networkMessage);
}
} | #vulnerable code
public void processMessage(NulsMessage message) throws IOException {
if (message.getHeader().getHeadType() == NulsMessageHeader.EVENT_MESSAGE) {
try {
System.out.println("------receive message:" + Hex.encode(message.serialize()));
} catch (IOException e) {
e.printStackTrace();
}
if (this.status != Peer.HANDSHAKE) {
return;
}
if (checkBroadcastExist(message.getData())) {
return;
}
eventProcessorService.dispatch(message.getData(), this.getHash());
} else {
byte[] networkHeader = new byte[NetworkDataHeader.NETWORK_HEADER_SIZE];
System.arraycopy(message.getData(), 0, networkHeader, 0, NetworkDataHeader.NETWORK_HEADER_SIZE);
NetworkDataHeader header;
BaseNetworkData networkMessage;
try {
header = new NetworkDataHeader(new NulsByteBuffer(networkHeader));
networkMessage = BaseNetworkData.transfer(header.getType(), message.getData());
} catch (NulsException e) {
Log.error("networkMessage transfer error:", e);
this.destroy();
return;
}
if (this.status != Peer.HANDSHAKE && !isHandShakeMessage(networkMessage)) {
return;
}
asynExecute(networkMessage);
}
}
#location 31
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean downloadedBlock(String nodeId, Block block) {
System.out.println("downloaded:" + block.getHeader().getHeight());
NodeDownloadingStatus status = nodeStatusMap.get(nodeId);
if (null == status) {
return false;
}
if (!status.containsHeight(block.getHeader().getHeight())) {
return false;
}
blockMap.put(block.getHeader().getHeight(), block);
status.downloaded(block.getHeader().getHeight());
status.setUpdateTime(System.currentTimeMillis());
if (status.finished()) {
this.queueService.offer(queueId, nodeId);
}
verify();
return true;
} | #vulnerable code
public boolean downloadedBlock(String nodeId, Block block) {
System.out.println("downloaded:"+block.getHeader().getHeight());
NodeDownloadingStatus status = nodeStatusMap.get(nodeId);
if (null == status) {
return false;
}
if (!status.containsHeight(block.getHeader().getHeight())) {
return false;
}
blockMap.put(block.getHeader().getHeight(), block);
status.downloaded(block.getHeader().getHeight());
status.setUpdateTime(System.currentTimeMillis());
if (status.finished()) {
this.queueService.offer(queueId, nodeId);
}
verify();
return true;
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onEvent(DisruptorData<ProcessData<E>> processDataDisruptorMessage, long l, boolean b) {
try {
BaseMessage message = processDataDisruptorMessage.getData().getData();
if (null == message || message.getHeader() == null) {
return;
}
//todo test
if (message.getHeader().getModuleId() == ProtocolConstant.MODULE_ID_PROTOCOL && message.getHeader().getMsgType() == ProtocolConstant.MESSAGE_TYPE_NEW_BLOCK) {
SmallBlockMessage smallBlockMessage = (SmallBlockMessage) message;
Log.warn("rcv-msg:" + smallBlockMessage.getMsgBody().getHeader().getHash().toString());
}
boolean commonDigestTx = message.getHeader().getMsgType() == MessageBusConstant.MSG_TYPE_COMMON_MSG_HASH_MSG &&
message.getHeader().getModuleId() == MessageBusConstant.MODULE_ID_MESSAGE_BUS;
if (!commonDigestTx) {
messageCacheService.cacheRecievedMessageHash(message.getHash());
return;
}
if (messageCacheService.kownTheMessage(((CommonDigestMessage) message).getMsgBody())) {
Log.info("discard:{}," + ((CommonDigestMessage) message).getMsgBody(), processDataDisruptorMessage.getData().getNode().getId());
processDataDisruptorMessage.setStoped(true);
} else if (messageCacheService.kownTheMessage(message.getHash())) {
Log.info("discard2:{}," + message.getClass(), processDataDisruptorMessage.getData().getNode().getId());
processDataDisruptorMessage.setStoped(true);
} else {
messageCacheService.cacheRecievedMessageHash(message.getHash());
}
} catch (Exception e) {
Log.error(e);
}
} | #vulnerable code
@Override
public void onEvent(DisruptorData<ProcessData<E>> processDataDisruptorMessage, long l, boolean b) {
try {
BaseMessage message = processDataDisruptorMessage.getData().getData();
if (null == message || message.getHeader() == null) {
return;
}
messageCacheService.cacheRecievedMessageHash(message.getHash());
//todo test
if (message.getHeader().getModuleId() == ProtocolConstant.MODULE_ID_PROTOCOL && message.getHeader().getMsgType() == ProtocolConstant.MESSAGE_TYPE_NEW_BLOCK) {
SmallBlockMessage smallBlockMessage = (SmallBlockMessage) message;
Log.warn("rcv-msg:" + smallBlockMessage.getMsgBody().getHeader().getHash().toString());
}
boolean commonDigestTx = message.getHeader().getMsgType() == MessageBusConstant.MSG_TYPE_COMMON_MSG_HASH_MSG &&
message.getHeader().getModuleId() == MessageBusConstant.MODULE_ID_MESSAGE_BUS;
if (!commonDigestTx) {
return;
}
if (messageCacheService.kownTheMessage(((CommonDigestMessage) message).getMsgBody())) {
Log.info("discard:{}," + ((CommonDigestMessage) message).getMsgBody(), processDataDisruptorMessage.getData().getNode().getId());
processDataDisruptorMessage.setStoped(true);
} else if (messageCacheService.kownTheMessage(message.getHash())) {
Log.info("discard2:{}," + message.getClass(), processDataDisruptorMessage.getData().getNode().getId());
processDataDisruptorMessage.setStoped(true);
}
} catch (Exception e) {
Log.error(e);
}
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public ValidateResult validate(Block block) {
if (block.getHeader().getTxCount() != block.getTxs().size()) {
return ValidateResult.getFailedResult("txCount is wrong!");
}
int count = 0;
List<Transaction> txList = new ArrayList<>();
for (Transaction tx : block.getTxs()) {
ValidateResult result = tx.verify();
if(result.isFailed()&&result.getErrorCode()== ErrorCode.ORPHAN_TX){
AbstractCoinTransaction coinTx = (AbstractCoinTransaction) tx;
result = coinTx.getCoinDataProvider().verifyCoinData(coinTx,txList);
if(result.isSuccess()){
coinTx.setSkipInputValidator(true);
result = coinTx.verify();
coinTx.setSkipInputValidator(false);
}
}
if (null==result||result.isFailed()) {
if(result.getErrorCode()== ErrorCode.ORPHAN_TX){
return result;
}
return ValidateResult.getFailedResult("there is wrong transaction!msg:"+result.getMessage());
}
if (tx.getType() == TransactionConstant.TX_TYPE_COIN_BASE) {
count++;
}
txList.add(tx);
}
if (count > 1) {
return ValidateResult.getFailedResult("coinbase transaction must only one!");
}
return ValidateResult.getSuccessResult();
} | #vulnerable code
@Override
public ValidateResult validate(Block block) {
if (block.getHeader().getTxCount() != block.getTxs().size()) {
return ValidateResult.getFailedResult("txCount is wrong!");
}
int count = 0;
for (Transaction tx : block.getTxs()) {
ValidateResult result = tx.verify();
if (null==result||result.isFailed()) {
if(result.getErrorCode()== ErrorCode.ORPHAN_TX){
return result;
}
return ValidateResult.getFailedResult("there is wrong transaction!msg:"+result.getMessage());
}
if (tx.getType() == TransactionConstant.TX_TYPE_COIN_BASE) {
count++;
}
}
if (count > 1) {
return ValidateResult.getFailedResult("coinbase transaction must only one!");
}
return ValidateResult.getSuccessResult();
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private boolean verifyBaseTx(Block block, MeetingRound currentRound, MeetingMember member) {
List<Transaction> txs = block.getTxs();
Transaction tx = txs.get(0);
if (tx.getType() != TransactionConstant.TX_TYPE_COIN_BASE) {
BlockLog.debug("Coinbase transaction order wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
// Log.error("Coinbase transaction order wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
return false;
}
YellowPunishTransaction yellowPunishTx = null;
for (int i = 1; i < txs.size(); i++) {
Transaction transaction = txs.get(i);
if (transaction.getType() == TransactionConstant.TX_TYPE_COIN_BASE) {
BlockLog.debug("Coinbase transaction more than one! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
// Log.error("Coinbase transaction more than one! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
return false;
}
if (null == yellowPunishTx && transaction.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) {
yellowPunishTx = (YellowPunishTransaction) transaction;
} else if (null != yellowPunishTx && transaction.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) {
BlockLog.debug("Yellow punish transaction more than one! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
// Log.error("Yellow punish transaction more than one! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
return false;
}
}
CoinBaseTransaction coinBaseTransaction = ConsensusTool.createCoinBaseTx(member, block.getTxs(), currentRound, block.getHeader().getHeight() + PocConsensusConstant.COINBASE_UNLOCK_HEIGHT);
if (null == coinBaseTransaction || !tx.getHash().equals(coinBaseTransaction.getHash())) {
BlockLog.debug("the coin base tx is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
Log.error("the coin base tx is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
return false;
}
try {
YellowPunishTransaction yellowPunishTransaction = ConsensusTool.createYellowPunishTx(chain.getBestBlock(), member, currentRound);
if (yellowPunishTransaction == yellowPunishTx) {
return true;
} else if (yellowPunishTransaction == null || yellowPunishTx == null) {
BlockLog.debug("The yellow punish tx is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
// Log.error("The yellow punish tx is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
return false;
} else if (!yellowPunishTransaction.getHash().equals(yellowPunishTx.getHash())) {
BlockLog.debug("The yellow punish tx's hash is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
// Log.error("The yellow punish tx's hash is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
return false;
}
} catch (Exception e) {
BlockLog.debug("The tx's wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex(), e);
// Log.error("The tx's wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex(), e);
return false;
}
return true;
} | #vulnerable code
private boolean verifyBaseTx(Block block, MeetingRound currentRound, MeetingMember member) {
if(5176 == block.getHeader().getHeight()) {
System.out.println("in the bug");
}
List<Transaction> txs = block.getTxs();
Transaction tx = txs.get(0);
if (tx.getType() != TransactionConstant.TX_TYPE_COIN_BASE) {
BlockLog.debug("Coinbase transaction order wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
// Log.error("Coinbase transaction order wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
return false;
}
YellowPunishTransaction yellowPunishTx = null;
for (int i = 1; i < txs.size(); i++) {
Transaction transaction = txs.get(i);
if (transaction.getType() == TransactionConstant.TX_TYPE_COIN_BASE) {
BlockLog.debug("Coinbase transaction more than one! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
// Log.error("Coinbase transaction more than one! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
return false;
}
if (null == yellowPunishTx && transaction.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) {
yellowPunishTx = (YellowPunishTransaction) transaction;
} else if (null != yellowPunishTx && transaction.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) {
BlockLog.debug("Yellow punish transaction more than one! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
// Log.error("Yellow punish transaction more than one! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
return false;
}
}
CoinBaseTransaction coinBaseTransaction = ConsensusTool.createCoinBaseTx(member, block.getTxs(), currentRound, block.getHeader().getHeight() + PocConsensusConstant.COINBASE_UNLOCK_HEIGHT);
if (null == coinBaseTransaction || !tx.getHash().equals(coinBaseTransaction.getHash())) {
BlockLog.debug("the coin base tx is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
Log.error("the coin base tx is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
Log.error("Pierre-error-test: tx is <" + tx.toString() + ">, coinBaseTransaction is <" + coinBaseTransaction.toString() + ">");
return false;
}
try {
YellowPunishTransaction yellowPunishTransaction = ConsensusTool.createYellowPunishTx(chain.getBestBlock(), member, currentRound);
if (yellowPunishTransaction == yellowPunishTx) {
return true;
} else if (yellowPunishTransaction == null || yellowPunishTx == null) {
BlockLog.debug("The yellow punish tx is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
// Log.error("The yellow punish tx is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
return false;
} else if (!yellowPunishTransaction.getHash().equals(yellowPunishTx.getHash())) {
BlockLog.debug("The yellow punish tx's hash is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
// Log.error("The yellow punish tx's hash is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex());
return false;
}
} catch (Exception e) {
BlockLog.debug("The tx's wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex(), e);
// Log.error("The tx's wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex(), e);
return false;
}
return true;
}
#location 33
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
@DbSession
public void save(CoinData coinData, Transaction tx) throws NulsException {
UtxoData utxoData = (UtxoData) coinData;
List<UtxoInputPo> inputPoList = new ArrayList<>();
List<UtxoOutput> spends = new ArrayList<>();
List<UtxoOutputPo> spendPoList = new ArrayList<>();
List<TxAccountRelationPo> txRelations = new ArrayList<>();
Set<String> addressSet = new HashSet<>();
lock.lock();
try {
processDataInput(utxoData, inputPoList, spends, spendPoList, addressSet);
List<UtxoOutputPo> outputPoList = new ArrayList<>();
for (int i = 0; i < utxoData.getOutputs().size(); i++) {
UtxoOutput output = utxoData.getOutputs().get(i);
output = ledgerCacheService.getUtxo(output.getKey());
if (output == null) {
throw new NulsRuntimeException(ErrorCode.DATA_NOT_FOUND);
}
if (output.isConfirm() || OutPutStatusEnum.UTXO_SPENT == output.getStatus()) {
Log.error("-----------------------------------save() output status is" + output.getStatus().name());
throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "use a not legal utxo");
}
if (OutPutStatusEnum.UTXO_UNCONFIRM_CONSENSUS_LOCK == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_CONSENSUS_LOCK);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_TIME_LOCK == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_TIME_LOCK);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_UNSPEND);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND);
}
UtxoOutputPo outputPo = UtxoTransferTool.toOutputPojo(output);
outputPoList.add(outputPo);
addressSet.add(Address.fromHashs(output.getAddress()).getBase58());
}
for (String address : addressSet) {
TxAccountRelationPo relationPo = new TxAccountRelationPo(tx.getHash().getDigestHex(), address);
txRelations.add(relationPo);
}
outputDataService.updateStatus(spendPoList);
inputDataService.save(inputPoList);
outputDataService.save(outputPoList);
relationDataService.save(txRelations);
afterSaveDatabase(spends, utxoData, tx);
for (String address : addressSet) {
UtxoTransactionTool.getInstance().calcBalance(address, true);
}
} catch (Exception e) {
//rollback
// Log.warn(e.getMessage(), e);
// for (UtxoOutput output : utxoData.getOutputs()) {
// ledgerCacheService.removeUtxo(output.getKey());
// }
// for (UtxoOutput spend : spends) {
// ledgerCacheService.updateUtxoStatus(spend.getKey(), UtxoOutput.UTXO_CONFIRM_LOCK, UtxoOutput.UTXO_SPENT);
// }
throw e;
} finally {
lock.unlock();
}
} | #vulnerable code
@Override
@DbSession
public void save(CoinData coinData, Transaction tx) throws NulsException {
UtxoData utxoData = (UtxoData) coinData;
List<UtxoInputPo> inputPoList = new ArrayList<>();
List<UtxoOutput> spends = new ArrayList<>();
List<UtxoOutputPo> spendPoList = new ArrayList<>();
List<TxAccountRelationPo> txRelations = new ArrayList<>();
Set<String> addressSet = new HashSet<>();
try {
processDataInput(utxoData, inputPoList, spends, spendPoList, addressSet);
List<UtxoOutputPo> outputPoList = new ArrayList<>();
for (int i = 0; i < utxoData.getOutputs().size(); i++) {
UtxoOutput output = utxoData.getOutputs().get(i);
output = ledgerCacheService.getUtxo(output.getKey());
if (output == null) {
throw new NulsRuntimeException(ErrorCode.DATA_NOT_FOUND);
}
if (output.isConfirm() || OutPutStatusEnum.UTXO_SPENT == output.getStatus()) {
Log.error("-----------------------------------save() output status is" + output.getStatus().name());
throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "use a not legal utxo");
}
if (OutPutStatusEnum.UTXO_UNCONFIRM_CONSENSUS_LOCK == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_CONSENSUS_LOCK);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_TIME_LOCK == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_TIME_LOCK);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_UNSPEND);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND);
}
UtxoOutputPo outputPo = UtxoTransferTool.toOutputPojo(output);
outputPoList.add(outputPo);
addressSet.add(Address.fromHashs(output.getAddress()).getBase58());
}
for (String address : addressSet) {
TxAccountRelationPo relationPo = new TxAccountRelationPo(tx.getHash().getDigestHex(), address);
txRelations.add(relationPo);
}
outputDataService.updateStatus(spendPoList);
inputDataService.save(inputPoList);
outputDataService.save(outputPoList);
relationDataService.save(txRelations);
afterSaveDatabase(spends, utxoData, tx);
for (String address : addressSet) {
UtxoTransactionTool.getInstance().calcBalance(address, true);
}
} catch (Exception e) {
//rollback
// Log.warn(e.getMessage(), e);
// for (UtxoOutput output : utxoData.getOutputs()) {
// ledgerCacheService.removeUtxo(output.getKey());
// }
// for (UtxoOutput spend : spends) {
// ledgerCacheService.updateUtxoStatus(spend.getKey(), UtxoOutput.UTXO_CONFIRM_LOCK, UtxoOutput.UTXO_SPENT);
// }
throw e;
}
}
#location 37
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean addBlockHashResponse(String nodeId, BlockHashResponse response) {
if (this.nodeIdList == null || !this.nodeIdList.contains(nodeId)) {
return false;
}
if (!requesting) {
return false;
}
if (response.getBestHeight() == 0 && NulsContext.getInstance().getBestHeight() > 0) {
hashesMap.remove(nodeId);
nodeIdList.remove(nodeId);
return false;
}
if (hashesMap.get(nodeId) == null) {
hashesMap.put(nodeId, response);
} else {
BlockHashResponse instance = hashesMap.get(nodeId);
instance.merge(response);
hashesMap.put(nodeId, instance);
}
// if (response.getHeightList().get(response.getHeightList().size() - 1) < end) {
// return true;
// }
String key = response.getBestHash().getDigestHex();
List<String> nodes = calcMap.get(key);
if (null == nodes) {
nodes = new ArrayList<>();
}
if (!nodes.contains(nodeId)) {
nodes.add(nodeId);
}
calcMap.put(key, nodes);
calc();
return true;
} | #vulnerable code
public boolean addBlockHashResponse(String nodeId, BlockHashResponse response) {
if (this.nodeIdList == null || !this.nodeIdList.contains(nodeId)) {
return false;
}
if (!requesting) {
return false;
}
if (response.getBestHeight() == 0 && NulsContext.getInstance().getBestHeight() > 0) {
hashesMap.remove(nodeId);
nodeIdList.remove(nodeId);
return false;
}
if (hashesMap.get(nodeId) == null) {
hashesMap.put(nodeId, response);
} else {
BlockHashResponse instance = hashesMap.get(nodeId);
instance.merge(response);
hashesMap.put(nodeId, instance);
}
if (response.getHeightList().get(response.getHeightList().size() - 1) < end) {
return true;
}
String key = response.getBestHash().getDigestHex();
List<String> nodes = calcMap.get(key);
if (null == nodes) {
nodes = new ArrayList<>();
}
if (!nodes.contains(nodeId)) {
nodes.add(nodeId);
}
calcMap.put(key, nodes);
calc();
return true;
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
@DbSession
public boolean saveBlock(Block block) throws IOException {
BlockLog.debug("save block height:" + block.getHeader().getHeight() + ", preHash:" + block.getHeader().getPreHash() + " , hash:" + block.getHeader().getHash() + ", address:" + Address.fromHashs(block.getHeader().getPackingAddress()));
BlockHeader bestBlockHeader = getLocalBestBlockHeader();
if((bestBlockHeader == null && block.getHeader().getHeight() != 0L) || (bestBlockHeader != null && !bestBlockHeader.getHash().equals(block.getHeader().getPreHash()))) {
throw new NulsRuntimeException(ErrorCode.FAILED, "save blcok error , prehash is error , height: " + block.getHeader().getHeight() + " , hash: " + block.getHeader().getHash());
}
List<Transaction> commitedList = new ArrayList<>();
for (int x = 0; x < block.getHeader().getTxCount(); x++) {
Transaction tx = block.getTxs().get(x);
tx.setIndex(x);
tx.setBlockHeight(block.getHeader().getHeight());
try {
tx.verifyWithException();
commitedList.add(tx);
ledgerService.commitTx(tx, block);
} catch (Exception e) {
Log.error(e);
this.rollback(commitedList);
throw new NulsRuntimeException(e);
}
}
ledgerService.saveTxList(block.getTxs());
blockStorageService.save(block);
List<Transaction> localTxList = null;
try {
localTxList = this.ledgerService.getWaitingTxList();
} catch (Exception e) {
Log.error(e);
}
if (null != localTxList && !localTxList.isEmpty()) {
for (Transaction tx : localTxList) {
try {
ValidateResult result = ledgerService.conflictDetectTx(tx, block.getTxs());
if (result.isFailed()) {
ledgerService.deleteLocalTx(tx.getHash().getDigestHex());
}
} catch (NulsException e) {
Log.error(e);
}
}
}
return true;
} | #vulnerable code
@Override
@DbSession
public boolean saveBlock(Block block) throws IOException {
BlockLog.debug("save block height:" + block.getHeader().getHeight() + ", preHash:" + block.getHeader().getPreHash() + " , hash:" + block.getHeader().getHash() + ", address:" + Address.fromHashs(block.getHeader().getPackingAddress()));
BlockHeader bestBlockHeader = getLocalBestBlockHeader();
if(!bestBlockHeader.getHash().equals(block.getHeader().getPreHash())) {
throw new NulsRuntimeException(ErrorCode.FAILED, "save blcok error , prehash is error , height: " + block.getHeader().getHeight() + " , hash: " + block.getHeader().getHash());
}
List<Transaction> commitedList = new ArrayList<>();
for (int x = 0; x < block.getHeader().getTxCount(); x++) {
Transaction tx = block.getTxs().get(x);
tx.setIndex(x);
tx.setBlockHeight(block.getHeader().getHeight());
try {
tx.verifyWithException();
commitedList.add(tx);
ledgerService.commitTx(tx, block);
} catch (Exception e) {
Log.error(e);
this.rollback(commitedList);
throw new NulsRuntimeException(e);
}
}
ledgerService.saveTxList(block.getTxs());
blockStorageService.save(block);
List<Transaction> localTxList = null;
try {
localTxList = this.ledgerService.getWaitingTxList();
} catch (Exception e) {
Log.error(e);
}
if (null != localTxList && !localTxList.isEmpty()) {
for (Transaction tx : localTxList) {
try {
ValidateResult result = ledgerService.conflictDetectTx(tx, block.getTxs());
if (result.isFailed()) {
ledgerService.deleteLocalTx(tx.getHash().getDigestHex());
}
} catch (NulsException e) {
Log.error(e);
}
}
}
return true;
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected void parse(NulsByteBuffer byteBuffer) throws NulsException {
this.setHeader(byteBuffer.readNulsData(new EventHeader()));
// version = new NulsVersion(byteBuffer.readShort());
bestBlockHeight = byteBuffer.readVarInt();
bestBlockHash = byteBuffer.readString();
nulsVersion = byteBuffer.readString();
} | #vulnerable code
@Override
protected void parse(NulsByteBuffer byteBuffer) throws NulsException {
this.setHeader(byteBuffer.readNulsData(new EventHeader()));
// version = new NulsVersion(byteBuffer.readShort());
bestBlockHeight = byteBuffer.readVarInt();
bestBlockHash = new String(byteBuffer.readByLengthByte());
nulsVersion = new String(byteBuffer.readByLengthByte());
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void requestTxGroup(NulsDigestData blockHash, String nodeId) {
GetTxGroupRequest request = new GetTxGroupRequest();
GetTxGroupParam data = new GetTxGroupParam();
data.setBlockHash(blockHash);
List<NulsDigestData> txHashList = new ArrayList<>();
SmallBlock smb = temporaryCacheManager.getSmallBlock(blockHash.getDigestHex());
for (NulsDigestData txHash : smb.getTxHashList()) {
boolean exist = txCacheManager.txExist(txHash);
if (!exist) {
txHashList.add(txHash);
}
}
if (txHashList.isEmpty()) {
BlockHeader header = temporaryCacheManager.getBlockHeader(smb.getBlockHash().getDigestHex());
if (null == header) {
return;
}
Block block = new Block();
block.setHeader(header);
List<Transaction> txs = new ArrayList<>();
for (NulsDigestData txHash : smb.getTxHashList()) {
Transaction tx = txCacheManager.getTx(txHash);
if (null == tx) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
txs.add(tx);
}
block.setTxs(txs);
ValidateResult vResult = block.verify();
if (vResult.isFailed()&&vResult.getErrorCode()!=ErrorCode.ORPHAN_BLOCK&&vResult.getErrorCode()!=ErrorCode.ORPHAN_TX) {
return;
}
blockManager.addBlock(block, false,nodeId);
AssembledBlockNotice notice = new AssembledBlockNotice();
notice.setEventBody(header);
eventBroadcaster.publishToLocal(notice);
return;
}
data.setTxHashList(txHashList);
request.setEventBody(data);
tgRequest.put(blockHash.getDigestHex(), System.currentTimeMillis());
Integer value = tgRequestCount.get(blockHash.getDigestHex());
if (null == value) {
value = 0;
}
tgRequestCount.put(blockHash.getDigestHex(), 1 + value);
if (StringUtils.isBlank(nodeId)) {
eventBroadcaster.broadcastAndCache(request, false);
} else {
eventBroadcaster.sendToNode(request, nodeId);
}
} | #vulnerable code
public void requestTxGroup(NulsDigestData blockHash, String nodeId) {
GetTxGroupRequest request = new GetTxGroupRequest();
GetTxGroupParam data = new GetTxGroupParam();
data.setBlockHash(blockHash);
List<NulsDigestData> txHashList = new ArrayList<>();
SmallBlock smb = temporaryCacheManager.getSmallBlock(blockHash.getDigestHex());
for (NulsDigestData txHash : smb.getTxHashList()) {
boolean exist = txCacheManager.txExist(txHash);
if (!exist) {
txHashList.add(txHash);
}
}
if (txHashList.isEmpty()) {
BlockHeader header = temporaryCacheManager.getBlockHeader(smb.getBlockHash().getDigestHex());
if (null == header) {
return;
}
Block block = new Block();
block.setHeader(header);
List<Transaction> txs = new ArrayList<>();
for (NulsDigestData txHash : smb.getTxHashList()) {
Transaction tx = txCacheManager.getTx(txHash);
if (null == tx) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
txs.add(tx);
}
block.setTxs(txs);
ValidateResult<RedPunishData> vResult = block.verify();
if (null == vResult || vResult.isFailed()) {
if (vResult.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) {
RedPunishData redPunishData = vResult.getObject();
ConsensusMeetingRunner.putPunishData(redPunishData);
}
return;
}
blockManager.addBlock(block, false,nodeId);
AssembledBlockNotice notice = new AssembledBlockNotice();
notice.setEventBody(header);
eventBroadcaster.publishToLocal(notice);
return;
}
data.setTxHashList(txHashList);
request.setEventBody(data);
tgRequest.put(blockHash.getDigestHex(), System.currentTimeMillis());
Integer value = tgRequestCount.get(blockHash.getDigestHex());
if (null == value) {
value = 0;
}
tgRequestCount.put(blockHash.getDigestHex(), 1 + value);
if (StringUtils.isBlank(nodeId)) {
eventBroadcaster.broadcastAndCache(request, false);
} else {
eventBroadcaster.sendToNode(request, nodeId);
}
}
#location 32
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public PocMeetingRound getRound(long preRoundIndex, long roundIndex, boolean needPreRound) {
PocMeetingRound round = ROUND_MAP.get(roundIndex);
Block preRoundFirstBlock = null;
BlockRoundData preRoundData = null;
if (null == round) {
Block bestBlock = getBestBlock();
BlockRoundData nowRoundData = new BlockRoundData(bestBlock.getHeader().getExtend());
if (nowRoundData.getRoundIndex() >= preRoundIndex) {
preRoundFirstBlock = getBlockService().getPreRoundFirstBlock(preRoundIndex);
if (null == preRoundFirstBlock) {
return null;
}
preRoundData = new BlockRoundData(preRoundFirstBlock.getHeader().getExtend());
round = calcRound(preRoundFirstBlock.getHeader().getHeight(), roundIndex, preRoundData.getRoundEndTime(), false);
if (roundIndex > (preRoundData.getRoundIndex() + 1)) {
long roundTime = PocConsensusConstant.BLOCK_TIME_INTERVAL_SECOND * 1000L * round.getMemberCount();
long startTime = round.getStartTime() + (roundIndex - (preRoundData.getRoundIndex() + 1)) * roundTime;
round.setStartTime(startTime);
List<PocMeetingMember> memberList = round.getMemberList();
for (PocMeetingMember member : memberList) {
member.setRoundStartTime(round.getStartTime());
}
Collections.sort(memberList);
round.setMemberList(memberList);
}
ROUND_MAP.put(round.getIndex(), round);
} else {
return null;
}
}
if (needPreRound && round.getPreRound() == null) {
if (null == preRoundFirstBlock) {
Block firstBlock = getBlockService().getPreRoundFirstBlock(preRoundIndex);
if (null == firstBlock) {
return null;
}
preRoundFirstBlock = firstBlock;
preRoundData = new BlockRoundData(preRoundFirstBlock.getHeader().getExtend());
}
if (preRoundFirstBlock.getHeader().getHeight() == 0) {
round.setPreRound(calcRound(0, 1, preRoundData.getRoundStartTime(), false));
return round;
}
Block preblock = getBlockService().getBlock(preRoundFirstBlock.getHeader().getPreHash().getDigestHex());
if (null == preblock) {
return null;
}
BlockRoundData preBlockRoundData = new BlockRoundData(preblock.getHeader().getExtend());
round.setPreRound(getRound(preBlockRoundData.getRoundIndex(), preRoundIndex, false));
}
StringBuilder str = new StringBuilder();
for (PocMeetingMember member : round.getMemberList()) {
str.append(member.getPackingAddress());
str.append(" ,order:" + member.getPackingIndexOfRound());
str.append(",packEndTime:" + new Date(member.getPackEndTime()));
str.append("\n");
}
if(null==round.getPreRound()){
BlockLog.debug("calc new round:index:" + round.getIndex() + " , start:" + new Date(round.getStartTime())
+ ", netTime:(" + new Date(TimeService.currentTimeMillis()).toString() + ") , members:\n :" + str);
}else {
BlockLog.debug("calc new round:index:" + round.getIndex() + " ,preIndex:" + round.getPreRound().getIndex() + " , start:" + new Date(round.getStartTime())
+ ", netTime:(" + new Date(TimeService.currentTimeMillis()).toString() + ") , members:\n :" + str);
}
return round;
} | #vulnerable code
public PocMeetingRound getRound(long preRoundIndex, long roundIndex, boolean needPreRound) {
PocMeetingRound round = ROUND_MAP.get(roundIndex);
Block preRoundFirstBlock = null;
BlockRoundData preRoundData = null;
if (null == round) {
Block bestBlock = getBestBlock();
BlockRoundData nowRoundData = new BlockRoundData(bestBlock.getHeader().getExtend());
if (nowRoundData.getRoundIndex() >= preRoundIndex) {
preRoundFirstBlock = getBlockService().getPreRoundFirstBlock(preRoundIndex);
if (null == preRoundFirstBlock) {
return null;
}
preRoundData = new BlockRoundData(preRoundFirstBlock.getHeader().getExtend());
round = calcRound(preRoundFirstBlock.getHeader().getHeight(), roundIndex, preRoundData.getRoundEndTime(), false);
if (roundIndex > (preRoundData.getRoundIndex() + 1)) {
long roundTime = PocConsensusConstant.BLOCK_TIME_INTERVAL_SECOND * 1000L * round.getMemberCount();
long startTime = round.getStartTime() + (roundIndex - (preRoundData.getRoundIndex() + 1)) * roundTime;
round.setStartTime(startTime);
List<PocMeetingMember> memberList = round.getMemberList();
for (PocMeetingMember member : memberList) {
member.setRoundStartTime(round.getStartTime());
}
Collections.sort(memberList);
round.setMemberList(memberList);
}
ROUND_MAP.put(round.getIndex(), round);
} else {
return null;
}
}
if (needPreRound && round.getPreRound() == null) {
if (null == preRoundFirstBlock) {
Block firstBlock = getBlockService().getPreRoundFirstBlock(preRoundIndex);
if (null == firstBlock) {
return null;
}
preRoundFirstBlock = firstBlock;
preRoundData = new BlockRoundData(preRoundFirstBlock.getHeader().getExtend());
}
if (preRoundFirstBlock.getHeader().getHeight() == 0) {
round.setPreRound(calcRound(0, 1, preRoundData.getRoundStartTime(), false));
return round;
}
Block preblock = getBlockService().getBlock(preRoundFirstBlock.getHeader().getPreHash().getDigestHex());
if (null == preblock) {
return null;
}
BlockRoundData preBlockRoundData = new BlockRoundData(preblock.getHeader().getExtend());
round.setPreRound(getRound(preBlockRoundData.getRoundIndex(), preRoundIndex, false));
}
StringBuilder str = new StringBuilder();
for (PocMeetingMember member : round.getMemberList()) {
str.append(member.getPackingAddress());
str.append(" ,order:" + member.getPackingIndexOfRound());
str.append(",packEndTime:" + new Date(member.getPackEndTime()));
str.append("\n");
}
if(null==round.getPreRound()){
BlockLog.info("calc new round:index:" + round.getIndex() + " , start:" + new Date(round.getStartTime())
+ ", netTime:(" + new Date(TimeService.currentTimeMillis()).toString() + ") , members:\n :" + str);
}else {
BlockLog.info("calc new round:index:" + round.getIndex() + " ,preIndex:" + round.getPreRound().getIndex() + " , start:" + new Date(round.getStartTime())
+ ", netTime:(" + new Date(TimeService.currentTimeMillis()).toString() + ") , members:\n :" + str);
}
return round;
}
#location 33
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public PocMeetingRound getCurrentRound() {
return currentRound;
} | #vulnerable code
public PocMeetingRound getCurrentRound() {
Block currentBlock = NulsContext.getInstance().getBestBlock();
BlockRoundData currentRoundData = new BlockRoundData(currentBlock.getHeader().getExtend());
PocMeetingRound round = ROUND_MAP.get(currentRoundData.getRoundIndex());
if (null == round) {
round = resetCurrentMeetingRound();
}
return round;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public BlockInfo request(long start, long end, long split) {
lock.lock();
this.startTime = TimeService.currentTimeMillis();
requesting = true;
hashesMap.clear();
calcMap.clear();
this.start = start;
this.end = end;
this.split = split;
GetBlocksHashRequest event = new GetBlocksHashRequest(start, end, split);
nodeIdList = this.eventBroadcaster.broadcastAndCache(event, false);
if (nodeIdList.isEmpty()) {
Log.error("get best height from net faild!");
lock.unlock();
return null;
}
return this.getBlockInfo();
} | #vulnerable code
public BlockInfo request(long start, long end, long split) {
lock.lock();
this.startTime = TimeService.currentTimeMillis();
requesting = true;
hashesMap.clear();
calcMap.clear();
this.start = start;
this.end = end;
this.split = split;
GetBlocksHashRequest event = new GetBlocksHashRequest(start, end, split);
nodeIdList = this.eventBroadcaster.broadcastAndCache(event, false);
if (nodeIdList.isEmpty()) {
Log.error("get best height from net faild!");
lock.unlock();
throw new NulsRuntimeException(ErrorCode.NET_MESSAGE_ERROR, "broadcast faild!");
}
return this.getBlockInfo();
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Transaction getTx(NulsDigestData hash) {
TransactionPo po = txDao.get(hash.getDigestHex());
if (null != po) {
try {
Transaction tx = UtxoTransferTool.toTransaction(po);
return tx;
} catch (Exception e) {
Log.error(e);
}
}
return null;
} | #vulnerable code
@Override
public Transaction getTx(NulsDigestData hash) {
TransactionLocalPo localPo = localTxDao.get(hash.getDigestHex());
if (localPo != null) {
try {
Transaction tx = UtxoTransferTool.toTransaction(localPo);
return tx;
} catch (Exception e) {
Log.error(e);
}
}
TransactionPo po = txDao.get(hash.getDigestHex());
if (null == po) {
return null;
}
try {
Transaction tx = UtxoTransferTool.toTransaction(po);
return tx;
} catch (Exception e) {
Log.error(e);
}
return null;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public NetworkEventResult process(BaseEvent networkEvent, Node node) {
VersionEvent event = (VersionEvent) networkEvent;
// String key = event.getHeader().getEventType() + "-" + node.getId();
// if (cacheService.existEvent(key)) {
// Log.info("----------VersionEventHandler cacheService existEvent--------");
// getNetworkService().removeNode(node.getId());
// return null;
// }
// cacheService.putEvent(key, event, true);
if (event.getBestBlockHeight() < 0) {
throw new NetworkMessageException(ErrorCode.NET_MESSAGE_ERROR);
}
node.setVersionMessage(event);
if (!node.isHandShake()) {
node.setStatus(Node.HANDSHAKE);
node.setPort(event.getExternalPort());
node.setLastTime(TimeService.currentTimeMillis());
getNodeDao().saveChange(NodeTransferTool.toPojo(node));
}
return null;
} | #vulnerable code
@Override
public NetworkEventResult process(BaseEvent networkEvent, Node node) {
VersionEvent event = (VersionEvent) networkEvent;
String key = event.getHeader().getEventType() + "-" + node.getId();
if (cacheService.existEvent(key)) {
Log.info("----------VersionEventHandler cacheService existEvent--------");
getNetworkService().removeNode(node.getId());
return null;
}
cacheService.putEvent(key, event, true);
if (event.getBestBlockHeight() < 0) {
throw new NetworkMessageException(ErrorCode.NET_MESSAGE_ERROR);
}
node.setVersionMessage(event);
if (!node.isHandShake()) {
node.setStatus(Node.HANDSHAKE);
node.setPort(event.getExternalPort());
node.setLastTime(TimeService.currentTimeMillis());
getNodeDao().saveChange(NodeTransferTool.toPojo(node));
}
return null;
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean saveLocalTx(Transaction tx) throws IOException {
try {
ValidateResult validateResult = this.conflictDetectTx(tx, this.getWaitingTxList());
if (validateResult.isFailed()) {
throw new NulsRuntimeException(validateResult.getErrorCode(), validateResult.getMessage());
}
} catch (Exception e) {
Log.error(e);
throw new NulsRuntimeException(e);
}
TransactionLocalPo localPo = UtxoTransferTool.toLocalTransactionPojo(tx);
localPo.setTxStatus(TransactionLocalPo.UNCONFIRM);
localTxDao.save(localPo);
ledgerCacheService.putLocalTx(tx);
// save relation
if (tx instanceof AbstractCoinTransaction) {
AbstractCoinTransaction abstractTx = (AbstractCoinTransaction) tx;
UtxoData utxoData = (UtxoData) abstractTx.getCoinData();
if (utxoData.getInputs() != null && !utxoData.getInputs().isEmpty()) {
UtxoInput input = utxoData.getInputs().get(0);
UtxoOutput output = input.getFrom();
TxAccountRelationPo relationPo = new TxAccountRelationPo();
relationPo.setTxHash(tx.getHash().getDigestHex());
relationPo.setAddress(output.getAddress());
relationDataService.save(relationPo);
}
}
return true;
} | #vulnerable code
@Override
public boolean saveLocalTx(Transaction tx) throws IOException {
try {
ValidateResult validateResult = this.conflictDetectTx(tx, this.getWaitingTxList());
if (validateResult.isFailed()) {
throw new NulsRuntimeException(validateResult.getErrorCode(), validateResult.getMessage());
}
} catch (Exception e) {
Log.error(e);
throw new NulsRuntimeException(e);
}
TransactionLocalPo localPo = UtxoTransferTool.toLocalTransactionPojo(tx);
localPo.setTxStatus(TransactionLocalPo.UNCONFIRM);
localTxDao.save(localPo);
// save relation
if (tx instanceof AbstractCoinTransaction) {
AbstractCoinTransaction abstractTx = (AbstractCoinTransaction) tx;
UtxoData utxoData = (UtxoData) abstractTx.getCoinData();
if (utxoData.getInputs() != null && !utxoData.getInputs().isEmpty()) {
UtxoInput input = utxoData.getInputs().get(0);
UtxoOutput output = input.getFrom();
TxAccountRelationPo relationPo = new TxAccountRelationPo();
relationPo.setTxHash(tx.getHash().getDigestHex());
relationPo.setAddress(output.getAddress());
relationDataService.save(relationPo);
}
}
// if (tx instanceof AbstractCoinTransaction) {
// AbstractCoinTransaction abstractTx = (AbstractCoinTransaction) tx;
// UtxoData utxoData = (UtxoData) abstractTx.getCoinData();
//
// for (UtxoOutput output : utxoData.getOutputs()) {
// if (output.isUsable() && NulsContext.LOCAL_ADDRESS_LIST.contains(output.getAddress())) {
// output.setTxHash(tx.getHash());
// ledgerCacheService.putUtxo(output.getKey(), output, false);
// }
// }
// }
return true;
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Result transfer(byte[] from, byte[] to, Na values, String password, String remark) {
try {
AssertUtil.canNotEmpty(from, "the from address can not be empty");
AssertUtil.canNotEmpty(to, "the to address can not be empty");
AssertUtil.canNotEmpty(values, "the amount can not be empty");
if (values.isZero() || values.isLessThan(Na.ZERO)) {
return Result.getFailed("amount error");
}
Result<Account> accountResult = accountService.getAccount(from);
if (accountResult.isFailed()) {
return accountResult;
}
Account account = accountResult.getData();
if (accountService.isEncrypted(account).isSuccess()) {
AssertUtil.canNotEmpty(password, "the password can not be empty");
Result passwordResult = accountService.validPassword(account, password);
if (passwordResult.isFailed()) {
return passwordResult;
}
}
TransferTransaction tx = new TransferTransaction();
if (StringUtils.isNotBlank(remark)) {
try {
tx.setRemark(remark.getBytes(NulsConfig.DEFAULT_ENCODING));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
tx.setTime(TimeService.currentTimeMillis());
CoinData coinData = new CoinData();
Coin toCoin = new Coin(to, values);
coinData.getTo().add(toCoin);
CoinDataResult coinDataResult = getCoinData(from, values, tx.size() + P2PKHScriptSig.DEFAULT_SERIALIZE_LENGTH);
if (!coinDataResult.isEnough()) {
return Result.getFailed(LedgerErrorCode.BALANCE_NOT_ENOUGH);
}
coinData.setFrom(coinDataResult.getCoinList());
if (coinDataResult.getChange() != null) {
coinData.getTo().add(coinDataResult.getChange());
}
tx.setCoinData(coinData);
tx.setHash(NulsDigestData.calcDigestData(tx.serialize()));
P2PKHScriptSig sig = new P2PKHScriptSig();
sig.setPublicKey(account.getPubKey());
sig.setSignData(accountService.signData(tx.getHash().serialize(), account, password));
tx.setScriptSig(sig.serialize());
Result saveResult = saveUnconfirmedTransaction(tx);
if (saveResult.isFailed()) {
return saveResult;
}
Result sendResult = this.transactionService.broadcastTx(tx);
if (sendResult.isFailed()) {
return sendResult;
}
return Result.getSuccess().setData(tx.getHash().getDigestHex());
} catch (IOException e) {
Log.error(e);
return Result.getFailed(e.getMessage());
} catch (NulsException e) {
Log.error(e);
return Result.getFailed(e.getErrorCode());
}
} | #vulnerable code
@Override
public Result transfer(byte[] from, byte[] to, Na values, String password, String remark) {
try {
AssertUtil.canNotEmpty(from, "the from address can not be empty");
AssertUtil.canNotEmpty(to, "the to address can not be empty");
AssertUtil.canNotEmpty(values, "the amount can not be empty");
if (values.isZero() || values.isLessThan(Na.ZERO)) {
return Result.getFailed("amount error");
}
Result<Account> accountResult = accountService.getAccount(from);
if (accountResult.isFailed()) {
return accountResult;
}
Account account = accountResult.getData();
if (accountService.isEncrypted(account).isSuccess()) {
AssertUtil.canNotEmpty(password, "the password can not be empty");
Result passwordResult = accountService.validPassword(account, password);
if (passwordResult.isFailed()) {
return passwordResult;
}
}
TransferTransaction tx = new TransferTransaction();
if (StringUtils.isNotBlank(remark)) {
try {
tx.setRemark(remark.getBytes(NulsConfig.DEFAULT_ENCODING));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
tx.setTime(TimeService.currentTimeMillis());
CoinData coinData = new CoinData();
Coin toCoin = new Coin(to, values);
coinData.getTo().add(toCoin);
CoinDataResult coinDataResult = getCoinData(from, values, tx.size() + P2PKHScriptSig.DEFAULT_SERIALIZE_LENGTH);
if (!coinDataResult.isEnough()) {
return Result.getFailed(LedgerErrorCode.BALANCE_NOT_ENOUGH);
}
coinData.setFrom(coinDataResult.getCoinList());
if (coinDataResult.getChange() != null) {
coinData.getTo().add(coinDataResult.getChange());
}
tx.setCoinData(coinData);
tx.setHash(NulsDigestData.calcDigestData(tx.serialize()));
P2PKHScriptSig sig = new P2PKHScriptSig();
sig.setPublicKey(account.getPubKey());
sig.setSignData(accountService.signData(tx.getHash().serialize(), account, password));
tx.setScriptSig(sig.serialize());
ValidateResult result1 = tx.verify();
if (result1.isFailed()) {
return result1;
}
result1 = this.ledgerService.verifyCoinData(tx, this.getAllUnconfirmedTransaction().getData());
if (result1.isFailed()) {
return result1;
}
Result saveResult = saveUnconfirmedTransaction(tx);
if (saveResult.isFailed()) {
return saveResult;
}
Result sendResult = this.transactionService.broadcastTx(tx);
if (sendResult.isFailed()) {
return sendResult;
}
return Result.getSuccess().setData(tx.getHash().getDigestHex());
} catch (IOException e) {
Log.error(e);
return Result.getFailed(e.getMessage());
} catch (NulsException e) {
Log.error(e);
return Result.getFailed(e.getErrorCode());
}
}
#location 53
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void reset() {
lock.lock();try{
this.needReSet = true;
ROUND_MAP.clear();
this.init();}finally {
lock.unlock();
}
} | #vulnerable code
public void reset() {
this.needReSet = true;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private List<Transaction> getTxList(Block block, List<NulsDigestData> txHashList) {
List<Transaction> txList = new ArrayList<>();
for (Transaction tx : block.getTxs()) {
if (txHashList.contains(tx.getHash())) {
txList.add(tx);
}
}
if (txList.size() != txHashList.size()) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
return txList;
} | #vulnerable code
private List<Transaction> getTxList(Block block, List<NulsDigestData> txHashList) {
List<Transaction> txList = new ArrayList<>();
Map<String, Integer> allTxMap = new HashMap<>();
for (int i = 0; i < block.getHeader().getTxCount(); i++) {
Transaction tx = block.getTxs().get(i);
allTxMap.put(tx.getHash().getDigestHex(), i);
}
for (NulsDigestData hash : txHashList) {
txList.add(block.getTxs().get(allTxMap.get(hash.getDigestHex())));
}
if (txList.size() != txHashList.size()) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
return txList;
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onMessage(GetBlockRequest message, Node fromNode) {
BlockSendThread.offer(message, fromNode);
} | #vulnerable code
@Override
public void onMessage(GetBlockRequest message, Node fromNode) throws NulsException {
GetBlockDataParam param = message.getMsgBody();
if (param.getSize() > MAX_SIZE) {
return;
}
if (param.getSize() == 1) {
Block block = null;
Result<Block> result = this.blockService.getBlock(param.getStartHash());
if (result.isFailed()) {
sendNotFound(param.getStartHash(), fromNode);
return;
}
block = result.getData();
sendBlock(block, fromNode);
return;
}
Block chainStartBlock = null;
Result<Block> blockResult = this.blockService.getBlock(param.getStartHash());
if (blockResult.isFailed()) {
sendNotFound(param.getStartHash(), fromNode);
return;
} else {
chainStartBlock = blockResult.getData();
}
Block chainEndBlock = null;
blockResult = this.blockService.getBlock(param.getEndHash());
if (blockResult.isFailed()) {
sendNotFound(param.getEndHash(), fromNode);
return;
} else {
chainEndBlock = blockResult.getData();
}
if (chainEndBlock.getHeader().getHeight() < chainStartBlock.getHeader().getHeight()) {
return;
}
long end = param.getStart() + param.getSize() - 1;
if (chainStartBlock.getHeader().getHeight() > param.getStart() || chainEndBlock.getHeader().getHeight() < end) {
sendNotFound(param.getStartHash(), fromNode);
return;
}
Block block = chainEndBlock;
while (true) {
this.sendBlock(block, fromNode);
if (block.getHeader().getHash().equals(chainStartBlock.getHeader().getHash())) {
break;
}
if (block.getHeader().getPreHash().equals(chainStartBlock.getHeader().getHash())) {
block = chainStartBlock;
continue;
}
block = blockService.getBlock(block.getHeader().getPreHash()).getData();
}
}
#location 46
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void init() {
//load five(CACHE_COUNT) round from db on the start time ;
Block bestBlock = getBestBlock();
BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend());
for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) {
Block firstBlock = getBlockService().getPreRoundFirstBlock(i - 1);
BlockRoundData preRoundData = new BlockRoundData(firstBlock.getHeader().getExtend());
PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, preRoundData.getRoundEndTime());
ROUND_MAP.put(round.getIndex(), round);
Log.debug("load the round data index:{}", round.getIndex());
}
} | #vulnerable code
public void init() {
//load five(CACHE_COUNT) round from db on the start time ;
Block bestBlock = getBestBlock();
BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend());
for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) {
Block firstBlock = getBlockService().getPreRoundFirstBlock(i - 1);
BlockRoundData thisRoundData = new BlockRoundData(firstBlock.getHeader().getExtend());
PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, thisRoundData.getRoundStartTime());
ROUND_MAP.put(round.getIndex(), round);
Log.debug("load the round data index:{}", round.getIndex());
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void requestTxGroup(NulsDigestData blockHash, String nodeId) {
GetTxGroupRequest request = new GetTxGroupRequest();
GetTxGroupParam data = new GetTxGroupParam();
data.setBlockHash(blockHash);
List<NulsDigestData> txHashList = new ArrayList<>();
SmallBlock smb = temporaryCacheManager.getSmallBlock(blockHash.getDigestHex());
for (NulsDigestData txHash : smb.getTxHashList()) {
boolean exist = txCacheManager.txExist(txHash);
if (!exist) {
txHashList.add(txHash);
}
}
if (txHashList.isEmpty()) {
BlockHeader header = temporaryCacheManager.getBlockHeader(smb.getBlockHash().getDigestHex());
if (null == header) {
return;
}
Block block = new Block();
block.setHeader(header);
List<Transaction> txs = new ArrayList<>();
for (NulsDigestData txHash : smb.getTxHashList()) {
Transaction tx = txCacheManager.getTx(txHash);
if (null == tx) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
txs.add(tx);
}
block.setTxs(txs);
ValidateResult vResult = block.verify();
if (vResult.isFailed()&&vResult.getErrorCode()!=ErrorCode.ORPHAN_BLOCK&&vResult.getErrorCode()!=ErrorCode.ORPHAN_TX) {
return;
}
blockManager.addBlock(block, false,nodeId);
AssembledBlockNotice notice = new AssembledBlockNotice();
notice.setEventBody(header);
eventBroadcaster.publishToLocal(notice);
return;
}
data.setTxHashList(txHashList);
request.setEventBody(data);
tgRequest.put(blockHash.getDigestHex(), System.currentTimeMillis());
Integer value = tgRequestCount.get(blockHash.getDigestHex());
if (null == value) {
value = 0;
}
tgRequestCount.put(blockHash.getDigestHex(), 1 + value);
if (StringUtils.isBlank(nodeId)) {
eventBroadcaster.broadcastAndCache(request, false);
} else {
eventBroadcaster.sendToNode(request, nodeId);
}
} | #vulnerable code
public void requestTxGroup(NulsDigestData blockHash, String nodeId) {
GetTxGroupRequest request = new GetTxGroupRequest();
GetTxGroupParam data = new GetTxGroupParam();
data.setBlockHash(blockHash);
List<NulsDigestData> txHashList = new ArrayList<>();
SmallBlock smb = temporaryCacheManager.getSmallBlock(blockHash.getDigestHex());
for (NulsDigestData txHash : smb.getTxHashList()) {
boolean exist = txCacheManager.txExist(txHash);
if (!exist) {
txHashList.add(txHash);
}
}
if (txHashList.isEmpty()) {
BlockHeader header = temporaryCacheManager.getBlockHeader(smb.getBlockHash().getDigestHex());
if (null == header) {
return;
}
Block block = new Block();
block.setHeader(header);
List<Transaction> txs = new ArrayList<>();
for (NulsDigestData txHash : smb.getTxHashList()) {
Transaction tx = txCacheManager.getTx(txHash);
if (null == tx) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
txs.add(tx);
}
block.setTxs(txs);
ValidateResult<RedPunishData> vResult = block.verify();
if (null == vResult || vResult.isFailed()) {
if (vResult.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) {
RedPunishData redPunishData = vResult.getObject();
ConsensusMeetingRunner.putPunishData(redPunishData);
}
return;
}
blockManager.addBlock(block, false,nodeId);
AssembledBlockNotice notice = new AssembledBlockNotice();
notice.setEventBody(header);
eventBroadcaster.publishToLocal(notice);
return;
}
data.setTxHashList(txHashList);
request.setEventBody(data);
tgRequest.put(blockHash.getDigestHex(), System.currentTimeMillis());
Integer value = tgRequestCount.get(blockHash.getDigestHex());
if (null == value) {
value = 0;
}
tgRequestCount.put(blockHash.getDigestHex(), 1 + value);
if (StringUtils.isBlank(nodeId)) {
eventBroadcaster.broadcastAndCache(request, false);
} else {
eventBroadcaster.sendToNode(request, nodeId);
}
}
#location 34
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
@DbSession
public void save(CoinData coinData, Transaction tx) throws NulsException {
UtxoData utxoData = (UtxoData) coinData;
List<UtxoInputPo> inputPoList = new ArrayList<>();
List<UtxoOutput> spends = new ArrayList<>();
List<UtxoOutputPo> spendPoList = new ArrayList<>();
List<TxAccountRelationPo> txRelations = new ArrayList<>();
Set<String> addressSet = new HashSet<>();
lock.lock();
try {
processDataInput(utxoData, inputPoList, spends, spendPoList, addressSet);
List<UtxoOutputPo> outputPoList = new ArrayList<>();
for (int i = 0; i < utxoData.getOutputs().size(); i++) {
UtxoOutput output = utxoData.getOutputs().get(i);
output = ledgerCacheService.getUtxo(output.getKey());
if (output == null) {
throw new NulsRuntimeException(ErrorCode.DATA_NOT_FOUND);
}
if (output.isConfirm() || OutPutStatusEnum.UTXO_SPENT == output.getStatus()) {
Log.error("-----------------------------------save() output status is" + output.getStatus().name());
throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "use a not legal utxo");
}
if (OutPutStatusEnum.UTXO_UNCONFIRM_CONSENSUS_LOCK == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_CONSENSUS_LOCK);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_TIME_LOCK == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_TIME_LOCK);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_UNSPEND);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND);
}
UtxoOutputPo outputPo = UtxoTransferTool.toOutputPojo(output);
outputPoList.add(outputPo);
addressSet.add(Address.fromHashs(output.getAddress()).getBase58());
}
for (String address : addressSet) {
TxAccountRelationPo relationPo = new TxAccountRelationPo(tx.getHash().getDigestHex(), address);
txRelations.add(relationPo);
}
outputDataService.updateStatus(spendPoList);
inputDataService.save(inputPoList);
outputDataService.save(outputPoList);
relationDataService.save(txRelations);
afterSaveDatabase(spends, utxoData, tx);
for (String address : addressSet) {
UtxoTransactionTool.getInstance().calcBalance(address, true);
}
} catch (Exception e) {
//rollback
// Log.warn(e.getMessage(), e);
// for (UtxoOutput output : utxoData.getOutputs()) {
// ledgerCacheService.removeUtxo(output.getKey());
// }
// for (UtxoOutput spend : spends) {
// ledgerCacheService.updateUtxoStatus(spend.getKey(), UtxoOutput.UTXO_CONFIRM_LOCK, UtxoOutput.UTXO_SPENT);
// }
throw e;
} finally {
lock.unlock();
}
} | #vulnerable code
@Override
@DbSession
public void save(CoinData coinData, Transaction tx) throws NulsException {
UtxoData utxoData = (UtxoData) coinData;
List<UtxoInputPo> inputPoList = new ArrayList<>();
List<UtxoOutput> spends = new ArrayList<>();
List<UtxoOutputPo> spendPoList = new ArrayList<>();
List<TxAccountRelationPo> txRelations = new ArrayList<>();
Set<String> addressSet = new HashSet<>();
try {
processDataInput(utxoData, inputPoList, spends, spendPoList, addressSet);
List<UtxoOutputPo> outputPoList = new ArrayList<>();
for (int i = 0; i < utxoData.getOutputs().size(); i++) {
UtxoOutput output = utxoData.getOutputs().get(i);
output = ledgerCacheService.getUtxo(output.getKey());
if (output == null) {
throw new NulsRuntimeException(ErrorCode.DATA_NOT_FOUND);
}
if (output.isConfirm() || OutPutStatusEnum.UTXO_SPENT == output.getStatus()) {
Log.error("-----------------------------------save() output status is" + output.getStatus().name());
throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "use a not legal utxo");
}
if (OutPutStatusEnum.UTXO_UNCONFIRM_CONSENSUS_LOCK == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_CONSENSUS_LOCK);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_TIME_LOCK == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_TIME_LOCK);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_UNSPEND);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND);
}
UtxoOutputPo outputPo = UtxoTransferTool.toOutputPojo(output);
outputPoList.add(outputPo);
addressSet.add(Address.fromHashs(output.getAddress()).getBase58());
}
for (String address : addressSet) {
TxAccountRelationPo relationPo = new TxAccountRelationPo(tx.getHash().getDigestHex(), address);
txRelations.add(relationPo);
}
outputDataService.updateStatus(spendPoList);
inputDataService.save(inputPoList);
outputDataService.save(outputPoList);
relationDataService.save(txRelations);
afterSaveDatabase(spends, utxoData, tx);
for (String address : addressSet) {
UtxoTransactionTool.getInstance().calcBalance(address, true);
}
} catch (Exception e) {
//rollback
// Log.warn(e.getMessage(), e);
// for (UtxoOutput output : utxoData.getOutputs()) {
// ledgerCacheService.removeUtxo(output.getKey());
// }
// for (UtxoOutput spend : spends) {
// ledgerCacheService.updateUtxoStatus(spend.getKey(), UtxoOutput.UTXO_CONFIRM_LOCK, UtxoOutput.UTXO_SPENT);
// }
throw e;
}
}
#location 13
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onEvent(SmallBlockEvent event, String fromId) {
ValidateResult result = event.getEventBody().verify();
if (result.isFailed()) {
return;
}
temporaryCacheManager.cacheSmallBlock(event.getEventBody());
downloadDataUtils.removeSmallBlock(event.getEventBody().getBlockHash().getDigestHex());
GetTxGroupRequest request = new GetTxGroupRequest();
GetTxGroupParam param = new GetTxGroupParam();
param.setBlockHash(event.getEventBody().getBlockHash());
for (NulsDigestData hash : event.getEventBody().getTxHashList()) {
if (!receivedTxCacheManager.txExist(hash) && !orphanTxCacheManager.txExist(hash)) {
param.addHash(hash);
}
}
if (param.getTxHashList().isEmpty()) {
BlockHeader header = temporaryCacheManager.getBlockHeader(event.getEventBody().getBlockHash().getDigestHex());
if (null == header) {
return;
}
Block block = new Block();
block.setHeader(header);
List<Transaction> txs = new ArrayList<>();
for (NulsDigestData txHash : event.getEventBody().getTxHashList()) {
Transaction tx = receivedTxCacheManager.getTx(txHash);
if (null == tx) {
tx = orphanTxCacheManager.getTx(txHash);
}
if (null == tx) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
txs.add(tx);
}
block.setTxs(txs);
ValidateResult<RedPunishData> vResult = block.verify();
if (null == vResult || (vResult.isFailed() && vResult.getErrorCode() != ErrorCode.ORPHAN_TX)) {
if (vResult.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) {
RedPunishData data = vResult.getObject();
ConsensusMeetingRunner.putPunishData(data);
networkService.blackNode(fromId, NodePo.BLACK);
} else {
networkService.removeNode(fromId, NodePo.YELLOW);
}
return;
}
blockManager.addBlock(block, false, fromId);
downloadDataUtils.removeTxGroup(block.getHeader().getHash().getDigestHex());
BlockHeaderEvent headerEvent = new BlockHeaderEvent();
headerEvent.setEventBody(header);
eventBroadcaster.broadcastHashAndCacheAysn(headerEvent, false, fromId);
return;
}
request.setEventBody(param);
this.eventBroadcaster.sendToNode(request, fromId);
} | #vulnerable code
@Override
public void onEvent(SmallBlockEvent event, String fromId) {
ValidateResult result = event.getEventBody().verify();
if (result.isFailed()) {
return;
}
temporaryCacheManager.cacheSmallBlock(event.getEventBody());
downloadDataUtils.removeSmallBlock(event.getEventBody().getBlockHash().getDigestHex());
GetTxGroupRequest request = new GetTxGroupRequest();
GetTxGroupParam param = new GetTxGroupParam();
param.setBlockHash(event.getEventBody().getBlockHash());
for (NulsDigestData hash : event.getEventBody().getTxHashList()) {
if (!receivedTxCacheManager.txExist(hash) && !orphanTxCacheManager.txExist(hash)) {
param.addHash(hash);
}
}
if (param.getTxHashList().isEmpty()) {
BlockHeader header = temporaryCacheManager.getBlockHeader(event.getEventBody().getBlockHash().getDigestHex());
if (null == header) {
return;
}
Block block = new Block();
block.setHeader(header);
List<Transaction> txs = new ArrayList<>();
for (NulsDigestData txHash : event.getEventBody().getTxHashList()) {
Transaction tx = receivedTxCacheManager.getTx(txHash);
if (null == tx) {
tx = orphanTxCacheManager.getTx(txHash);
}
if (null == tx) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
txs.add(tx);
}
block.setTxs(txs);
ValidateResult<RedPunishData> vResult = block.verify();
if (null == vResult || (vResult.isFailed() && vResult.getErrorCode() != ErrorCode.ORPHAN_TX)) {
if (vResult.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) {
RedPunishData data = vResult.getObject();
ConsensusMeetingRunner.putPunishData(data);
networkService.blackNode(fromId, NodePo.BLACK);
} else {
networkService.removeNode(fromId, NodePo.YELLOW);
}
return;
}
blockManager.addBlock(block, false, fromId);
downloadDataUtils.removeTxGroup(block.getHeader().getHash().getDigestHex());
BlockHeaderEvent headerEvent = new BlockHeaderEvent();
headerEvent.setEventBody(header);
eventBroadcaster.broadcastHashAndCacheAysn(headerEvent, false, fromId);
return;
}
request.setEventBody(param);
this.eventBroadcaster.sendToNode(request, fromId);
}
#location 39
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onEvent(BlockEvent event, String fromId) {
Block block = event.getEventBody();
ValidateResult result = block.verify();
if (result.isFailed()) {
if (result.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) {
networkService.blackNode(fromId, NodePo.YELLOW);
}
return;
}
if (BlockBatchDownloadUtils.getInstance().downloadedBlock(fromId, block)) {
return;
}
blockCacheManager.cacheBlock(block);
} | #vulnerable code
@Override
public void onEvent(BlockEvent event, String fromId) {
Block block = event.getEventBody();
ValidateResult result = block.verify();
if (result.isFailed()) {
if (result.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) {
networkService.removeNode(fromId);
}
return;
}
if (BlockBatchDownloadUtils.getInstance().downloadedBlock(fromId, block)) {
return;
}
blockCacheManager.cacheBlock(block);
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void start() {
List<Peer> peers = discovery.getLocalPeers(10);
if (peers.isEmpty()) {
peers = getSeedPeers();
}
for (Peer peer : peers) {
peer.setType(Peer.OUT);
addPeerToGroup(NetworkConstant.NETWORK_PEER_OUT_GROUP, peer);
}
boolean isConsensus = NulsContext.MODULES_CONFIG.getCfgValue(PocConsensusConstant.CFG_CONSENSUS_SECTION, PocConsensusConstant.PROPERTY_DELEGATE_PEER, false);
if (isConsensus) {
network.maxOutCount(network.maxOutCount() * 5);
network.maxInCount(network.maxInCount() * 5);
}
System.out.println("-----------peerManager start");
//start heart beat thread
ThreadManager.createSingleThreadAndRun(NulsConstant.MODULE_ID_NETWORK, "peerDiscovery", this.discovery);
} | #vulnerable code
public void start() {
List<Peer> peers = discovery.getLocalPeers(10);
if (peers.isEmpty()) {
peers = getSeedPeers();
}
for (Peer peer : peers) {
peer.setType(Peer.OUT);
addPeerToGroup(NetworkConstant.NETWORK_PEER_OUT_GROUP, peer);
}
boolean isConsensus = ConfigLoader.getCfgValue(PocConsensusConstant.CFG_CONSENSUS_SECTION, PocConsensusConstant.PROPERTY_DELEGATE_PEER, false);
if (isConsensus) {
network.maxOutCount(network.maxOutCount() * 5);
network.maxInCount(network.maxInCount() * 5);
}
System.out.println("-----------peerManager start");
//start heart beat thread
ThreadManager.createSingleThreadAndRun(NulsConstant.MODULE_ID_NETWORK, "peerDiscovery", this.discovery);
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected Block createBlock() {
// new a block header
BlockHeader blockHeader = new BlockHeader();
blockHeader.setHeight(0);
blockHeader.setPreHash(NulsDigestData.calcDigestData("00000000000".getBytes()));
blockHeader.setTime(1L);
blockHeader.setTxCount(1);
blockHeader.setMerkleHash(NulsDigestData.calcDigestData(new byte[20]));
// add a round data
BlockRoundData roundData = new BlockRoundData();
roundData.setConsensusMemberCount(1);
roundData.setPackingIndexOfRound(1);
roundData.setRoundIndex(1);
roundData.setRoundStartTime(1L);
try {
blockHeader.setExtend(roundData.serialize());
} catch (IOException e) {
throw new NulsRuntimeException(e);
}
// new a block of height 0
Block block = new Block();
block.setHeader(blockHeader);
List<Transaction> txs = new ArrayList<>();
block.setTxs(txs);
Transaction tx = new TestTransaction();
txs.add(tx);
List<NulsDigestData> txHashList = block.getTxHashList();
blockHeader.setMerkleHash(NulsDigestData.calcMerkleDigestData(txHashList));
NulsSignData signData = signDigest(blockHeader.getHash().getDigestBytes(), ecKey);
P2PKHScriptSig sig = new P2PKHScriptSig();
sig.setSignData(signData);
sig.setPublicKey(ecKey.getPubKey());
blockHeader.setScriptSig(sig);
return block;
} | #vulnerable code
protected Block createBlock() {
// new a block header
BlockHeader blockHeader = new BlockHeader();
blockHeader.setHeight(0);
blockHeader.setPreHash(NulsDigestData.calcDigestData("00000000000".getBytes()));
blockHeader.setTime(1L);
blockHeader.setTxCount(1);
blockHeader.setMerkleHash(NulsDigestData.calcDigestData(new byte[20]));
// add a round data
BlockRoundData roundData = new BlockRoundData();
roundData.setConsensusMemberCount(1);
roundData.setPackingIndexOfRound(1);
roundData.setRoundIndex(1);
roundData.setRoundStartTime(1L);
try {
blockHeader.setExtend(roundData.serialize());
} catch (IOException e) {
throw new NulsRuntimeException(e);
}
// new a block of height 0
Block block = new Block();
block.setHeader(blockHeader);
List<Transaction> txs = new ArrayList<>();
block.setTxs(txs);
Transaction tx = new TestTransaction();
txs.add(tx);
List<NulsDigestData> txHashList = block.getTxHashList();
blockHeader.setMerkleHash(NulsDigestData.calcMerkleDigestData(txHashList));
NulsSignData signData = null;
try {
signData = accountService.signData(blockHeader.getHash().getDigestBytes(), ecKey);
} catch (NulsException e) {
e.printStackTrace();
}
P2PKHScriptSig sig = new P2PKHScriptSig();
sig.setSignData(signData);
sig.setPublicKey(ecKey.getPubKey());
blockHeader.setScriptSig(sig);
return block;
}
#location 38
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void checkIt() {
int maxSize = 0;
BlockHeaderChain longestChain = null;
StringBuilder str = new StringBuilder("++++++++++++++++++++++++chain info:");
for (BlockHeaderChain chain : chainList) {
str.append("+++++++++++\nchain:start-" + chain.getHeaderDigestList().get(0).getHeight() + ", end-" + chain.getHeaderDigestList().get(chain.size() - 1).getHeight());
int listSize = chain.size();
if (maxSize < listSize) {
maxSize = listSize;
longestChain = chain;
} else if (maxSize == listSize) {
HeaderDigest hd = chain.getLastHd();
HeaderDigest hd_long = longestChain.getLastHd();
if (hd.getTime() < hd_long.getTime()) {
longestChain = chain;
}
}
}
if (tempIndex % 10 == 0) {
BlockLog.info(str.toString());
tempIndex++;
}
if (this.approvingChain != null && !this.approvingChain.getId().equals(longestChain.getId())) {
BlockService blockService = NulsContext.getServiceBean(BlockService.class);
for (int i=approvingChain.size()-1;i>=0;i--) {
HeaderDigest hd = approvingChain.getHeaderDigestList().get(i);
try {
blockService.rollbackBlock(hd.getHash());
} catch (NulsException e) {
Log.error(e);
}
}
for(int i=0;i<longestChain.getHeaderDigestList().size();i++){
HeaderDigest hd = longestChain.getHeaderDigestList().get(i);
blockService.approvalBlock(hd.getHash());
}
}
this.approvingChain = longestChain;
Set<String> rightHashSet = new HashSet<>();
Set<String> removeHashSet = new HashSet<>();
for (int i = chainList.size() - 1; i >= 0; i--) {
BlockHeaderChain chain = chainList.get(i);
if (chain.size() < (maxSize - 6)) {
removeHashSet.addAll(chain.getHashSet());
this.chainList.remove(chain);
} else {
rightHashSet.addAll(chain.getHashSet());
}
}
for (String hash : removeHashSet) {
if (!rightHashSet.contains(hash)) {
confirmingBlockCacheManager.removeBlock(hash);
}
}
} | #vulnerable code
private void checkIt() {
int maxSize = 0;
BlockHeaderChain longestChain = null;
StringBuilder str = new StringBuilder("++++++++++++++++++++++++chain info:");
for (BlockHeaderChain chain : chainList) {
str.append("+++++++++++\nchain:start-" + chain.getHeaderDigestList().get(0).getHeight() + ", end-" + chain.getHeaderDigestList().get(chain.size() - 1).getHeight());
int listSize = chain.size();
if (maxSize < listSize) {
maxSize = listSize;
longestChain = chain;
} else if (maxSize == listSize) {
HeaderDigest hd = chain.getLastHd();
HeaderDigest hd_long = longestChain.getLastHd();
if (hd.getTime() < hd_long.getTime()) {
longestChain = chain;
}
}
}
if (tempIndex % 10 == 0) {
BlockLog.info(str.toString());
tempIndex++;
}
if (this.approvingChain != null || !this.approvingChain.getId().equals(longestChain.getId())) {
BlockService blockService = NulsContext.getServiceBean(BlockService.class);
for (int i=approvingChain.size()-1;i>=0;i--) {
HeaderDigest hd = approvingChain.getHeaderDigestList().get(i);
try {
blockService.rollbackBlock(hd.getHash());
} catch (NulsException e) {
Log.error(e);
}
}
for(int i=0;i<longestChain.getHeaderDigestList().size();i++){
HeaderDigest hd = longestChain.getHeaderDigestList().get(i);
blockService.approvalBlock(hd.getHash());
}
}
this.approvingChain = longestChain;
Set<String> rightHashSet = new HashSet<>();
Set<String> removeHashSet = new HashSet<>();
for (int i = chainList.size() - 1; i >= 0; i--) {
BlockHeaderChain chain = chainList.get(i);
if (chain.size() < (maxSize - 6)) {
removeHashSet.addAll(chain.getHashSet());
this.chainList.remove(chain);
} else {
rightHashSet.addAll(chain.getHashSet());
}
}
for (String hash : removeHashSet) {
if (!rightHashSet.contains(hash)) {
confirmingBlockCacheManager.removeBlock(hash);
}
}
}
#location 28
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
SocketChannel channel = (SocketChannel) ctx.channel();
Attribute<Node> nodeAttribute = channel.attr(key);
Node node = nodeAttribute.get();
String nodeId = node == null ? null : node.getId();
Log.debug("---------------------- client channelRegistered -----------" + nodeId);
Map<String, Node> nodes = nodeManager.getNodes();
//Map<String, Node> nodes = getNetworkService().getNodes();
// If a node with the same IP already in nodes, as a out node, can not add anymore
for (Node n : nodes.values()) {
//both ip and port equals , it means the node is myself
if (n.getIp().equals(node.getIp()) && !n.getPort().equals(node.getSeverPort())) {
Log.debug("----------------------client: it already had a connection: " + n.getId() + " type:" + n.getType() + ", this connection: " + nodeId + "---------------------- ");
ctx.channel().close();
return;
}
}
} | #vulnerable code
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
SocketChannel channel = (SocketChannel) ctx.channel();
Attribute<Node> nodeAttribute = channel.attr(key);
Node node = nodeAttribute.get();
String nodeId = node == null ? null : node.getId();
Log.debug("---------------------- client channelRegistered -----------" + nodeId);
Map<String, Node> nodes = null;
//Map<String, Node> nodes = getNetworkService().getNodes();
// If a node with the same IP already in nodes, as a out node, can not add anymore
for (Node n : nodes.values()) {
//both ip and port equals , it means the node is myself
if (n.getIp().equals(node.getIp()) && !n.getPort().equals(node.getSeverPort())) {
Log.debug("----------------------client: it already had a connection: " + n.getId() + " type:" + n.getType() + ", this connection: " + nodeId + "---------------------- ");
ctx.channel().close();
return;
}
}
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Transaction getTx(NulsDigestData hash) {
TransactionPo po = txDao.get(hash.getDigestHex());
if (null != po) {
try {
Transaction tx = UtxoTransferTool.toTransaction(po);
return tx;
} catch (Exception e) {
Log.error(e);
}
}
return null;
} | #vulnerable code
@Override
public Transaction getTx(NulsDigestData hash) {
TransactionLocalPo localPo = localTxDao.get(hash.getDigestHex());
if (localPo != null) {
try {
Transaction tx = UtxoTransferTool.toTransaction(localPo);
return tx;
} catch (Exception e) {
Log.error(e);
}
}
TransactionPo po = txDao.get(hash.getDigestHex());
if (null == po) {
return null;
}
try {
Transaction tx = UtxoTransferTool.toTransaction(po);
return tx;
} catch (Exception e) {
Log.error(e);
}
return null;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Result<Account> importAccount(String prikey, String password) {
if (!ECKey.isValidPrivteHex(prikey)) {
return Result.getFailed(AccountErrorCode.PARAMETER_ERROR);
}
Account account;
try {
account = AccountTool.createAccount(prikey);
} catch (NulsException e) {
return Result.getFailed(AccountErrorCode.FAILED);
}
if (StringUtils.validPassword(password)) {
try {
account.encrypt(password);
} catch (NulsException e) {
Log.error(e);
}
}
AccountPo po = new AccountPo(account);
accountStorageService.saveAccount(po);
LOCAL_ADDRESS_LIST.add(account.getAddress().toString());
accountLedgerService.importAccountLedger(account.getAddress().getBase58());
return Result.getSuccess().setData(account);
} | #vulnerable code
@Override
public Result<Account> importAccount(String prikey, String password) {
if (!ECKey.isValidPrivteHex(prikey)) {
return Result.getFailed(AccountErrorCode.PARAMETER_ERROR);
}
Account account;
try {
account = AccountTool.createAccount(prikey);
} catch (NulsException e) {
return Result.getFailed(AccountErrorCode.FAILED);
}
Account accountDB = getAccountByAddress(account.getAddress().toString());
if (null != accountDB) {
return Result.getFailed(AccountErrorCode.ACCOUNT_EXIST);
}
if (StringUtils.validPassword(password)) {
try {
account.encrypt(password);
} catch (NulsException e) {
Log.error(e);
}
}
AccountPo po = new AccountPo(account);
accountStorageService.saveAccount(po);
LOCAL_ADDRESS_LIST.add(account.getAddress().toString());
accountLedgerService.importAccountLedger(account.getAddress().getBase58());
return Result.getSuccess().setData(account);
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void reSendLocalTx() throws NulsException {
List<Transaction> txList = ledgerCacheService.getUnconfirmTxList();
List<Transaction> helpList = new ArrayList<>();
for (Transaction tx : txList) {
if (TimeService.currentTimeMillis() - tx.getTime() < DateUtil.MINUTE_TIME * 2) {
continue;
}
ValidateResult result = getLedgerService().verifyTx(tx, helpList);
if (result.isFailed()) {
getLocalDataService().deleteUnCofirmTx(tx.getHash().getDigestHex());
ledgerCacheService.removeLocalTx(tx.getHash().getDigestHex());
continue;
}
Transaction transaction = getLedgerService().getTx(tx.getHash());
if (transaction != null) {
getLocalDataService().deleteUnCofirmTx(tx.getHash().getDigestHex());
ledgerCacheService.removeLocalTx(tx.getHash().getDigestHex());
continue;
}
helpList.add(tx);
TransactionEvent event = new TransactionEvent();
event.setEventBody(tx);
getEventBroadcaster().publishToLocal(event);
}
} | #vulnerable code
private void reSendLocalTx() throws NulsException {
List<Transaction> txList = getLedgerCacheService().getUnconfirmTxList();
List<Transaction> helpList = new ArrayList<>();
for (Transaction tx : txList) {
if (TimeService.currentTimeMillis() - tx.getTime() < DateUtil.MINUTE_TIME * 2) {
continue;
}
ValidateResult result = getLedgerService().verifyTx(tx, helpList);
if (result.isFailed()) {
getLocalDataService().deleteUnCofirmTx(tx.getHash().getDigestHex());
ledgerCacheService.removeLocalTx(tx.getHash().getDigestHex());
continue;
}
Transaction transaction = getLedgerService().getTx(tx.getHash());
if (transaction != null) {
getLocalDataService().deleteUnCofirmTx(tx.getHash().getDigestHex());
ledgerCacheService.removeLocalTx(tx.getHash().getDigestHex());
continue;
}
helpList.add(tx);
TransactionEvent event = new TransactionEvent();
event.setEventBody(tx);
getEventBroadcaster().publishToLocal(event);
}
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean isLocalHasSeed(List<Account> accountList) {
for (Account account : accountList) {
for (String seedAddress : csManager.getSeedNodeList()) {
if (seedAddress.equals(account.getAddress().getBase58())) {
return true;
}
}
}
return false;
} | #vulnerable code
public boolean isLocalHasSeed(List<Account> accountList) {
for (Account account : accountList) {
for (PocMeetingMember seed : this.getDefaultSeedList()) {
if (seed.getAgentAddress().equals(account.getAddress().getBase58())) {
return true;
}
}
}
return false;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void start() {
try {
ChannelFuture future = boot.connect(node.getIp(), node.getSeverPort()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
socketChannel = (SocketChannel) future.channel();
} else {
Log.info("Client connect to host error: " + future.cause() + ", remove node: " + node.getId());
getNetworkService().removeNode(node.getId());
}
}
});
future.channel().closeFuture().sync();
} catch (Exception e) {
//maybe time out or refused or something
if (socketChannel != null) {
socketChannel.close();
}
Log.error("Client start exception:" + e.getMessage() + ", remove node: " + node.getId());
getNetworkService().removeNode(node.getId());
}
} | #vulnerable code
public void start() {
try {
ChannelFuture future = boot.connect(node.getIp(), node.getSeverPort()).sync();
if (future.isSuccess()) {
socketChannel = (SocketChannel) future.channel();
} else {
System.out.println("---------------client start !success remove node-----------------" + node.getId());
getNetworkService().removeNode(node.getId());
}
future.channel().closeFuture().sync();
} catch (Exception e) {
Log.debug("-------------NettyClient start error: " + e.getMessage());
//maybe time out or refused or something
if (socketChannel != null) {
socketChannel.close();
}
System.out.println("---------------client start exception remove node-----------------" + node.getId());
getNetworkService().removeNode(node.getId());
}
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public List<Transaction> getWaitingTxList() throws NulsException {
return ledgerCacheService.getUnconfirmTxList();
} | #vulnerable code
@Override
public List<Transaction> getWaitingTxList() throws NulsException {
List<TransactionLocalPo> poList = localTxDao.getUnConfirmTxs();
List<Transaction> txList = new ArrayList<>();
for (TransactionLocalPo po : poList) {
Transaction tx = UtxoTransferTool.toTransaction(po);
txList.add(tx);
}
return txList;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void start() {
this.waitForDependencyRunning(MessageBusConstant.MODULE_ID_MESSAGE_BUS);
this.waitForDependencyInited(ConsensusConstant.MODULE_ID_CONSENSUS);
this.initHandlers();
((DownloadServiceImpl) NulsContext.getServiceBean(DownloadService.class)).start();
} | #vulnerable code
@Override
public void start() {
this.waitForDependencyRunning(MessageBusConstant.MODULE_ID_MESSAGE_BUS);
this.initHandlers();
((DownloadServiceImpl) NulsContext.getServiceBean(DownloadService.class)).start();
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected void parse(NulsByteBuffer byteBuffer) throws NulsException {
address = Address.fromHashs(byteBuffer.readByLengthByte());
alias = new String(byteBuffer.readByLengthByte());
encryptedPriKey = byteBuffer.readByLengthByte();
pubKey = byteBuffer.readByLengthByte();
status = (int) (byteBuffer.readByte());
extend = byteBuffer.readByLengthByte();
} | #vulnerable code
@Override
protected void parse(NulsByteBuffer byteBuffer) throws NulsException {
alias = new String(byteBuffer.readByLengthByte());
address = new Address(new String(byteBuffer.readByLengthByte()));
encryptedPriKey = byteBuffer.readByLengthByte();
pubKey = byteBuffer.readByLengthByte();
status = (int)(byteBuffer.readVarInt());
extend = byteBuffer.readByLengthByte();
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void calc() {
if (null == nodeIdList || nodeIdList.isEmpty()) {
throw new NulsRuntimeException(ErrorCode.FAILED, "success list of nodes is empty!");
}
int size = nodeIdList.size();
int halfSize = (size + 1) / 2;
//todo 临时去掉=号
if (hashesMap.size() < halfSize) {
return;
}
BlockInfo result = null;
for (String key : calcMap.keySet()) {
List<String> nodes = calcMap.get(key);
//todo 临时加上=号
if (nodes.size() >= halfSize) {
result = new BlockInfo();
BlockHashResponse response = hashesMap.get(nodes.get(0));
Long bestHeight = 0L;
NulsDigestData bestHash = null;
for (int i = 0; i < response.getHeightList().size(); i++) {
Long height = response.getHeightList().get(i);
NulsDigestData hash = response.getHashList().get(i);
if (height > bestHeight) {
bestHash = hash;
bestHeight = height;
}
result.putHash(height, hash);
}
result.setBestHash(bestHash);
result.setBestHeight(bestHeight);
result.setNodeIdList(nodes);
result.setFinished(true);
break;
}
}
if (null != result) {
bestBlockInfo = result;
} else if (size == calcMap.size()) {
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
Log.error(e);
}
this.request(start, end, split);
}
} | #vulnerable code
private void calc() {
if (null == nodeIdList || nodeIdList.isEmpty()) {
throw new NulsRuntimeException(ErrorCode.FAILED, "success list of nodes is empty!");
}
int size = nodeIdList.size();
int halfSize = (size + 1) / 2;
if (hashesMap.size() <= halfSize) {
return;
}
BlockInfo result = null;
for (String key : calcMap.keySet()) {
List<String> nodes = calcMap.get(key);
if (nodes.size() > halfSize) {
result = new BlockInfo();
BlockHashResponse response = hashesMap.get(result.getNodeIdList().get(0));
Long bestHeight = 0L;
NulsDigestData bestHash = null;
for (int i = 0; i < response.getHeightList().size(); i++) {
Long height = response.getHeightList().get(i);
NulsDigestData hash = response.getHashList().get(i);
if (height > bestHeight) {
bestHash = hash;
bestHeight = height;
}
result.putHash(height, hash);
}
result.setBestHash(bestHash);
result.setBestHeight(bestHeight);
result.setNodeIdList(nodes);
result.setFinished(true);
break;
}
}
if (null != result) {
bestBlockInfo = result;
} else if (size == calcMap.size()) {
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
Log.error(e);
}
this.request(start, end, split);
}
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public TransferTransaction createTransferTx(CoinTransferData transferData, String password, String remark) throws Exception {
TransferTransaction tx = new TransferTransaction(transferData, password);
tx.setRemark(remark.getBytes(NulsContext.DEFAULT_ENCODING));
tx.setHash(NulsDigestData.calcDigestData(tx.serialize()));
AccountService accountService = getAccountService();
if (transferData.getFrom().isEmpty()) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
Account account = accountService.getAccount(transferData.getFrom().get(0));
tx.setSign(accountService.signData(tx.getHash(), account, password));
return tx;
} | #vulnerable code
public TransferTransaction createTransferTx(CoinTransferData transferData, String password, String remark) throws Exception {
TransferTransaction tx = new TransferTransaction(transferData, password);
tx.setRemark(remark.getBytes(NulsContext.DEFAULT_ENCODING));
tx.setHash(NulsDigestData.calcDigestData(tx.serialize()));
tx.setSign(getAccountService().signData(tx.getHash(), password));
return tx;
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void handleKey(SelectionKey key) {
ConnectionHandler handler = (ConnectionHandler) key.attachment();
try {
if (!key.isValid()) {
// Key has been cancelled, make sure the socket gets closed
System.out.println("--------------------destory 1" + handler.peer.getIp());
handler.peer.destroy();
return;
}
if (key.isReadable()) {
// Do a socket read and invoke the connection's receiveBytes message
int len = handler.channel.read(handler.readBuffer);
if (len == 0) {
// Was probably waiting on a write
return;
} else if (len == -1) {
// Socket was closed
key.cancel();
System.out.println("--------------------destory 2" + handler.peer.getIp());
handler.peer.destroy();
return;
}
// "flip" the buffer - setting the limit to the current position and setting position to 0
handler.readBuffer.flip();
handler.peer.receiveMessage(handler.readBuffer);
// Now drop the bytes which were read by compacting readBuff (resetting limit and keeping relative position)
handler.readBuffer.compact();
}
if (key.isWritable()) {
handler.writeBytes();
}
} catch (Exception e) {
// This can happen eg if the channel closes while the thread is about to get killed
// (ClosedByInterruptException), or if handler.connection.receiveBytes throws something
e.printStackTrace();
Throwable t = e;
Log.warn("Error handling SelectionKey: {}", t.getMessage() != null ? t.getMessage() : t.getClass().getName());
System.out.println("--------------------destory 3" + handler.peer.getIp());
handler.peer.destroy();
}
} | #vulnerable code
public static void handleKey(SelectionKey key) {
ConnectionHandler handler = (ConnectionHandler) key.attachment();
try {
if (!key.isValid()) {
// Key has been cancelled, make sure the socket gets closed
System.out.println("--------------------destory 1");
handler.peer.destroy();
return;
}
if (key.isReadable()) {
// Do a socket read and invoke the connection's receiveBytes message
int len = handler.channel.read(handler.readBuffer);
if (len == 0) {
// Was probably waiting on a write
return;
} else if (len == -1) {
// Socket was closed
key.cancel();
System.out.println(handler.peer.getIp());
System.out.println("--------------------destory 2");
handler.peer.destroy();
return;
}
System.out.println("--------len : " + len);
// "flip" the buffer - setting the limit to the current position and setting position to 0
handler.readBuffer.flip();
handler.peer.receiveMessage(handler.readBuffer);
// Now drop the bytes which were read by compacting readBuff (resetting limit and keeping relative position)
handler.readBuffer.compact();
}
if (key.isWritable()) {
handler.writeBytes();
}
} catch (Exception e) {
// This can happen eg if the channel closes while the thread is about to get killed
// (ClosedByInterruptException), or if handler.connection.receiveBytes throws something
e.printStackTrace();
Throwable t = e;
Log.warn("Error handling SelectionKey: {}", t.getMessage() != null ? t.getMessage() : t.getClass().getName());
System.out.println("--------------------destory 3");
handler.peer.destroy();
}
}
#location 27
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public HeaderDigest getLastHd() {
List<HeaderDigest> list = new ArrayList<>(headerDigestList);
if (list.size() > 0) {
return list.get(list.size() - 1);
}
return null;
} | #vulnerable code
public HeaderDigest getLastHd() {
if (null == lastHd) {
List<HeaderDigest> list = new ArrayList<>(headerDigestList);
if(list.size() > 0) {
this.lastHd = list.get(list.size() - 1);
}
}
return lastHd;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public double readDouble() throws NulsException { byte[] bytes = this.readByLengthByte();
if(null==bytes){
return 0;
}
return Utils.bytes2Double(bytes);
} | #vulnerable code
public double readDouble() throws NulsException {
return Utils.bytes2Double(this.readByLengthByte());
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean addBlockHashResponse(String nodeId, BlockHashResponse response) {
if (!hashesMap.containsKey(nodeId)) {
return false;
}
if (!requesting) {
return false;
}
if (hashesMap.get(nodeId) == null) {
hashesMap.put(nodeId, response);
} else {
BlockHashResponse instance = hashesMap.get(nodeId);
instance.merge(response);
hashesMap.put(nodeId, instance);
}
if (response.getHeightList().get(response.getHeightList().size() - 1) < end) {
return true;
}
String key = response.getHash().getDigestHex();
List<String> nodes = calcMap.get(key);
if (null == nodes) {
nodes = new ArrayList<>();
}
if (!nodes.contains(nodeId)) {
nodes.add(nodeId);
}
calcMap.put(key, nodes);
calc();
return true;
} | #vulnerable code
public boolean addBlockHashResponse(String nodeId, BlockHashResponse response) {
if (!hashesMap.containsKey(nodeId)) {
return false;
}
if (!requesting) {
return false;
}
if(hashesMap.get(nodeId)==null){
hashesMap.put(nodeId, response);
}else{
BlockHashResponse instance = hashesMap.get(nodeId);
instance.merge(response);
hashesMap.put(nodeId,instance);
}
if(response.getHeightList().get(response.getHeightList().size()-1)<end){
return true;
}
String key = response.getHash().getDigestHex();
List<String> nodes = calcMap.get(key);
if (null == nodes) {
nodes = new ArrayList<>();
}
if (!nodes.contains(nodeId)) {
nodes.add(nodeId);
}
calcMap.put(key, nodes);
calc();
return true;
}
#location 27
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public ValidateResult validate(AliasTransaction tx) {
Alias alias = tx.getTxData();
if (!Address.validAddress(alias.getAddress())) {
return ValidateResult.getFailedResult(ErrorCode.ADDRESS_ERROR);
}
if (!StringUtils.validAlias(alias.getAlias())) {
return ValidateResult.getFailedResult(ErrorCode.ALIAS_ERROR);
}
long aliasValue = 0;
UtxoData utxoData = (UtxoData) tx.getCoinData();
for (UtxoInput input : utxoData.getInputs()) {
aliasValue += input.getFrom().getValue();
}
if (aliasValue < AccountConstant.ALIAS_NA.getValue() + tx.getFee().getValue()) {
return ValidateResult.getFailedResult(ErrorCode.INVALID_INPUT);
}
if (tx.getStatus() == TxStatusEnum.CACHED) {
List<Transaction> txList = getLedgerService().getCacheTxList(TransactionConstant.TX_TYPE_SET_ALIAS);
if (txList != null && tx.size() > 0) {
for (Transaction trx : txList) {
if (trx.getHash().equals(tx.getHash())) {
continue;
}
Alias a = ((AliasTransaction) trx).getTxData();
if (alias.getAddress().equals(a.getAddress())) {
return ValidateResult.getFailedResult(ErrorCode.ACCOUNT_ALREADY_SET_ALIAS);
}
if (alias.getAlias().equals(a.getAlias())) {
return ValidateResult.getFailedResult("The alias has been occupied");
}
}
}
}
AliasPo aliasPo = getAliasDataService().get(alias.getAlias());
if (aliasPo != null) {
return ValidateResult.getFailedResult(ErrorCode.ALIAS_EXIST);
}
return ValidateResult.getSuccessResult();
} | #vulnerable code
@Override
public ValidateResult validate(AliasTransaction tx) {
Alias alias = tx.getTxData();
if (!Address.validAddress(alias.getAddress())) {
return ValidateResult.getFailedResult("The address format error");
}
if (!StringUtils.validAlias(alias.getAlias())) {
return ValidateResult.getFailedResult("The alias is between 3 to 20 characters");
}
long aliasValue = 0;
UtxoData utxoData = (UtxoData) tx.getCoinData();
for (UtxoInput input : utxoData.getInputs()) {
if (input.getFrom() == null) {
return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX);
}
aliasValue += input.getFrom().getValue();
}
if (aliasValue < AccountConstant.ALIAS_NA.add(getLedgerService().getTxFee(TransactionConstant.TX_TYPE_SET_ALIAS)).getValue()) {
return ValidateResult.getFailedResult("utxo not enough");
}
if (tx.getStatus() == TxStatusEnum.CACHED) {
List<Transaction> txList = getLedgerService().getCacheTxList(TransactionConstant.TX_TYPE_SET_ALIAS);
if (txList != null && tx.size() > 0) {
for (Transaction trx : txList) {
if(trx.getHash().equals(tx.getHash())) {
continue;
}
Alias a = ((AliasTransaction) trx).getTxData();
if (alias.getAddress().equals(a.getAddress())) {
return ValidateResult.getFailedResult("Alias has been set up ");
}
if (alias.getAlias().equals(a.getAlias())) {
return ValidateResult.getFailedResult("The alias has been occupied");
}
}
}
}
AliasPo aliasPo = getAliasDataService().get(alias.getAlias());
if (aliasPo != null) {
return ValidateResult.getFailedResult("The alias has been occupied");
}
return ValidateResult.getSuccessResult();
}
#location 20
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void start() {
List<Peer> peers = discovery.getLocalPeers(10);
if (peers.isEmpty()) {
peers = getSeedPeers();
}
for (Peer peer : peers) {
peer.setType(Peer.OUT);
addPeerToGroup(NetworkConstant.NETWORK_PEER_OUT_GROUP, peer);
}
boolean isConsensus = NulsContext.MODULES_CONFIG.getCfgValue(PocConsensusConstant.CFG_CONSENSUS_SECTION, PocConsensusConstant.PROPERTY_DELEGATE_PEER, false);
if (isConsensus) {
network.maxOutCount(network.maxOutCount() * 5);
network.maxInCount(network.maxInCount() * 5);
}
System.out.println("-----------peerManager start");
//start heart beat thread
ThreadManager.createSingleThreadAndRun(NulsConstant.MODULE_ID_NETWORK, "peerDiscovery", this.discovery);
} | #vulnerable code
public void start() {
List<Peer> peers = discovery.getLocalPeers(10);
if (peers.isEmpty()) {
peers = getSeedPeers();
}
for (Peer peer : peers) {
peer.setType(Peer.OUT);
addPeerToGroup(NetworkConstant.NETWORK_PEER_OUT_GROUP, peer);
}
boolean isConsensus = ConfigLoader.getCfgValue(PocConsensusConstant.CFG_CONSENSUS_SECTION, PocConsensusConstant.PROPERTY_DELEGATE_PEER, false);
if (isConsensus) {
network.maxOutCount(network.maxOutCount() * 5);
network.maxInCount(network.maxInCount() * 5);
}
System.out.println("-----------peerManager start");
//start heart beat thread
ThreadManager.createSingleThreadAndRun(NulsConstant.MODULE_ID_NETWORK, "peerDiscovery", this.discovery);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public ValidateResult validate(AliasTransaction tx) {
Alias alias = tx.getTxData();
if (StringUtils.isBlank(alias.getAddress()) || new Address(alias.getAddress()).getHash().length != 23) {
return ValidateResult.getFailedResult("The address format error");
}
if (!StringUtils.validAlias(alias.getAlias())) {
return ValidateResult.getFailedResult("The alias is between 3 to 20 characters");
}
List<Transaction> txList = getLedgerService().getCacheTxList(TransactionConstant.TX_TYPE_SET_ALIAS);
if (txList != null && tx.size() > 0) {
for (Transaction trx : txList) {
Alias a = ((AliasTransaction) trx).getTxData();
if(alias.getAddress().equals(a.getAlias())) {
return ValidateResult.getFailedResult("The alias has been occupied");
}
if(alias.getAlias().equals(a.getAlias())){
return ValidateResult.getFailedResult("The alias has been occupied");
}
}
}
AliasPo aliasPo = getAliasDataService().get(alias.getAlias());
if (aliasPo != null) {
return ValidateResult.getFailedResult("The alias has been occupied");
}
return ValidateResult.getSuccessResult();
} | #vulnerable code
@Override
public ValidateResult validate(AliasTransaction tx) {
Alias alias = tx.getTxData();
if (StringUtils.isBlank(alias.getAddress()) || new Address(alias.getAddress()).getHash().length != 23) {
return ValidateResult.getFailedResult("The address format error");
}
if (!StringUtils.validAlias(alias.getAlias())) {
return ValidateResult.getFailedResult("The alias is between 3 to 20 characters");
}
AliasPo aliasPo = getAliasDataService().get(alias.getAlias());
if (aliasPo != null) {
return ValidateResult.getFailedResult("The alias has been occupied");
}
return ValidateResult.getSuccessResult();
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Set<K> keySet(String cacheTitle) {
Cache cache = this.cacheManager.getCache(cacheTitle);
if (null == cache) {
return new HashSet<>();
}
Iterator it = cache.iterator();
Set<K> set = new HashSet<>();
while (it.hasNext()) {
Cache.Entry<K, T> entry = (Cache.Entry<K, T>) it.next();
set.add((K) entry.getKey());
}
return set;
} | #vulnerable code
@Override
public Set<K> keySet(String cacheTitle) {
Iterator it = cacheManager.getCache(cacheTitle).iterator();
Set<K> set = new HashSet<>();
while (it.hasNext()) {
Cache.Entry<K, T> entry = (Cache.Entry<K, T>) it.next();
set.add((K) entry.getKey());
}
return set;
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Result createArea(String areaName) {
// prevent too many areas
if(AREAS.size() > (MAX -1)) {
return new Result(false, "KV_AREA_CREATE_ERROR");
}
if(StringUtils.isBlank(areaName)) {
return Result.getFailed(ErrorCode.NULL_PARAMETER);
}
if (AREAS.containsKey(areaName)) {
return new Result(true, "KV_AREA_EXISTS");
}
if(!checkPathLegal(areaName)) {
return new Result(false, "KV_AREA_CREATE_ERROR");
}
Result result;
try {
File dir = new File(dataPath + File.separator + areaName);
if(!dir.exists()) {
dir.mkdir();
}
String filePath = dataPath + File.separator + areaName + File.separator + BASE_DB_NAME;
DB db = openDB(filePath, true);
AREAS.put(areaName, db);
result = Result.getSuccess();
} catch (Exception e) {
Log.error("error create area: " + areaName, e);
result = new Result(false, "KV_AREA_CREATE_ERROR");
}
return result;
} | #vulnerable code
public static Result createArea(String areaName) {
// prevent too many areas
if(AREAS.size() > (MAX -1)) {
return new Result(false, "KV_AREA_CREATE_ERROR");
}
if(StringUtils.isBlank(areaName)) {
return Result.getFailed(ErrorCode.NULL_PARAMETER);
}
if (AREAS.containsKey(areaName)) {
return new Result(true, "KV_AREA_EXISTS");
}
//TODO 特殊字符校验
if(!checkPathLegal(areaName)) {
return new Result(false, "KV_AREA_CREATE_ERROR");
}
Result result;
try {
File dir = new File(dataPath + File.separator + areaName);
if(!dir.exists()) {
dir.mkdir();
}
String filePath = dataPath + File.separator + areaName + File.separator + BASE_DB_NAME;
DB db = openDB(filePath, true);
AREAS.put(areaName, db);
result = Result.getSuccess();
} catch (Exception e) {
Log.error("error create area: " + areaName, e);
result = new Result(false, "KV_AREA_CREATE_ERROR");
}
return result;
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void nextRound() throws NulsException, IOException {
packingRoundManager.calc(getBestBlock());
PocMeetingRound round = packingRoundManager.getCurrentRound();
while (TimeService.currentTimeMillis() < round.getStartTime()) {
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
Log.error(e);
}
}
boolean imIn = consensusManager.isPartakePacking() &&round.getLocalPacker() != null;
if (imIn) {
startMeeting(round);
}
} | #vulnerable code
private void nextRound() throws NulsException, IOException {
packingRoundManager.calc(getBestBlock());
while (TimeService.currentTimeMillis() < (packingRoundManager.getCurrentRound().getStartTime())) {
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
Log.error(e);
}
}
boolean imIn = consensusManager.isPartakePacking() && packingRoundManager.getCurrentRound().getLocalPacker() != null;
if (imIn) {
startMeeting();
}
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void init() {
//load five(CACHE_COUNT) round from db on the start time ;
Block bestBlock = getBestBlock();
BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend());
for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) {
Block firstBlock = getBlockService().getRoundFirstBlock(bestBlock, i - 1);
BlockRoundData thisRoundData = new BlockRoundData(firstBlock.getHeader().getExtend());
PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, thisRoundData.getRoundStartTime());
ROUND_MAP.put(round.getIndex(), round);
Log.debug("load the round data index:{}", round.getIndex());
}
} | #vulnerable code
public void init() {
//load five(CACHE_COUNT) round from db on the start time ;
Block bestBlock = NulsContext.getInstance().getBestBlock();
BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend());
for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) {
Block firstBlock = getBlockService().getRoundFirstBlock(bestBlock, i - 1);
BlockRoundData thisRoundData = new BlockRoundData(firstBlock.getHeader().getExtend());
PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, thisRoundData.getRoundStartTime());
ROUND_MAP.put(round.getIndex(), round);
Log.debug("load the round data index:{}", round.getIndex());
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public PocMeetingRound getCurrentRound() {
return currentRound;
} | #vulnerable code
public PocMeetingRound getCurrentRound() {
Block currentBlock = NulsContext.getInstance().getBestBlock();
BlockRoundData currentRoundData = new BlockRoundData(currentBlock.getHeader().getExtend());
PocMeetingRound round = ROUND_MAP.get(currentRoundData.getRoundIndex());
if (null == round) {
round = resetCurrentMeetingRound();
}
return round;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void rollbackAppraval(Block block) {
if (null == block) {
Log.warn("the block is null!");
return;
}
this.rollbackTxList(block.getTxs(), 0, block.getTxs().size());
Block preBlock =this.getBlock(block.getHeader().getPreHash().getDigestHex());
context.setBestBlock(preBlock);
PackingRoundManager.getValidateInstance().calc(preBlock);
List<String> hashList = this.bifurcateProcessor.getHashList(block.getHeader().getHeight() - 1);
if (hashList.size() > 1) {
this.rollbackAppraval(preBlock);
}
} | #vulnerable code
private void rollbackAppraval(Block block) {
if (null == block) {
Log.warn("the block is null!");
return;
}
this.rollbackTxList(block.getTxs(), 0, block.getTxs().size());
PackingRoundManager.getValidateInstance().calc(this.getBlock(block.getHeader().getPreHash().getDigestHex()));
List<String> hashList = this.bifurcateProcessor.getHashList(block.getHeader().getHeight() - 1);
if (hashList.size() > 1) {
Block preBlock = confirmingBlockCacheManager.getBlock(block.getHeader().getPreHash().getDigestHex());
context.setBestBlock(preBlock);
this.rollbackAppraval(preBlock);
}
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void init() {
//load five(CACHE_COUNT) round from db on the start time ;
Block bestBlock = getBestBlock();
BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend());
for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) {
Block firstBlock = getBlockService().getPreRoundFirstBlock(i - 1);
BlockRoundData preRoundData = new BlockRoundData(firstBlock.getHeader().getExtend());
PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, preRoundData.getRoundEndTime());
ROUND_MAP.put(round.getIndex(), round);
Log.debug("load the round data index:{}", round.getIndex());
}
} | #vulnerable code
public void init() {
//load five(CACHE_COUNT) round from db on the start time ;
Block bestBlock = getBestBlock();
BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend());
for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) {
Block firstBlock = getBlockService().getPreRoundFirstBlock(i - 1);
BlockRoundData thisRoundData = new BlockRoundData(firstBlock.getHeader().getExtend());
PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, thisRoundData.getRoundStartTime());
ROUND_MAP.put(round.getIndex(), round);
Log.debug("load the round data index:{}", round.getIndex());
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private PocMeetingRound calcNextRound(BlockHeader bestBlockHeader, long bestHeight, BlockRoundData bestRoundData) {
PocMeetingRound round = new PocMeetingRound();
round.setIndex(bestRoundData.getRoundIndex() + 1);
round.setStartTime(bestRoundData.getRoundEndTime());
long calcHeight = 0L;
if (bestRoundData.getPackingIndexOfRound() == bestRoundData.getConsensusMemberCount() || NulsContext.getInstance().getBestHeight() <= bestHeight) {
calcHeight = bestHeight - PocConsensusConstant.CONFIRM_BLOCK_COUNT;
} else {
Block bestBlock = NulsContext.getInstance().getBestBlock();
if (null == bestBlock) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "best block is null");
}
BlockRoundData localBestRoundData = new BlockRoundData(bestBlock.getHeader().getExtend());
if (localBestRoundData.getRoundIndex() == bestRoundData.getRoundIndex() && localBestRoundData.getPackingIndexOfRound() != localBestRoundData.getConsensusMemberCount()) {
throw new NulsRuntimeException(ErrorCode.FAILED, "The next round of information is not yet available.");
} else if (localBestRoundData.getRoundIndex() == bestRoundData.getRoundIndex() && localBestRoundData.getPackingIndexOfRound() == localBestRoundData.getConsensusMemberCount()) {
return calcNextRound(bestBlock.getHeader(), bestBlock.getHeader().getHeight(), localBestRoundData);
} else {
Block nextRoundFirstBlock = getBlockService().getRoundFirstBlockFromDb(round.getIndex());
if (null == nextRoundFirstBlock) {
long height = bestHeight + 1;
while (true) {
Block block = getBlockService().getBlock(height);
height++;
BlockRoundData blockRoundData = new BlockRoundData(block.getHeader().getExtend());
if (blockRoundData.getRoundIndex() == round.getIndex()) {
nextRoundFirstBlock = block;
break;
}
}
}
calcHeight = nextRoundFirstBlock.getHeader().getHeight() - PocConsensusConstant.CONFIRM_BLOCK_COUNT - 1;
}
}
List<PocMeetingMember> memberList = getMemberList(calcHeight, round, bestBlockHeader);
Collections.sort(memberList);
round.setMemberList(memberList);
round.setMemberCount(memberList.size());
while (round.getEndTime() < TimeService.currentTimeMillis()) {
long time = TimeService.currentTimeMillis() - round.getStartTime();
long roundTime = round.getEndTime() - round.getStartTime();
long index = time / roundTime;
long startTime = round.getStartTime() + index * roundTime;
round.setStartTime(startTime);
round.setIndex(bestRoundData.getRoundIndex() + index);
}
for(PocMeetingMember member:memberList){
member.setRoundIndex(round.getIndex());
member.setRoundStartTime(round.getStartTime());
}
return round;
} | #vulnerable code
private PocMeetingRound calcNextRound(BlockHeader bestBlockHeader, long bestHeight, BlockRoundData bestRoundData) {
PocMeetingRound round = new PocMeetingRound();
round.setIndex(bestRoundData.getRoundIndex() + 1);
round.setStartTime(bestRoundData.getRoundEndTime());
long calcHeight = 0L;
if (bestRoundData.getPackingIndexOfRound() == bestRoundData.getConsensusMemberCount() || NulsContext.getInstance().getBestHeight() <= bestHeight) {
calcHeight = bestHeight - PocConsensusConstant.CONFIRM_BLOCK_COUNT;
} else {
Block bestBlock = NulsContext.getInstance().getBestBlock();
if (null == bestBlock) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "best block is null");
}
BlockRoundData localBestRoundData = new BlockRoundData(bestBlock.getHeader().getExtend());
if (localBestRoundData.getRoundIndex() == bestRoundData.getRoundIndex() && localBestRoundData.getPackingIndexOfRound() != localBestRoundData.getConsensusMemberCount()) {
throw new NulsRuntimeException(ErrorCode.FAILED, "The next round of information is not yet available.");
} else if (localBestRoundData.getRoundIndex() == bestRoundData.getRoundIndex() && localBestRoundData.getPackingIndexOfRound() == localBestRoundData.getConsensusMemberCount()) {
return calcNextRound(bestBlock.getHeader(), bestBlock.getHeader().getHeight(), localBestRoundData);
} else {
Block nextRoundFirstBlock = getBlockService().getRoundFirstBlockFromDb(round.getIndex());
if (null == nextRoundFirstBlock) {
long height = bestHeight + 1;
while (true) {
Block block = getBlockService().getBlock(height);
height++;
BlockRoundData blockRoundData = new BlockRoundData(block.getHeader().getExtend());
if (blockRoundData.getRoundIndex() == round.getIndex()) {
nextRoundFirstBlock = block;
break;
}
}
}
calcHeight = nextRoundFirstBlock.getHeader().getHeight() - PocConsensusConstant.CONFIRM_BLOCK_COUNT - 1;
}
}
List<PocMeetingMember> memberList = getMemberList(calcHeight, round, bestBlockHeader);
Collections.sort(memberList);
round.setMemberList(memberList);
round.setMemberCount(memberList.size());
while (round.getEndTime() < TimeService.currentTimeMillis()) {
long time = TimeService.currentTimeMillis() - round.getStartTime();
long roundTime = round.getEndTime() - round.getStartTime();
long index = time / roundTime;
long startTime = round.getStartTime() + index * roundTime;
round.setStartTime(startTime);
round.setIndex(bestRoundData.getRoundIndex() + index);
}
return round;
}
#location 21
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Result<Balance> getBalance(byte[] address) throws NulsException {
if (address == null || address.length != AddressTool.HASH_LENGTH) {
return Result.getFailed(AccountLedgerErrorCode.PARAMETER_ERROR);
}
if (!isLocalAccount(address)) {
return Result.getFailed(AccountLedgerErrorCode.ACCOUNT_NOT_EXIST);
}
Balance balance = balanceManager.getBalance(address).getData();
if (balance == null) {
return Result.getFailed(AccountLedgerErrorCode.ACCOUNT_NOT_EXIST);
}
return Result.getSuccess().setData(balance);
} | #vulnerable code
@Override
public Result<Balance> getBalance(byte[] address) throws NulsException {
if (address == null || address.length != AddressTool.HASH_LENGTH) {
return Result.getFailed(AccountLedgerErrorCode.PARAMETER_ERROR);
}
if (!isLocalAccount(address)) {
return Result.getFailed(AccountLedgerErrorCode.ACCOUNT_NOT_EXIST);
}
Balance balance = balanceProvider.getBalance(address).getData();
if (balance == null) {
return Result.getFailed(AccountLedgerErrorCode.ACCOUNT_NOT_EXIST);
}
return Result.getSuccess().setData(balance);
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean processingBifurcation(long height) {
lock.lock();
try {
return this.bifurcateProcessor.processing(height);
} finally {
lock.unlock();
}
} | #vulnerable code
public boolean processingBifurcation(long height) {
return this.bifurcateProcessor.processing(height);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static UtxoOutputPo toOutputPojo(UtxoOutput output) {
UtxoOutputPo po = new UtxoOutputPo();
po.setTxHash(output.getTxHash().getDigestHex());
po.setOutIndex(output.getIndex());
po.setValue(output.getValue());
po.setLockTime(output.getLockTime());
po.setAddress(Address.fromHashs(output.getAddress()).getBase58());
if(null!=output.getScript()){
po.setScript(output.getScript().getBytes());
}
po.setStatus((byte) output.getStatus());
return po;
} | #vulnerable code
public static UtxoOutputPo toOutputPojo(UtxoOutput output) {
UtxoOutputPo po = new UtxoOutputPo();
po.setTxHash(output.getTxHash().getDigestHex());
po.setOutIndex(output.getIndex());
po.setValue(output.getValue());
po.setLockTime(output.getLockTime());
po.setAddress(Address.fromHashs(output.getAddress()).getBase58());
if(null==output.getScript()){
po.setScript(output.getScript().getBytes());
}
po.setStatus((byte) output.getStatus());
return po;
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public ValidateResult validate(AbstractCoinTransaction tx) {
UtxoData data = (UtxoData) tx.getCoinData();
for (int i = 0; i < data.getInputs().size(); i++) {
UtxoInput input = data.getInputs().get(i);
UtxoOutput output = input.getFrom();
if (output == null && tx.getStatus() == TxStatusEnum.CACHED) {
return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX);
} else if (output == null) {
return ValidateResult.getFailedResult(ErrorCode.UTXO_NOT_FOUND);
}
if (tx.getStatus() == TxStatusEnum.CACHED) {
if (!output.isUsable()) {
return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE);
}
} else if (tx.getStatus() == TxStatusEnum.AGREED) {
if (!output.isSpend()) {
return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE);
}
}
byte[] owner = output.getOwner();
P2PKHScriptSig p2PKHScriptSig = null;
try {
p2PKHScriptSig = P2PKHScriptSig.createFromBytes(tx.getScriptSig());
} catch (NulsException e) {
return ValidateResult.getFailedResult(ErrorCode.DATA_ERROR);
}
byte[] user = p2PKHScriptSig.getSignerHash160();
if (!Arrays.equals(owner, user)) {
return ValidateResult.getFailedResult(ErrorCode.INVALID_OUTPUT);
}
return ValidateResult.getSuccessResult();
}
return ValidateResult.getSuccessResult();
} | #vulnerable code
@Override
public ValidateResult validate(AbstractCoinTransaction tx) {
UtxoData data = (UtxoData) tx.getCoinData();
for (int i = 0; i < data.getInputs().size(); i++) {
UtxoInput input = data.getInputs().get(i);
UtxoOutput output = input.getFrom();
if (output == null && tx.getStatus() == TxStatusEnum.CACHED) {
return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX);
}
if (tx.getStatus() == TxStatusEnum.CACHED) {
if (!output.isUsable()) {
return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE);
}
} else if (tx.getStatus() == TxStatusEnum.AGREED) {
if (!output.isSpend()) {
return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE);
}
}
byte[] owner = output.getOwner();
P2PKHScriptSig p2PKHScriptSig = null;
try {
p2PKHScriptSig = P2PKHScriptSig.createFromBytes(tx.getScriptSig());
} catch (NulsException e) {
return ValidateResult.getFailedResult(ErrorCode.DATA_ERROR);
}
byte[] user = p2PKHScriptSig.getSignerHash160();
if (!Arrays.equals(owner, user)) {
return ValidateResult.getFailedResult(ErrorCode.INVALID_OUTPUT);
}
return ValidateResult.getSuccessResult();
}
return ValidateResult.getSuccessResult();
}
#location 22
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void cacheBlockToBuffer(Block block) {
blockCacheBuffer.cacheBlock(block);
BlockLog.info("orphan cache block height:" + block.getHeader().getHeight() + ", preHash:" + block.getHeader().getPreHash() + " , hash:" + block.getHeader().getHash() + ", address:" + Address.fromHashs(block.getHeader().getPackingAddress()));
Block preBlock = blockCacheBuffer.getBlock(block.getHeader().getPreHash().getDigestHex());
if (preBlock == null) {
if (this.downloadService.getStatus() != DownloadStatus.DOWNLOADING) {
downloadUtils.getBlockByHash(block.getHeader().getPreHash().getDigestHex());
}
} else {
this.addBlock(preBlock, true, null);
}
} | #vulnerable code
private void cacheBlockToBuffer(Block block) {
blockCacheBuffer.cacheBlock(block);
BlockLog.info("orphan cache block height:" + block.getHeader().getHeight() + ", preHash:" + block.getHeader().getPreHash() + " , hash:" + block.getHeader().getHash() + ", address:" + Address.fromHashs(block.getHeader().getPackingAddress()));
Block preBlock = blockCacheBuffer.getBlock(block.getHeader().getPreHash().getDigestHex());
if (preBlock == null) {
if (NulsContext.getServiceBean(DownloadService.class).getStatus() != DownloadStatus.DOWNLOADING) {
downloadUtils.getBlockByHash(block.getHeader().getPreHash().getDigestHex());
}
} else {
this.addBlock(preBlock, true, null);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void newTx() throws Exception {
assertNotNull(service);
// new a tx
Transaction tx = new TestTransaction();
CoinData coinData = new CoinData();
List<Coin> fromList = new ArrayList<>();
fromList.add(new Coin(new byte[20], Na.NA, 0L));
coinData.setFrom(fromList);
tx.setCoinData(coinData);
tx.setTime(1l);
assertNotNull(tx);
assertNotNull(tx.getHash());
assertEquals(tx.getHash().getDigestHex(), "00204a54f8b12b75c3c1fe5f261416adaf1a1b906ccf5673bb7a133ede5a0a4c56f8");
Result result = service.newTx(tx);
assertNotNull(result);
assertTrue(result.isSuccess());
assertFalse(result.isFailed());
//test orphan
NulsDataValidator<TestTransaction> testValidator = new NulsDataValidator<TestTransaction>() {
@Override
public ValidateResult validate(TestTransaction data) {
if (data.getHash().getDigestHex().equals("0020e27ee243921bf482d7b62b6ee63c7ab1938953c834318b79fa3204c5c869e26b")) {
return ValidateResult.getFailedResult("test.transaction", TransactionErrorCode.ORPHAN_TX);
} else {
return ValidateResult.getSuccessResult();
}
}
};
ValidatorManager.addValidator(TestTransaction.class, testValidator);
tx = new TestTransaction();
tx.setTime(2l);
assertEquals(tx.getHash().getDigestHex(), "0020e27ee243921bf482d7b62b6ee63c7ab1938953c834318b79fa3204c5c869e26b");
result = service.newTx(tx);
assertNotNull(result);
assertTrue(result.isSuccess());
assertFalse(result.isFailed());
List<Transaction> list = TxMemoryPool.getInstance().getAll();
assertNotNull(list);
assertEquals(list.size(), 1);
List<Transaction> orphanList = TxMemoryPool.getInstance().getAllOrphan();
assertNotNull(orphanList);
assertEquals(orphanList.size(), 1);
} | #vulnerable code
@Test
public void newTx() throws Exception {
assertNotNull(service);
// new a tx
Transaction tx = new TestTransaction();
CoinData coinData = new CoinData();
List<Coin> fromList = new ArrayList<>();
fromList.add(new Coin(new byte[20], Na.NA, 0L));
coinData.setFrom(fromList);
tx.setCoinData(coinData);
tx.setTime(1l);
assertNotNull(tx);
assertNotNull(tx.getHash());
assertEquals(tx.getHash().getDigestHex(), "08001220b9ab6a1e5ab8e2b09758d6143bb9b66b8fe0c2c4bf49f2bfb74709ef2bf1d02f");
Result result = service.newTx(tx);
assertNotNull(result);
assertTrue(result.isSuccess());
assertFalse(result.isFailed());
//test orphan
NulsDataValidator<TestTransaction> testValidator = new NulsDataValidator<TestTransaction>() {
@Override
public ValidateResult validate(TestTransaction data) {
if (data.getHash().getDigestHex().equals("08001220328876d03b50feba0ac58d3fcb4638a2fb95847315a88c8de7105408d931999a")) {
return ValidateResult.getFailedResult("test.transaction", TransactionErrorCode.ORPHAN_TX);
} else {
return ValidateResult.getSuccessResult();
}
}
};
ValidatorManager.addValidator(TestTransaction.class, testValidator);
tx = new TestTransaction();
tx.setTime(2l);
result = service.newTx(tx);
assertNotNull(result);
assertTrue(result.isSuccess());
assertFalse(result.isFailed());
List<Transaction> list = TxMemoryPool.getInstance().getAll();
assertNotNull(list);
assertEquals(list.size(), 1);
List<Transaction> orphanList = TxMemoryPool.getInstance().getAllOrphan();
assertNotNull(orphanList);
assertEquals(orphanList.size(), 1);
}
#location 17
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void init(Map<String, String> initParams) {
String databaseType = null;
if(initParams.get("databaseType") != null) {
databaseType = initParams.get("databaseType");
}
if (!StringUtils.isEmpty(databaseType) && hasType(databaseType)) {
String path = "classpath:/database-" + databaseType + ".xml";
NulsContext.setApplicationContext(new ClassPathXmlApplicationContext(new String[]{path}, true, NulsContext.getApplicationContext()));
}
} | #vulnerable code
@Override
public void init(Map<String, String> initParams) {
String dataBaseType = null;
if(initParams.get("dataBaseType") != null) {
dataBaseType = initParams.get("dataBaseType");
}
if (!StringUtils.isEmpty(dataBaseType) && hasType(dataBaseType)) {
String path = "classpath:/database-" + dataBaseType + ".xml";
NulsContext.setApplicationContext(new ClassPathXmlApplicationContext(new String[]{path}, true, NulsContext.getApplicationContext()));
}
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void start() {
List<Node> nodeList = getNetworkStorage().getLocalNodeList(20);
nodeList.addAll(getSeedNodes());
for (Node node : nodeList) {
addNode(node);
}
running = true;
TaskManager.createAndRunThread(NetworkConstant.NETWORK_MODULE_ID, "NetworkNodeManager", this);
nodeDiscoverHandler.start();
} | #vulnerable code
public void start() {
getNetworkStorage().init();
List<Node> nodeList = getNetworkStorage().getLocalNodeList(20);
nodeList.addAll(getSeedNodes());
for (Node node : nodeList) {
addNode(node);
}
running = true;
TaskManager.createAndRunThread(NetworkConstant.NETWORK_MODULE_ID, "NetworkNodeManager", this);
nodeDiscoverHandler.start();
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean resetSystem(String reason) {
if ((TimeService.currentTimeMillis() - lastResetTime) <= INTERVAL_TIME) {
Log.info("system reset interrupt!");
return true;
}
Log.info("---------------reset start----------------");
Log.info("Received a reset system request, reason: 【" + reason + "】");
NetworkService networkService = NulsContext.getServiceBean(NetworkService.class);
networkService.reset();
DownloadService downloadService = NulsContext.getServiceBean(DownloadService.class);
downloadService.reset();
ConsensusManager.getInstance().clearCache();
Log.info("---------------reset end----------------");
this.lastResetTime = TimeService.currentTimeMillis();
return true;
} | #vulnerable code
@Override
public boolean resetSystem(String reason) {
if ((TimeService.currentTimeMillis() - lastResetTime) <= INTERVAL_TIME) {
Log.info("system reset interrupt!");
return true;
}
Log.info("---------------reset start----------------");
Log.info("Received a reset system request, reason: 【" + reason + "】");
NetworkService networkService = NulsContext.getServiceBean(NetworkService.class);
networkService.reset();
DownloadService downloadService = NulsContext.getServiceBean(DownloadService.class);
downloadService.reset();
NulsContext.getServiceBean(LedgerService.class).resetLedgerCache();
ConsensusMeetingRunner consensusMeetingRunner = ConsensusMeetingRunner.getInstance();
consensusMeetingRunner.resetConsensus();
Log.info("---------------reset end----------------");
this.lastResetTime = TimeService.currentTimeMillis();
return true;
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public HeaderDigest getLastHd() {
if (null == lastHd) {
List<HeaderDigest> list = new ArrayList<>(headerDigestList);
this.lastHd = list.get(list.size() - 1);
}
return lastHd;
} | #vulnerable code
public HeaderDigest getLastHd() {
if(null==lastHd){
List<HeaderDigest> list = new ArrayList<>(headerDigestList);
this.lastHd = list.get(list.size()-1);
}
return lastHd;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public NetworkEventResult process(BaseEvent event, Node node) {
GetNodeEvent getNodeEvent = (GetNodeEvent) event;
// String key = event.getHeader().getEventType() + "-" + node.getIp();
// if (cacheService.existEvent(key)) {
// getNetworkService().removeNode(node.getId());
// return null;
// }
// cacheService.putEvent(key, event, false);
List<Node> list = getAvailableNodes(getNodeEvent.getLength(), node.getId());
NodeEvent replyEvent = new NodeEvent(list);
return new NetworkEventResult(true, replyEvent);
} | #vulnerable code
@Override
public NetworkEventResult process(BaseEvent event, Node node) {
GetNodeEvent getNodeEvent = (GetNodeEvent) event;
String key = event.getHeader().getEventType() + "-" + node.getIp();
if (cacheService.existEvent(key)) {
getNetworkService().removeNode(node.getId());
return null;
}
cacheService.putEvent(key, event, false);
List<Node> list = getAvailableNodes(getNodeEvent.getLength(), node.getId());
NodeEvent replyEvent = new NodeEvent(list);
return new NetworkEventResult(true, replyEvent);
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public HeaderDigest getLastHd() {
List<HeaderDigest> list = new ArrayList<>(headerDigestList);
if (list.size() > 0) {
return list.get(list.size() - 1);
}
return null;
} | #vulnerable code
public HeaderDigest getLastHd() {
if (null == lastHd) {
List<HeaderDigest> list = new ArrayList<>(headerDigestList);
if(list.size() > 0) {
this.lastHd = list.get(list.size() - 1);
}
}
return lastHd;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean processing(long height) {
if (chainList.isEmpty()) {
return false;
}
this.checkIt();
if (null == approvingChain) {
return false;
}
Set<HeaderDigest> removeHashSet = new HashSet<>();
for (int i = chainList.size() - 1; i >= 0; i--) {
BlockHeaderChain chain = chainList.get(i);
if (chain.size() < (approvingChain.size() - 6)) {
removeHashSet.addAll(chain.getHeaderDigestList());
this.chainList.remove(chain);
}
}
for (HeaderDigest hd : removeHashSet) {
if (!approvingChain.contains(hd)) {
confirmingBlockCacheManager.removeBlock(hd.getHash());
}
}
if (approvingChain.getLastHd() != null && approvingChain.getLastHd().getHeight() >= (height + PocConsensusConstant.CONFIRM_BLOCK_COUNT)) {
return true;
}
return false;
} | #vulnerable code
public boolean processing(long height) {
if (chainList.isEmpty()) {
return false;
}
this.checkIt();
if (null == approvingChain) {
return false;
}
if (approvingChain.getLastHd() != null && approvingChain.getLastHd().getHeight() >= (height + PocConsensusConstant.CONFIRM_BLOCK_COUNT)) {
return true;
}
return false;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@PluginFactory
public static <S extends Serializable> SyslogAppender<S> createAppender(@PluginAttr("host") final String host,
@PluginAttr("port") final String portNum,
@PluginAttr("protocol") final String protocol,
@PluginAttr("reconnectionDelay") final String delay,
@PluginAttr("immediateFail") final String immediateFail,
@PluginAttr("name") final String name,
@PluginAttr("immediateFlush") final String immediateFlush,
@PluginAttr("suppressExceptions") final String suppress,
@PluginAttr("facility") final String facility,
@PluginAttr("id") final String id,
@PluginAttr("enterpriseNumber") final String ein,
@PluginAttr("includeMDC") final String includeMDC,
@PluginAttr("mdcId") final String mdcId,
@PluginAttr("mdcPrefix") final String mdcPrefix,
@PluginAttr("eventPrefix") final String eventPrefix,
@PluginAttr("newLine") final String includeNL,
@PluginAttr("newLineEscape") final String escapeNL,
@PluginAttr("appName") final String appName,
@PluginAttr("messageId") final String msgId,
@PluginAttr("mdcExcludes") final String excludes,
@PluginAttr("mdcIncludes") final String includes,
@PluginAttr("mdcRequired") final String required,
@PluginAttr("format") final String format,
@PluginElement("filters") final Filter filter,
@PluginConfiguration final Configuration config,
@PluginAttr("charset") final String charsetName,
@PluginAttr("exceptionPattern") final String exceptionPattern,
@PluginElement("LoggerFields") final LoggerFields loggerFields,
@PluginAttr("advertise") final String advertise) {
final boolean isFlush = immediateFlush == null ? true : Boolean.valueOf(immediateFlush);
final boolean handleExceptions = suppress == null ? true : Boolean.valueOf(suppress);
final int reconnectDelay = Integers.parseInt(delay);
final boolean fail = immediateFail == null ? true : Boolean.valueOf(immediateFail);
final int port = Integers.parseInt(portNum);
final boolean isAdvertise = advertise == null ? false : Boolean.valueOf(advertise);
@SuppressWarnings("unchecked")
final Layout<S> layout = (Layout<S>) (RFC5424.equalsIgnoreCase(format) ?
RFC5424Layout.createLayout(facility, id, ein, includeMDC, mdcId, mdcPrefix, eventPrefix, includeNL,
escapeNL, appName, msgId, excludes, includes, required, exceptionPattern, loggerFields, config) :
SyslogLayout.createLayout(facility, includeNL, escapeNL, charsetName));
if (name == null) {
LOGGER.error("No name provided for SyslogAppender");
return null;
}
final String prot = protocol != null ? protocol : Protocol.UDP.name();
final Protocol p = EnglishEnums.valueOf(Protocol.class, protocol);
final AbstractSocketManager manager = createSocketManager(p, host, port, reconnectDelay, fail, layout);
if (manager == null) {
return null;
}
return new SyslogAppender<S>(name, layout, filter, handleExceptions, isFlush, manager,
isAdvertise ? config.getAdvertiser() : null);
} | #vulnerable code
@PluginFactory
public static <S extends Serializable> SyslogAppender<S> createAppender(@PluginAttr("host") final String host,
@PluginAttr("port") final String portNum,
@PluginAttr("protocol") final String protocol,
@PluginAttr("reconnectionDelay") final String delay,
@PluginAttr("immediateFail") final String immediateFail,
@PluginAttr("name") final String name,
@PluginAttr("immediateFlush") final String immediateFlush,
@PluginAttr("suppressExceptions") final String suppress,
@PluginAttr("facility") final String facility,
@PluginAttr("id") final String id,
@PluginAttr("enterpriseNumber") final String ein,
@PluginAttr("includeMDC") final String includeMDC,
@PluginAttr("mdcId") final String mdcId,
@PluginAttr("mdcPrefix") final String mdcPrefix,
@PluginAttr("eventPrefix") final String eventPrefix,
@PluginAttr("newLine") final String includeNL,
@PluginAttr("newLineEscape") final String escapeNL,
@PluginAttr("appName") final String appName,
@PluginAttr("messageId") final String msgId,
@PluginAttr("mdcExcludes") final String excludes,
@PluginAttr("mdcIncludes") final String includes,
@PluginAttr("mdcRequired") final String required,
@PluginAttr("format") final String format,
@PluginElement("filters") final Filter filter,
@PluginConfiguration final Configuration config,
@PluginAttr("charset") final String charsetName,
@PluginAttr("exceptionPattern") final String exceptionPattern,
@PluginElement("LoggerFields") final LoggerFields loggerFields,
@PluginAttr("advertise") final String advertise) {
final boolean isFlush = immediateFlush == null ? true : Boolean.valueOf(immediateFlush);
final boolean handleExceptions = suppress == null ? true : Boolean.valueOf(suppress);
final int reconnectDelay = delay == null ? 0 : Integer.parseInt(delay);
final boolean fail = immediateFail == null ? true : Boolean.valueOf(immediateFail);
final int port = portNum == null ? 0 : Integer.parseInt(portNum);
final boolean isAdvertise = advertise == null ? false : Boolean.valueOf(advertise);
@SuppressWarnings("unchecked")
final Layout<S> layout = (Layout<S>) (RFC5424.equalsIgnoreCase(format) ?
RFC5424Layout.createLayout(facility, id, ein, includeMDC, mdcId, mdcPrefix, eventPrefix, includeNL,
escapeNL, appName, msgId, excludes, includes, required, exceptionPattern, loggerFields, config) :
SyslogLayout.createLayout(facility, includeNL, escapeNL, charsetName));
if (name == null) {
LOGGER.error("No name provided for SyslogAppender");
return null;
}
final String prot = protocol != null ? protocol : Protocol.UDP.name();
final Protocol p = EnglishEnums.valueOf(Protocol.class, protocol);
final AbstractSocketManager manager = createSocketManager(p, host, port, reconnectDelay, fail, layout);
if (manager == null) {
return null;
}
return new SyslogAppender<S>(name, layout, filter, handleExceptions, isFlush, manager,
isAdvertise ? config.getAdvertiser() : null);
}
#location 50
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static OutputStream getOutputStream(final boolean follow, final Target target) {
final PrintStream printStream = target == Target.SYSTEM_OUT ?
follow ? new PrintStream(new SystemOutStream()) : System.out :
follow ? new PrintStream(new SystemErrStream()) : System.err;
PropertiesUtil propsUtil = PropertiesUtil.getProperties();
if (!propsUtil.getStringProperty("os.name").startsWith("Windows") ||
propsUtil.getBooleanProperty("log4j.skipJansi")) {
return printStream;
} else {
try {
final ClassLoader loader = Loader.getClassLoader();
// We type the parameter as a wildcard to avoid a hard reference to Jansi.
final Class<?> clazz = loader.loadClass("org.fusesource.jansi.WindowsAnsiOutputStream");
final Constructor<?> constructor = clazz.getConstructor(OutputStream.class);
return (OutputStream) constructor.newInstance(printStream);
} catch (final ClassNotFoundException cnfe) {
LOGGER.debug("Jansi is not installed");
} catch (final NoSuchMethodException nsme) {
LOGGER.warn("WindowsAnsiOutputStream is missing the proper constructor");
} catch (final Exception ex) {
LOGGER.warn("Unable to instantiate WindowsAnsiOutputStream");
}
return printStream;
}
} | #vulnerable code
private static OutputStream getOutputStream(final boolean follow, final Target target) {
final PrintStream printStream = target == Target.SYSTEM_OUT ?
follow ? new PrintStream(new SystemOutStream()) : System.out :
follow ? new PrintStream(new SystemErrStream()) : System.err;
if (!System.getProperty("os.name").startsWith("Windows") || Boolean.getBoolean("log4j.skipJansi")) {
return printStream;
} else {
try {
final ClassLoader loader = Loader.getClassLoader();
// We type the parameter as a wildcard to avoid a hard reference to Jansi.
final Class<?> clazz = loader.loadClass("org.fusesource.jansi.WindowsAnsiOutputStream");
final Constructor<?> constructor = clazz.getConstructor(OutputStream.class);
return (OutputStream) constructor.newInstance(printStream);
} catch (final ClassNotFoundException cnfe) {
LOGGER.debug("Jansi is not installed");
} catch (final NoSuchMethodException nsme) {
LOGGER.warn("WindowsAnsiOutputStream is missing the proper constructor");
} catch (final Exception ex) {
LOGGER.warn("Unable to instantiate WindowsAnsiOutputStream");
}
return printStream;
}
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAppender() throws Exception {
for (int i = 0; i < 8; ++i) {
logger.debug("This is test message number " + i);
}
Thread.sleep(50);
final File dir = new File(DIR);
assertThat(dir, both(exists()).and(hasFiles()));
final File[] files = dir.listFiles();
assertNotNull(files);
for (final File file : files) {
assertHeader(file);
assertFooter(file);
}
final File logFile = new File(LOGFILE);
assertThat(logFile, exists());
assertHeader(logFile);
} | #vulnerable code
@Test
public void testAppender() throws Exception {
for (int i = 0; i < 8; ++i) {
logger.debug("This is test message number " + i);
}
Thread.sleep(50);
final File dir = new File(DIR);
assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0);
final File[] files = dir.listFiles();
assertTrue("No files created", files.length > 0);
for (final File file : files) {
assertHeader(file);
assertFooter(file);
}
final File logFile = new File(LOGFILE);
assertTrue("Expected logfile to exist: " + LOGFILE, logFile.exists());
assertHeader(logFile);
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected void write(final byte[] bytes, final int offset, final int length, final boolean immediateFlush) {
if (socket == null) {
if (reconnector != null && !immediateFail) {
reconnector.latch();
}
if (socket == null) {
final String msg = "Error writing to " + getName() + " socket not available";
throw new AppenderLoggingException(msg);
}
}
synchronized (this) {
try {
final OutputStream outputStream = getOutputStream();
outputStream.write(bytes, offset, length);
if (immediateFlush) {
outputStream.flush();
}
} catch (final IOException ex) {
if (retry && reconnector == null) {
reconnector = new Reconnector(this);
reconnector.setDaemon(true);
reconnector.setPriority(Thread.MIN_PRIORITY);
reconnector.start();
}
final String msg = "Error writing to " + getName();
throw new AppenderLoggingException(msg, ex);
}
}
} | #vulnerable code
@Override
protected void write(final byte[] bytes, final int offset, final int length, final boolean immediateFlush) {
if (socket == null) {
if (connector != null && !immediateFail) {
connector.latch();
}
if (socket == null) {
final String msg = "Error writing to " + getName() + " socket not available";
throw new AppenderLoggingException(msg);
}
}
synchronized (this) {
try {
final OutputStream outputStream = getOutputStream();
outputStream.write(bytes, offset, length);
if (immediateFlush) {
outputStream.flush();
}
} catch (final IOException ex) {
if (retry && connector == null) {
connector = new Reconnector(this);
connector.setDaemon(true);
connector.setPriority(Thread.MIN_PRIORITY);
connector.start();
}
final String msg = "Error writing to " + getName();
throw new AppenderLoggingException(msg, ex);
}
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFlush() throws IOException {
final OutputStream out = EasyMock.createMock(OutputStream.class);
out.flush(); // expect the flush to come through to the mocked OutputStream
out.close();
replay(out);
final LoggerFilterOutputStream los = new LoggerFilterOutputStream(out, getExtendedLogger(), LEVEL);
los.flush();
los.close();
verify(out);
} | #vulnerable code
@Test
public void testFlush() throws IOException {
final OutputStream out = EasyMock.createMock(OutputStream.class);
out.flush(); // expect the flush to come through to the mocked OutputStream
out.close();
replay(out);
final LoggerOutputStream los = new LoggerOutputStream(out, getExtendedLogger(), LEVEL);
los.flush();
los.close();
verify(out);
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static void copyFile(final File source, final File destination) throws IOException {
if (!destination.exists()) {
destination.createNewFile();
}
FileChannel srcChannel = null;
FileChannel destChannel = null;
FileInputStream srcStream = null;
FileOutputStream destStream = null;
try {
srcStream = new FileInputStream(source);
destStream = new FileOutputStream(destination);
srcChannel = srcStream.getChannel();
destChannel = destStream.getChannel();
destChannel.transferFrom(srcChannel, 0, srcChannel.size());
}
finally {
if(srcChannel != null) {
srcChannel.close();
}
if (srcStream != null) {
srcStream.close();
}
if (destChannel != null) {
destChannel.close();
}
if (destStream != null) {
destStream.close();
}
}
} | #vulnerable code
private static void copyFile(final File source, final File destination) throws IOException {
if (!destination.exists()) {
destination.createNewFile();
}
FileChannel srcChannel = null;
FileChannel destChannel = null;
try {
srcChannel = new FileInputStream(source).getChannel();
destChannel = new FileOutputStream(destination).getChannel();
destChannel.transferFrom(srcChannel, 0, srcChannel.size());
}
finally {
if(srcChannel != null) {
srcChannel.close();
}
if (destChannel != null) {
destChannel.close();
}
}
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void forcedLog(String fqcn, Priority level, Object message, Throwable t) {
org.apache.logging.log4j.Level lvl = org.apache.logging.log4j.Level.toLevel(level.toString());
Message msg = message instanceof Message ? (ObjectMessage) message : new ObjectMessage(message);
logger.log(null, fqcn, lvl, msg, t);
} | #vulnerable code
public void forcedLog(String fqcn, Priority level, Object message, Throwable t) {
org.apache.logging.log4j.Level lvl = org.apache.logging.log4j.Level.toLevel(level.toString());
logger.log(null, fqcn, lvl, new ObjectMessage(message), t);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void addScript(Script script) {
ScriptEngine engine = manager.getEngineByName(script.getLanguage());
if (engine == null) {
logger.error("No ScriptEngine found for language " + script.getLanguage() + ". Available languages are: " +
languages);
return;
}
if (engine.getFactory().getParameter("THREADING") == null) {
scripts.put(script.getName(), new ThreadLocalScriptRunner(script));
} else {
scripts.put(script.getName(), new MainScriptRunner(engine, script));
}
} | #vulnerable code
public void addScript(Script script) {
ScriptEngine engine = manager.getEngineByName(script.getLanguage());
if (engine == null) {
logger.error("No ScriptEngine found for language " + script.getLanguage());
}
if (engine.getFactory().getParameter("THREADING") == null) {
scripts.put(script.getName(), new ThreadLocalScriptRunner(script));
} else {
scripts.put(script.getName(), new MainScriptRunner(engine, script));
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws Exception {
System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getName());
Logger logger = LogManager.getLogger();
if (!(logger instanceof AsyncLogger)) {
throw new IllegalStateException();
}
// work around a bug in Log4j-2.5
workAroundLog4j2_5Bug();
logger.error("Starting...");
System.out.println("Starting...");
Thread.sleep(100);
final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
final long testStartNanos = System.nanoTime();
final long[] UPTIMES = new long[1024];
final long[] DURATIONS = new long[1024];
// warmup
long startMs = System.currentTimeMillis();
long end = startMs + TimeUnit.SECONDS.toMillis(10);
int warmupCount = 0;
do {
runTest(logger, runtimeMXBean, UPTIMES, DURATIONS, warmupCount);
warmupCount++;
// Thread.sleep(1000);// drain buffer
} while (System.currentTimeMillis() < end);
final int COUNT = 10;
for (int i = 0; i < COUNT; i++) {
int count = warmupCount + i;
runTest(logger, runtimeMXBean, UPTIMES, DURATIONS, count);
// Thread.sleep(1000);// drain buffer
}
double testDurationNanos = System.nanoTime() - testStartNanos;
System.out.println("Done. Calculating stats...");
printReport("Warmup", UPTIMES, DURATIONS, 0, warmupCount);
printReport("Test", UPTIMES, DURATIONS, warmupCount, COUNT);
StringBuilder sb = new StringBuilder(512);
sb.append("Test took: ").append(testDurationNanos/(1000.0*1000.0*1000.0)).append(" sec");
System.out.println(sb);
final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();
for (int i = 0; i < gcBeans.size(); i++) {
GarbageCollectorMXBean gcBean = gcBeans.get(i);
sb.setLength(0);
sb.append("GC[").append(gcBean.getName()).append("] ");
sb.append(gcBean.getCollectionCount()).append(" collections, collection time=");
sb.append(gcBean.getCollectionTime()).append(" millis.");
System.out.println(sb);
}
} | #vulnerable code
public static void main(String[] args) throws Exception {
System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getName());
Logger logger = LogManager.getLogger();
if (!(logger instanceof AsyncLogger)) {
throw new IllegalStateException();
}
logger.info("Starting...");
Thread.sleep(100);
final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
// warmup
final int ITERATIONS = 100000;
long startMs = System.currentTimeMillis();
long end = startMs + TimeUnit.SECONDS.toMillis(10);
long total = 0;
int count = 0;
StringBuilder sb = new StringBuilder(512);
do {
sb.setLength(0);
long startNanos = System.nanoTime();
long uptime = runtimeMXBean.getUptime();
loop(logger, ITERATIONS);
long endNanos = System.nanoTime();
long durationNanos = endNanos - startNanos;
final long opsPerSec = (1000L * 1000L * 1000L * ITERATIONS) / durationNanos;
sb.append(uptime).append(" Warmup: Throughput: ").append(opsPerSec).append(" ops/s");
System.out.println(sb);
total += opsPerSec;
count++;
// Thread.sleep(1000);// drain buffer
} while (System.currentTimeMillis() < end);
System.out.printf("Average warmup throughput: %,d ops/s%n", total/count);
final int COUNT = 10;
final long[] durationNanos = new long[10];
for (int i = 0; i < COUNT; i++) {
final long startNanos = System.nanoTime();
loop(logger, ITERATIONS);
long endNanos = System.nanoTime();
durationNanos[i] = endNanos - startNanos;
// Thread.sleep(1000);// drain buffer
}
total = 0;
for (int i = 0; i < COUNT; i++) {
final long opsPerSec = (1000L * 1000L * 1000L * ITERATIONS) / durationNanos[i];
System.out.printf("Throughput: %,d ops/s%n", opsPerSec);
total += opsPerSec;
}
System.out.printf("Average throughput: %,d ops/s%n", total/COUNT);
}
#location 34
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAppender() throws Exception {
final Logger logger = ctx.getLogger();
logger.debug("This is test message number 1");
Thread.sleep(1500);
// Trigger the rollover
for (int i = 0; i < 16; ++i) {
logger.debug("This is test message number " + i + 1);
}
final File dir = new File(DIR);
assertThat(dir, both(exists()).and(hasFiles()));
final int MAX_TRIES = 20;
final Matcher<File[]> hasGzippedFile = hasItemInArray(that(hasName(that(endsWith(".gz")))));
for (int i = 0; i < MAX_TRIES; i++) {
final File[] files = dir.listFiles();
if (hasGzippedFile.matches(files)) {
return; // test succeeded
}
logger.debug("Adding additional event " + i);
Thread.sleep(100); // Allow time for rollover to complete
}
fail("No compressed files found");
} | #vulnerable code
@Test
public void testAppender() throws Exception {
final Logger logger = ctx.getLogger();
logger.debug("This is test message number 1");
Thread.sleep(1500);
// Trigger the rollover
for (int i = 0; i < 16; ++i) {
logger.debug("This is test message number " + i + 1);
}
final File dir = new File(DIR);
assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0);
final int MAX_TRIES = 20;
for (int i = 0; i < MAX_TRIES; i++) {
final File[] files = dir.listFiles();
assertTrue("No files created", files.length > 0);
for (final File file : files) {
if (file.getName().endsWith(".gz")) {
return; // test succeeded
}
}
logger.debug("Adding additional event " + i);
Thread.sleep(100); // Allow time for rollover to complete
}
fail("No compressed files found");
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public String toSerializable(final LogEvent event) {
final Message message = event.getMessage();
final Object[] parameters = message.getParameters();
final StringBuilder buffer = getStringBuilder();
// Revisit when 1.3 is out so that we do not need to create a new
// printer for each event.
// No need to close the printer.
try (final CSVPrinter printer = new CSVPrinter(buffer, getFormat())) {
printer.printRecord(parameters);
return buffer.toString();
} catch (final IOException e) {
StatusLogger.getLogger().error(message, e);
return getFormat().getCommentMarker() + " " + e;
}
} | #vulnerable code
@Override
public String toSerializable(final LogEvent event) {
final Message message = event.getMessage();
final Object[] parameters = message.getParameters();
final StringBuilder buffer = prepareStringBuilder(strBuilder);
try {
// Revisit when 1.3 is out so that we do not need to create a new
// printer for each event.
// No need to close the printer.
final CSVPrinter printer = new CSVPrinter(buffer, getFormat());
printer.printRecord(parameters);
return buffer.toString();
} catch (final IOException e) {
StatusLogger.getLogger().error(message, e);
return getFormat().getCommentMarker() + " " + e;
}
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean hasFilters() {
return filters.hasFilters();
} | #vulnerable code
public boolean hasFilters() {
return hasFilters;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected void releaseSub() {
if (rpcClient != null) {
try {
synchronized(this) {
try {
if (batchSize > 1 && batchEvent.getEvents().size() > 0) {
send(batchEvent);
}
} catch (final Exception ex) {
LOGGER.error("Error sending final batch: {}", ex.getMessage());
}
}
rpcClient.close();
} catch (final Exception ex) {
LOGGER.error("Attempt to close RPC client failed", ex);
}
}
rpcClient = null;
} | #vulnerable code
@Override
protected void releaseSub() {
if (rpcClient != null) {
try {
rpcClient.close();
} catch (final Exception ex) {
LOGGER.error("Attempt to close RPC client failed", ex);
}
}
rpcClient = null;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public EventRoute getEventRoute(final Level logLevel) {
final int remainingCapacity = remainingDisruptorCapacity();
if (remainingCapacity < 0) {
return EventRoute.DISCARD;
}
return asyncQueueFullPolicy.getRoute(backgroundThreadId, logLevel);
} | #vulnerable code
@Override
public EventRoute getEventRoute(final Level logLevel) {
final int remainingCapacity = remainingDisruptorCapacity();
if (remainingCapacity < 0) {
return EventRoute.DISCARD;
}
return asyncEventRouter.getRoute(backgroundThreadId, logLevel);
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(final String[] args) throws Exception {
final JmsTopicReceiver receiver = new JmsTopicReceiver();
receiver.doMain(args);
} | #vulnerable code
public static void main(final String[] args) throws Exception {
if (args.length != 4) {
usage("Wrong number of arguments.");
}
final String tcfBindingName = args[0];
final String topicBindingName = args[1];
final String username = args[2];
final String password = args[3];
final JmsServer server = new JmsServer(tcfBindingName, topicBindingName, username, password);
server.start();
final Charset enc = Charset.defaultCharset();
final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in, enc));
// Loop until the word "exit" is typed
System.out.println("Type \"exit\" to quit JmsTopicReceiver.");
while (true) {
final String line = stdin.readLine();
if (line == null || line.equalsIgnoreCase("exit")) {
System.out.println("Exiting. Kill the application if it does not exit "
+ "due to daemon threads.");
server.stop();
return;
}
}
}
#location 19
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testConfig() {
final Configuration config = context.getConfiguration();
final Filter filter = config.getFilter();
assertNotNull("No StructuredDataFilter", filter);
assertTrue("Not a StructuredDataFilter", filter instanceof StructuredDataFilter);
final StructuredDataFilter sdFilter = (StructuredDataFilter) filter;
assertFalse("Should not be And filter", sdFilter.isAnd());
final Map<String, List<String>> map = sdFilter.getMap();
assertNotNull("No Map", map);
assertFalse("No elements in Map", map.isEmpty());
assertEquals("Incorrect number of elements in Map", 1, map.size());
assertTrue("Map does not contain key eventId", map.containsKey("eventId"));
assertEquals("List does not contain 2 elements", 2, map.get("eventId").size());
} | #vulnerable code
@Test
public void testConfig() {
final LoggerContext ctx = Configurator.initialize("Test1", "target/test-classes/log4j2-sdfilter.xml");
final Configuration config = ctx.getConfiguration();
final Filter filter = config.getFilter();
assertNotNull("No StructuredDataFilter", filter);
assertTrue("Not a StructuredDataFilter", filter instanceof StructuredDataFilter);
final StructuredDataFilter sdFilter = (StructuredDataFilter) filter;
assertFalse("Should not be And filter", sdFilter.isAnd());
final Map<String, List<String>> map = sdFilter.getMap();
assertNotNull("No Map", map);
assertFalse("No elements in Map", map.isEmpty());
assertEquals("Incorrect number of elements in Map", 1, map.size());
assertTrue("Map does not contain key eventId", map.containsKey("eventId"));
assertEquals("List does not contain 2 elements", 2, map.get("eventId").size());
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@BeforeClass
public static void setUpClass() throws Exception {
// TODO: refactor PluginManager.decode() into this module?
pluginCategories = new ConcurrentHashMap<String, ConcurrentMap<String, PluginEntry>>();
final Enumeration<URL> resources = PluginProcessor.class.getClassLoader().getResources(CACHE_FILE);
while (resources.hasMoreElements()) {
final URL url = resources.nextElement();
final DataInputStream in = new DataInputStream(new BufferedInputStream(url.openStream()));
try {
final int count = in.readInt();
for (int i = 0; i < count; i++) {
final String category = in.readUTF();
pluginCategories.putIfAbsent(category, new ConcurrentHashMap<String, PluginEntry>());
final ConcurrentMap<String, PluginEntry> m = pluginCategories.get(category);
final int entries = in.readInt();
for (int j = 0; j < entries; j++) {
final PluginEntry entry = new PluginEntry();
entry.setKey(in.readUTF());
entry.setClassName(in.readUTF());
entry.setName(in.readUTF());
entry.setPrintable(in.readBoolean());
entry.setDefer(in.readBoolean());
entry.setCategory(category);
m.putIfAbsent(entry.getKey(), entry);
}
pluginCategories.putIfAbsent(category, m);
}
} finally {
in.close();
}
}
} | #vulnerable code
@BeforeClass
public static void setUpClass() throws Exception {
// TODO: refactor PluginManager.decode() into this module?
pluginCategories = new ConcurrentHashMap<String, ConcurrentMap<String, PluginEntry>>();
final Enumeration<URL> resources = PluginProcessor.class.getClassLoader().getResources(CACHE_FILE);
while (resources.hasMoreElements()) {
final URL url = resources.nextElement();
final ObjectInput in = new ObjectInputStream(new BufferedInputStream(url.openStream()));
try {
final int count = in.readInt();
for (int i = 0; i < count; i++) {
final String category = in.readUTF();
pluginCategories.putIfAbsent(category, new ConcurrentHashMap<String, PluginEntry>());
final ConcurrentMap<String, PluginEntry> m = pluginCategories.get(category);
final int entries = in.readInt();
for (int j = 0; j < entries; j++) {
final PluginEntry entry = new PluginEntry();
entry.setKey(in.readUTF());
entry.setClassName(in.readUTF());
entry.setName(in.readUTF());
entry.setPrintable(in.readBoolean());
entry.setDefer(in.readBoolean());
entry.setCategory(category);
m.putIfAbsent(entry.getKey(), entry);
}
pluginCategories.putIfAbsent(category, m);
}
} finally {
in.close();
}
}
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws Exception {
System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getName());
Logger logger = LogManager.getLogger();
if (!(logger instanceof AsyncLogger)) {
throw new IllegalStateException();
}
// work around a bug in Log4j-2.5
workAroundLog4j2_5Bug();
logger.error("Starting...");
System.out.println("Starting...");
Thread.sleep(100);
final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
final long testStartNanos = System.nanoTime();
final long[] UPTIMES = new long[1024];
final long[] DURATIONS = new long[1024];
// warmup
long startMs = System.currentTimeMillis();
long end = startMs + TimeUnit.SECONDS.toMillis(10);
int warmupCount = 0;
do {
runTest(logger, runtimeMXBean, UPTIMES, DURATIONS, warmupCount);
warmupCount++;
// Thread.sleep(1000);// drain buffer
} while (System.currentTimeMillis() < end);
final int COUNT = 10;
for (int i = 0; i < COUNT; i++) {
int count = warmupCount + i;
runTest(logger, runtimeMXBean, UPTIMES, DURATIONS, count);
// Thread.sleep(1000);// drain buffer
}
double testDurationNanos = System.nanoTime() - testStartNanos;
System.out.println("Done. Calculating stats...");
printReport("Warmup", UPTIMES, DURATIONS, 0, warmupCount);
printReport("Test", UPTIMES, DURATIONS, warmupCount, COUNT);
StringBuilder sb = new StringBuilder(512);
sb.append("Test took: ").append(testDurationNanos/(1000.0*1000.0*1000.0)).append(" sec");
System.out.println(sb);
final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();
for (int i = 0; i < gcBeans.size(); i++) {
GarbageCollectorMXBean gcBean = gcBeans.get(i);
sb.setLength(0);
sb.append("GC[").append(gcBean.getName()).append("] ");
sb.append(gcBean.getCollectionCount()).append(" collections, collection time=");
sb.append(gcBean.getCollectionTime()).append(" millis.");
System.out.println(sb);
}
} | #vulnerable code
public static void main(String[] args) throws Exception {
System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getName());
Logger logger = LogManager.getLogger();
if (!(logger instanceof AsyncLogger)) {
throw new IllegalStateException();
}
logger.info("Starting...");
Thread.sleep(100);
final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
// warmup
final int ITERATIONS = 100000;
long startMs = System.currentTimeMillis();
long end = startMs + TimeUnit.SECONDS.toMillis(10);
long total = 0;
int count = 0;
StringBuilder sb = new StringBuilder(512);
do {
sb.setLength(0);
long startNanos = System.nanoTime();
long uptime = runtimeMXBean.getUptime();
loop(logger, ITERATIONS);
long endNanos = System.nanoTime();
long durationNanos = endNanos - startNanos;
final long opsPerSec = (1000L * 1000L * 1000L * ITERATIONS) / durationNanos;
sb.append(uptime).append(" Warmup: Throughput: ").append(opsPerSec).append(" ops/s");
System.out.println(sb);
total += opsPerSec;
count++;
// Thread.sleep(1000);// drain buffer
} while (System.currentTimeMillis() < end);
System.out.printf("Average warmup throughput: %,d ops/s%n", total/count);
final int COUNT = 10;
final long[] durationNanos = new long[10];
for (int i = 0; i < COUNT; i++) {
final long startNanos = System.nanoTime();
loop(logger, ITERATIONS);
long endNanos = System.nanoTime();
durationNanos[i] = endNanos - startNanos;
// Thread.sleep(1000);// drain buffer
}
total = 0;
for (int i = 0; i < COUNT; i++) {
final long opsPerSec = (1000L * 1000L * 1000L * ITERATIONS) / durationNanos[i];
System.out.printf("Throughput: %,d ops/s%n", opsPerSec);
total += opsPerSec;
}
System.out.printf("Average throughput: %,d ops/s%n", total/COUNT);
}
#location 51
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static boolean compare(final Class<?> testClass,
final String file1,
final String file2)
throws IOException {
try (final BufferedReader in1 = new BufferedReader(new FileReader(file1));
final BufferedReader in2 = new BufferedReader(new InputStreamReader(open(testClass, file2)))) {
return compare(testClass, file1, file2, in1, in2);
}
} | #vulnerable code
public static boolean compare(final Class<?> testClass,
final String file1,
final String file2)
throws IOException {
final BufferedReader in1 = new BufferedReader(new FileReader(file1));
final BufferedReader in2 = new BufferedReader(new InputStreamReader(
open(testClass, file2)));
try {
return compare(testClass, file1, file2, in1, in2);
} finally {
in1.close();
in2.close();
}
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMissingRootLogger() throws Exception {
final LoggerContext ctx = context.getContext();
final Logger logger = ctx.getLogger("sample.Logger1");
assertTrue("Logger should have the INFO level enabled", logger.isInfoEnabled());
assertFalse("Logger should have the DEBUG level disabled", logger.isDebugEnabled());
final Configuration config = ctx.getConfiguration();
assertNotNull("Config not null", config);
// final String MISSINGROOT = "MissingRootTest";
// assertTrue("Incorrect Configuration. Expected " + MISSINGROOT + " but found " + config.getName(),
// MISSINGROOT.equals(config.getName()));
final Map<String, Appender> map = config.getAppenders();
assertNotNull("Appenders not null", map);
assertEquals("There should only be two appenders", 2, map.size());
assertTrue("Contains List", map.containsKey("List"));
assertTrue("Contains Console", map.containsKey("Console"));
final Map<String, LoggerConfig> loggerMap = config.getLoggers();
assertNotNull("loggerMap not null", loggerMap);
assertEquals("There should only be one configured logger", 1, loggerMap.size());
// only the sample logger, no root logger in loggerMap!
assertTrue("contains key=sample", loggerMap.containsKey("sample"));
final LoggerConfig sample = loggerMap.get("sample");
final Map<String, Appender> sampleAppenders = sample.getAppenders();
assertEquals("The sample logger should only have one appender", 1, sampleAppenders.size());
// sample only has List appender, not Console!
assertTrue("The sample appender should be a ListAppender", sampleAppenders.containsKey("List"));
final AbstractConfiguration baseConfig = (AbstractConfiguration) config;
final LoggerConfig root = baseConfig.getRootLogger();
final Map<String, Appender> rootAppenders = root.getAppenders();
assertEquals("The root logger should only have one appender", 1, rootAppenders.size());
// root only has Console appender!
assertTrue("The root appender should be a ConsoleAppender", rootAppenders.containsKey("Console"));
assertEquals(Level.ERROR, root.getLevel());
} | #vulnerable code
@Test
public void testMissingRootLogger() throws Exception {
PluginManager.addPackage("org.apache.logging.log4j.test.appender");
final LoggerContext ctx = Configurator.initialize("Test1", "missingRootLogger.xml");
final Logger logger = LogManager.getLogger("sample.Logger1");
final Configuration config = ctx.getConfiguration();
assertNotNull("Config not null", config);
// final String MISSINGROOT = "MissingRootTest";
// assertTrue("Incorrect Configuration. Expected " + MISSINGROOT + " but found " + config.getName(),
// MISSINGROOT.equals(config.getName()));
final Map<String, Appender> map = config.getAppenders();
assertNotNull("Appenders not null", map);
assertEquals("Appenders Size", 2, map.size());
assertTrue("Contains List", map.containsKey("List"));
assertTrue("Contains Console", map.containsKey("Console"));
final Map<String, LoggerConfig> loggerMap = config.getLoggers();
assertNotNull("loggerMap not null", loggerMap);
assertEquals("loggerMap Size", 1, loggerMap.size());
// only the sample logger, no root logger in loggerMap!
assertTrue("contains key=sample", loggerMap.containsKey("sample"));
final LoggerConfig sample = loggerMap.get("sample");
final Map<String, Appender> sampleAppenders = sample.getAppenders();
assertEquals("sampleAppenders Size", 1, sampleAppenders.size());
// sample only has List appender, not Console!
assertTrue("sample has appender List", sampleAppenders.containsKey("List"));
final AbstractConfiguration baseConfig = (AbstractConfiguration) config;
final LoggerConfig root = baseConfig.getRootLogger();
final Map<String, Appender> rootAppenders = root.getAppenders();
assertEquals("rootAppenders Size", 1, rootAppenders.size());
// root only has Console appender!
assertTrue("root has appender Console", rootAppenders.containsKey("Console"));
assertEquals(Level.ERROR, root.getLevel());
logger.isDebugEnabled();
Configurator.shutdown(ctx);
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static boolean execute(final File source, final File destination, final boolean deleteSource, final int level)
throws IOException {
if (source.exists()) {
try (final FileInputStream fis = new FileInputStream(source);
final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destination))) {
zos.setLevel(level);
final ZipEntry zipEntry = new ZipEntry(source.getName());
zos.putNextEntry(zipEntry);
final byte[] inbuf = new byte[BUF_SIZE];
int n;
while ((n = fis.read(inbuf)) != -1) {
zos.write(inbuf, 0, n);
}
}
if (deleteSource && !source.delete()) {
LOGGER.warn("Unable to delete " + source.toString() + '.');
}
return true;
}
return false;
} | #vulnerable code
public static boolean execute(final File source, final File destination, final boolean deleteSource, final int level)
throws IOException {
if (source.exists()) {
final FileInputStream fis = new FileInputStream(source);
final FileOutputStream fos = new FileOutputStream(destination);
final ZipOutputStream zos = new ZipOutputStream(fos);
zos.setLevel(level);
final ZipEntry zipEntry = new ZipEntry(source.getName());
zos.putNextEntry(zipEntry);
final byte[] inbuf = new byte[BUF_SIZE];
int n;
while ((n = fis.read(inbuf)) != -1) {
zos.write(inbuf, 0, n);
}
zos.close();
fis.close();
if (deleteSource && !source.delete()) {
LOGGER.warn("Unable to delete " + source.toString() + '.');
}
return true;
}
return false;
}
#location 29
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFlush() throws IOException {
final OutputStream out = EasyMock.createMock("out", OutputStream.class);
out.flush(); // expect the flush to come through to the mocked OutputStream
out.close();
replay(out);
try (final OutputStream filteredOut =
IoBuilder.forLogger(getExtendedLogger())
.filter(out)
.setLevel(LEVEL)
.buildOutputStream()) {
filteredOut.flush();
}
verify(out);
} | #vulnerable code
@Test
public void testFlush() throws IOException {
final OutputStream out = EasyMock.createMock("out", OutputStream.class);
out.flush(); // expect the flush to come through to the mocked OutputStream
out.close();
replay(out);
final OutputStream filteredOut =
IoBuilder.forLogger(getExtendedLogger())
.filter(out)
.setLevel(LEVEL)
.buildOutputStream();
filteredOut.flush();
filteredOut.close();
verify(out);
}
#location 14
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testNoMsg() throws Exception {
final RegexFilter filter = RegexFilter.createFilter(".* test .*", null, false, null, null);
filter.start();
assertTrue(filter.isStarted());
assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (String) null, (Throwable) null));
assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Message) null, (Throwable) null));
assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, null, (Object[]) null));
} | #vulnerable code
@Test
public void testNoMsg() {
final RegexFilter filter = RegexFilter.createFilter(Pattern.compile(".* test .*"), false, null, null);
filter.start();
assertTrue(filter.isStarted());
assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (String) null, (Throwable) null));
assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, (Message) null, (Throwable) null));
assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, null, (Object[]) null));
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testThresholds() {
final ThresholdFilter filter = ThresholdFilter.createFilter(Level.ERROR, null, null);
filter.start();
assertTrue(filter.isStarted());
assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, null, (Throwable) null));
assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, null, (Throwable) null));
LogEvent event = new Log4jLogEvent(null, null, null, Level.DEBUG, new SimpleMessage("Test"), null);
assertSame(Filter.Result.DENY, filter.filter(event));
event = new Log4jLogEvent(null, null, null, Level.ERROR, new SimpleMessage("Test"), null);
assertSame(Filter.Result.NEUTRAL, filter.filter(event));
} | #vulnerable code
@Test
public void testThresholds() {
final ThresholdFilter filter = ThresholdFilter.createFilter("ERROR", null, null);
filter.start();
assertTrue(filter.isStarted());
assertSame(Filter.Result.DENY, filter.filter(null, Level.DEBUG, null, null, (Throwable) null));
assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.ERROR, null, null, (Throwable) null));
LogEvent event = new Log4jLogEvent(null, null, null, Level.DEBUG, new SimpleMessage("Test"), null);
assertSame(Filter.Result.DENY, filter.filter(event));
event = new Log4jLogEvent(null, null, null, Level.ERROR, new SimpleMessage("Test"), null);
assertSame(Filter.Result.NEUTRAL, filter.filter(event));
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMemMapLocation() throws Exception {
final File f = new File(LOGFILE);
if (f.exists()) {
assertTrue(f.delete());
}
assertTrue(!f.exists());
final int expectedFileLength = Integers.ceilingNextPowerOfTwo(32000);
assertEquals(32768, expectedFileLength);
final Logger log = LogManager.getLogger();
try {
log.warn("Test log1");
assertTrue(f.exists());
assertEquals("initial length", expectedFileLength, f.length());
log.warn("Test log2");
assertEquals("not grown", expectedFileLength, f.length());
} finally {
CoreLoggerContexts.stopLoggerContext(false);
}
final int LINESEP = System.lineSeparator().length();
assertEquals("Shrunk to actual used size", 474 + 2 * LINESEP, f.length());
String line1, line2, line3;
try (final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE))) {
line1 = reader.readLine();
line2 = reader.readLine();
line3 = reader.readLine();
}
assertNotNull(line1);
assertThat(line1, containsString("Test log1"));
final String location1 = "org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderLocationTest.testMemMapLocation(MemoryMappedFileAppenderLocationTest.java:65)";
assertThat(line1, containsString(location1));
assertNotNull(line2);
assertThat(line2, containsString("Test log2"));
final String location2 = "org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderLocationTest.testMemMapLocation(MemoryMappedFileAppenderLocationTest.java:69)";
assertThat(line2, containsString(location2));
assertNull("only two lines were logged", line3);
} | #vulnerable code
@Test
public void testMemMapLocation() throws Exception {
final File f = new File(LOGFILE);
if (f.exists()) {
assertTrue(f.delete());
}
assertTrue(!f.exists());
final int expectedFileLength = Integers.ceilingNextPowerOfTwo(32000);
assertEquals(32768, expectedFileLength);
final Logger log = LogManager.getLogger();
try {
log.warn("Test log1");
assertTrue(f.exists());
assertEquals("initial length", expectedFileLength, f.length());
log.warn("Test log2");
assertEquals("not grown", expectedFileLength, f.length());
} finally {
CoreLoggerContexts.stopLoggerContext(false);
}
final int LINESEP = System.getProperty("line.separator").length();
assertEquals("Shrunk to actual used size", 474 + 2 * LINESEP, f.length());
String line1, line2, line3;
try (final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE))) {
line1 = reader.readLine();
line2 = reader.readLine();
line3 = reader.readLine();
}
assertNotNull(line1);
assertThat(line1, containsString("Test log1"));
final String location1 = "org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderLocationTest.testMemMapLocation(MemoryMappedFileAppenderLocationTest.java:65)";
assertThat(line1, containsString(location1));
assertNotNull(line2);
assertThat(line2, containsString("Test log2"));
final String location2 = "org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderLocationTest.testMemMapLocation(MemoryMappedFileAppenderLocationTest.java:69)";
assertThat(line2, containsString(location2));
assertNull("only two lines were logged", line3);
}
#location 23
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAppender() throws Exception {
for (int i=0; i < 100; ++i) {
logger.debug("This is test message number " + i);
}
Thread.sleep(50);
final File dir = new File(DIR);
assertThat(dir, both(exists()).and(hasFiles()));
final File[] files = dir.listFiles();
assertNotNull(files);
assertThat(files, hasItemInArray(that(hasName(that(endsWith(".gz"))))));
} | #vulnerable code
@Test
public void testAppender() throws Exception {
for (int i=0; i < 100; ++i) {
logger.debug("This is test message number " + i);
}
Thread.sleep(50);
final File dir = new File(DIR);
assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0);
final File[] files = dir.listFiles();
assertTrue("No files created", files.length > 0);
boolean found = false;
for (final File file : files) {
if (file.getName().endsWith(".gz")) {
found = true;
break;
}
}
assertTrue("No compressed files found", found);
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testByName() throws Exception {
LoggerContext ctx = Configurator.intitalize("-config", null, null);
Logger logger = LogManager.getLogger("org.apache.test.TestConfigurator");
Configuration config = ctx.getConfiguration();
assertNotNull("No configuration", config);
assertTrue("Incorrect Configuration. Expected " + CONFIG_NAME + " but found " + config.getName(),
CONFIG_NAME.equals(config.getName()));
Map<String, Appender> map = config.getAppenders();
assertNotNull("No Appenders", map != null && map.size() > 0);
assertTrue("Wrong configuration", map.containsKey("List"));
Configurator.shutdown(ctx);
config = ctx.getConfiguration();
assertTrue("Incorrect Configuration. Expected " + DefaultConfiguration.DEFAULT_NAME + " but found " +
config.getName(), DefaultConfiguration.DEFAULT_NAME.equals(config.getName()));
} | #vulnerable code
@Test
public void testByName() throws Exception {
Configurator.intitalize("-config", null, null);
Logger logger = LogManager.getLogger("org.apache.test.TestConfigurator");
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
assertNotNull("No configuration", config);
assertTrue("Incorrect Configuration. Expected " + CONFIG_NAME + " but found " + config.getName(),
CONFIG_NAME.equals(config.getName()));
Map<String, Appender> map = config.getAppenders();
assertNotNull("No Appenders", map != null && map.size() > 0);
assertTrue("Wrong configuration", map.containsKey("List"));
Configurator.shutdown();
config = ctx.getConfiguration();
assertTrue("Incorrect Configuration. Expected " + DefaultConfiguration.DEFAULT_NAME + " but found " +
config.getName(), DefaultConfiguration.DEFAULT_NAME.equals(config.getName()));
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFlush() throws IOException {
final OutputStream out = EasyMock.createMock(OutputStream.class);
out.flush(); // expect the flush to come through to the mocked OutputStream
out.close();
replay(out);
final LoggerFilterOutputStream los = new LoggerFilterOutputStream(out, getExtendedLogger(), LEVEL);
los.flush();
los.close();
verify(out);
} | #vulnerable code
@Test
public void testFlush() throws IOException {
final OutputStream out = EasyMock.createMock(OutputStream.class);
out.flush(); // expect the flush to come through to the mocked OutputStream
out.close();
replay(out);
final LoggerOutputStream los = new LoggerOutputStream(out, getExtendedLogger(), LEVEL);
los.flush();
los.close();
verify(out);
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static boolean execute(final File source, final File destination, final boolean deleteSource, final int level)
throws IOException {
if (source.exists()) {
try (final FileInputStream fis = new FileInputStream(source);
final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destination))) {
zos.setLevel(level);
final ZipEntry zipEntry = new ZipEntry(source.getName());
zos.putNextEntry(zipEntry);
final byte[] inbuf = new byte[BUF_SIZE];
int n;
while ((n = fis.read(inbuf)) != -1) {
zos.write(inbuf, 0, n);
}
}
if (deleteSource && !source.delete()) {
LOGGER.warn("Unable to delete " + source.toString() + '.');
}
return true;
}
return false;
} | #vulnerable code
public static boolean execute(final File source, final File destination, final boolean deleteSource, final int level)
throws IOException {
if (source.exists()) {
final FileInputStream fis = new FileInputStream(source);
final FileOutputStream fos = new FileOutputStream(destination);
final ZipOutputStream zos = new ZipOutputStream(fos);
zos.setLevel(level);
final ZipEntry zipEntry = new ZipEntry(source.getName());
zos.putNextEntry(zipEntry);
final byte[] inbuf = new byte[BUF_SIZE];
int n;
while ((n = fis.read(inbuf)) != -1) {
zos.write(inbuf, 0, n);
}
zos.close();
fis.close();
if (deleteSource && !source.delete()) {
LOGGER.warn("Unable to delete " + source.toString() + '.');
}
return true;
}
return false;
}
#location 29
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void logToFile() throws Exception {
final FileOutputStream fos = new FileOutputStream(LOGFILE, false);
fos.flush();
fos.close();
final Logger logger = LogManager.getLogger("org.apache.logging.log4j.test2.Test");
logger.debug("This is a test");
final DataInputStream is = new DataInputStream(new BufferedInputStream(new FileInputStream(LOGFILE)));
try {
int count = 0;
String str = "";
while (is.available() != 0) {
str = is.readLine();
++count;
}
assertTrue("Incorrect count " + count, count == 1);
assertTrue("Bad data", str.endsWith("This is a test"));
} finally {
is.close();
}
} | #vulnerable code
@Test
public void logToFile() throws Exception {
final FileOutputStream fos = new FileOutputStream(LOGFILE, false);
fos.flush();
fos.close();
final Logger logger = LogManager.getLogger("org.apache.logging.log4j.test2.Test");
logger.debug("This is a test");
final DataInputStream is = new DataInputStream(new BufferedInputStream(new FileInputStream(LOGFILE)));
int count = 0;
String str = "";
while (is.available() != 0) {
str = is.readLine();
++count;
}
assertTrue("Incorrect count " + count, count == 1);
assertTrue("Bad data", str.endsWith("This is a test"));
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
AsyncLoggerDisruptor(String contextName) {
this.contextName = contextName;
} | #vulnerable code
EventRoute getEventRoute(final Level logLevel) {
final int remainingCapacity = remainingDisruptorCapacity();
if (remainingCapacity < 0) {
return EventRoute.DISCARD;
}
return asyncEventRouter.getRoute(backgroundThreadId, logLevel);
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
static void reportResult(final String file, final String name, final Histogram histogram)
throws IOException {
final String result = createSamplingReport(name, histogram);
println(result);
if (file != null) {
final FileWriter writer = new FileWriter(file, true);
try {
writer.write(result);
writer.write(System.getProperty("line.separator"));
} finally {
writer.close();
}
}
} | #vulnerable code
static void reportResult(final String file, final String name, final Histogram histogram)
throws IOException {
final String result = createSamplingReport(name, histogram);
println(result);
if (file != null) {
final FileWriter writer = new FileWriter(file, true);
writer.write(result);
writer.write(System.getProperty("line.separator"));
writer.close();
}
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static OutputStream getOutputStream(final boolean follow, final Target target) {
final PrintStream printStream = target == Target.SYSTEM_OUT ?
follow ? new PrintStream(new SystemOutStream()) : System.out :
follow ? new PrintStream(new SystemErrStream()) : System.err;
PropertiesUtil propsUtil = PropertiesUtil.getProperties();
if (!propsUtil.getStringProperty("os.name").startsWith("Windows") ||
propsUtil.getBooleanProperty("log4j.skipJansi")) {
return printStream;
} else {
try {
final ClassLoader loader = Loader.getClassLoader();
// We type the parameter as a wildcard to avoid a hard reference to Jansi.
final Class<?> clazz = loader.loadClass("org.fusesource.jansi.WindowsAnsiOutputStream");
final Constructor<?> constructor = clazz.getConstructor(OutputStream.class);
return (OutputStream) constructor.newInstance(printStream);
} catch (final ClassNotFoundException cnfe) {
LOGGER.debug("Jansi is not installed");
} catch (final NoSuchMethodException nsme) {
LOGGER.warn("WindowsAnsiOutputStream is missing the proper constructor");
} catch (final Exception ex) {
LOGGER.warn("Unable to instantiate WindowsAnsiOutputStream");
}
return printStream;
}
} | #vulnerable code
private static OutputStream getOutputStream(final boolean follow, final Target target) {
final PrintStream printStream = target == Target.SYSTEM_OUT ?
follow ? new PrintStream(new SystemOutStream()) : System.out :
follow ? new PrintStream(new SystemErrStream()) : System.err;
if (!System.getProperty("os.name").startsWith("Windows") || Boolean.getBoolean("log4j.skipJansi")) {
return printStream;
} else {
try {
final ClassLoader loader = Loader.getClassLoader();
// We type the parameter as a wildcard to avoid a hard reference to Jansi.
final Class<?> clazz = loader.loadClass("org.fusesource.jansi.WindowsAnsiOutputStream");
final Constructor<?> constructor = clazz.getConstructor(OutputStream.class);
return (OutputStream) constructor.newInstance(printStream);
} catch (final ClassNotFoundException cnfe) {
LOGGER.debug("Jansi is not installed");
} catch (final NoSuchMethodException nsme) {
LOGGER.warn("WindowsAnsiOutputStream is missing the proper constructor");
} catch (final Exception ex) {
LOGGER.warn("Unable to instantiate WindowsAnsiOutputStream");
}
return printStream;
}
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.