nus-yam/ex-repair huggingface dataset:
Program: 85896
Project: 85896
Buggy source:
private void processHeaders(HeadersMessage m) throws IOException, ProtocolException {
  Preconditions.checkState(!downloadBlockBodies,toString());
  try {
    for (int i=0; i < m.getBlockHeaders().size(); i++) {
      Block header=m.getBlockHeaders().get(i);
      if (header.getTimeSeconds() < fastCatchupTimeSecs) {
        if (blockChain.add(header)) {
          invokeOnBlocksDownloaded(header);
        }
 else {
          throw new ProtocolException("String_Node_Str" + header.getHashAsString());
        }
      }
 else {
        log.info("String_Node_Str",m.getBlockHeaders().size() - i);
        downloadBlockBodies=true;
        lastGetBlocksBegin=Sha256Hash.ZERO_HASH;
        blockChainDownload(Sha256Hash.ZERO_HASH);
        return;
      }
    }
    if (m.getBlockHeaders().size() >= HeadersMessage.MAX_HEADERS)     blockChainDownload(Sha256Hash.ZERO_HASH);
  }
 catch (  VerificationException e) {
    log.warn("String_Node_Str",e);
  }
catch (  PrunedException e) {
    throw new RuntimeException(e);
  }
}

Fixed version (ground truth):
private synchronized void processHeaders(HeadersMessage m) throws IOException, ProtocolException {
  Preconditions.checkState(!downloadBlockBodies,toString());
  try {
    for (int i=0; i < m.getBlockHeaders().size(); i++) {
      Block header=m.getBlockHeaders().get(i);
      if (header.getTimeSeconds() < fastCatchupTimeSecs) {
        if (blockChain.add(header)) {
          invokeOnBlocksDownloaded(header);
        }
 else {
          throw new ProtocolException("String_Node_Str" + header.getHashAsString());
        }
      }
 else {
        log.info("String_Node_Str",m.getBlockHeaders().size() - i);
        downloadBlockBodies=true;
        lastGetBlocksBegin=Sha256Hash.ZERO_HASH;
        blockChainDownload(Sha256Hash.ZERO_HASH);
        return;
      }
    }
    if (m.getBlockHeaders().size() >= HeadersMessage.MAX_HEADERS)     blockChainDownload(Sha256Hash.ZERO_HASH);
  }
 catch (  VerificationException e) {
    log.warn("String_Node_Str",e);
  }
catch (  PrunedException e) {
    throw new RuntimeException(e);
  }
}
Program: 85897
Project: 85897
Buggy source:
/** 
 * Sends the peer a ping message and returns a future that will be invoked when the pong is received back. The future provides a number which is the number of milliseconds elapsed between the ping and the pong. Once the pong is received the value returned by   {@link com.google.bitcoin.core.Peer#getLastPingTime()} isupdated.
 * @throws ProtocolException if the peer version is too low to support measurable pings.
 */
public ListenableFuture<Long> ping() throws IOException, ProtocolException {
  int peerVersion=getPeerVersionMessage().clientVersion;
  if (peerVersion < Pong.MIN_PROTOCOL_VERSION)   throw new ProtocolException("String_Node_Str" + peerVersion);
  PendingPing pendingPing=new PendingPing();
  pendingPings.add(pendingPing);
  sendMessage(new Ping(pendingPing.nonce));
  return pendingPing.future;
}

Fixed version (ground truth):
/** 
 * Sends the peer a ping message and returns a future that will be invoked when the pong is received back. The future provides a number which is the number of milliseconds elapsed between the ping and the pong. Once the pong is received the value returned by   {@link com.google.bitcoin.core.Peer#getLastPingTime()} isupdated.
 * @throws ProtocolException if the peer version is too low to support measurable pings.
 */
public synchronized ListenableFuture<Long> ping() throws IOException, ProtocolException {
  int peerVersion=getPeerVersionMessage().clientVersion;
  if (peerVersion < Pong.MIN_PROTOCOL_VERSION)   throw new ProtocolException("String_Node_Str" + peerVersion);
  PendingPing pendingPing=new PendingPing();
  pendingPings.add(pendingPing);
  sendMessage(new Ping(pendingPing.nonce));
  return pendingPing.future;
}
Program: 85898
Project: 85898
Buggy source:
/** 
 * Returns true if this peer will try and download things it is sent in "inv" messages. Normally you only need one peer to be downloading data. Defaults to true.
 */
public boolean getDownloadData(){
  return downloadData;
}

Fixed version (ground truth):
/** 
 * Returns true if this peer will try and download things it is sent in "inv" messages. Normally you only need one peer to be downloading data. Defaults to true.
 */
public synchronized boolean getDownloadData(){
  return downloadData;
}
Program: 85899
Project: 85899
Buggy source:
/** 
 * @return the height of the best chain as claimed by peer: sum of its ver announcement and blocks announced since.
 */
public long getBestHeight(){
  return peerVersionMessage.bestHeight + blocksAnnounced;
}

Fixed version (ground truth):
/** 
 * @return the height of the best chain as claimed by peer: sum of its ver announcement and blocks announced since.
 */
public synchronized long getBestHeight(){
  return peerVersionMessage.bestHeight + blocksAnnounced;
}
Program: 85900
Project: 85900
Buggy source:
/** 
 * @return the IP address and port of peer.
 */
public PeerAddress getAddress(){
  return address;
}

Fixed version (ground truth):
/** 
 * @return the IP address and port of peer.
 */
public synchronized PeerAddress getAddress(){
  return address;
}
Program: 85901
Project: 85901
Buggy source:
@Override public void connectRequested(ChannelHandlerContext ctx,ChannelStateEvent e) throws Exception {
  address=new PeerAddress((InetSocketAddress)e.getValue());
  channel=e.getChannel();
  super.connectRequested(ctx,e);
}

Fixed version (ground truth):
@Override public void connectRequested(ChannelHandlerContext ctx,ChannelStateEvent e) throws Exception {
synchronized (Peer.this) {
    address=new PeerAddress((InetSocketAddress)e.getValue());
  }
  channel=e.getChannel();
  super.connectRequested(ctx,e);
}
Program: 85902
Project: 85902
Buggy source:
private void processBlock(Block m) throws IOException {
  log.debug("String_Node_Str",address,m.getHashAsString());
  try {
synchronized (pendingGetBlockFutures) {
      for (int i=0; i < pendingGetBlockFutures.size(); i++) {
        GetDataFuture<Block> f=pendingGetBlockFutures.get(i);
        if (f.getItem().hash.equals(m.getHash())) {
          f.setResult(m);
          pendingGetBlockFutures.remove(i);
          return;
        }
      }
    }
    if (!downloadData) {
      log.warn("String_Node_Str",m.getHashAsString());
      return;
    }
    pendingBlockDownloads.remove(m.getHash());
    if (blockChain.add(m)) {
      invokeOnBlocksDownloaded(m);
    }
 else {
      blockChainDownload(blockChain.getOrphanRoot(m.getHash()).getHash());
    }
  }
 catch (  VerificationException e) {
    log.warn("String_Node_Str",e);
  }
catch (  PrunedException e) {
    throw new RuntimeException(e);
  }
}

Fixed version (ground truth):
private synchronized void processBlock(Block m) throws IOException {
  log.debug("String_Node_Str",address,m.getHashAsString());
  try {
synchronized (pendingGetBlockFutures) {
      for (int i=0; i < pendingGetBlockFutures.size(); i++) {
        GetDataFuture<Block> f=pendingGetBlockFutures.get(i);
        if (f.getItem().hash.equals(m.getHash())) {
          f.setResult(m);
          pendingGetBlockFutures.remove(i);
          return;
        }
      }
    }
    if (!downloadData) {
      log.warn("String_Node_Str",m.getHashAsString());
      return;
    }
    pendingBlockDownloads.remove(m.getHash());
    if (blockChain.add(m)) {
      invokeOnBlocksDownloaded(m);
    }
 else {
      blockChainDownload(blockChain.getOrphanRoot(m.getHash()).getHash());
    }
  }
 catch (  VerificationException e) {
    log.warn("String_Node_Str",e);
  }
catch (  PrunedException e) {
    throw new RuntimeException(e);
  }
}
Program: 85903
Project: 85903
Buggy source:
@Override public String toString(){
  if (address == null) {
    return "String_Node_Str";
  }
 else {
    return "String_Node_Str" + address.getAddr() + "String_Node_Str"+ address.getPort()+ "String_Node_Str";
  }
}

Fixed version (ground truth):
@Override public synchronized String toString(){
  if (address == null) {
    return "String_Node_Str";
  }
 else {
    return "String_Node_Str" + address.getAddr() + "String_Node_Str"+ address.getPort()+ "String_Node_Str";
  }
}
Program: 85905
Project: 85905
Buggy source:
protected void discoverPeers() throws PeerDiscoveryException {
  long start=System.currentTimeMillis();
  for (  PeerDiscovery peerDiscovery : peerDiscoverers) {
    InetSocketAddress[] addresses;
    addresses=peerDiscovery.getPeers(10,TimeUnit.SECONDS);
synchronized (inactives) {
      for (int i=0; i < addresses.length; i++) {
        inactives.add(new PeerAddress(addresses[i]));
      }
      if (inactives.size() > 0)       break;
    }
  }
  log.info("String_Node_Str",System.currentTimeMillis() - start);
}

Fixed version (ground truth):
protected void discoverPeers() throws PeerDiscoveryException {
  long start=System.currentTimeMillis();
  Set<PeerAddress> addressSet=Sets.newHashSet();
  for (  PeerDiscovery peerDiscovery : peerDiscoverers) {
    InetSocketAddress[] addresses;
    addresses=peerDiscovery.getPeers(10,TimeUnit.SECONDS);
    for (int i=0; i < addresses.length; i++)     addressSet.add(new PeerAddress(addresses[i]));
    if (addressSet.size() > 0)     break;
  }
synchronized (inactives) {
    inactives.addAll(addressSet);
  }
  log.info("String_Node_Str",System.currentTimeMillis() - start);
}
Program: 85906
Project: 85906
Buggy source:
private void processInv(InventoryMessage inv) throws IOException {
  List<InventoryItem> items=inv.getItems();
  List<InventoryItem> transactions=new LinkedList<InventoryItem>();
  List<InventoryItem> blocks=new LinkedList<InventoryItem>();
  for (  InventoryItem item : items) {
switch (item.type) {
case Transaction:
      transactions.add(item);
    break;
case Block:
  blocks.add(item);
break;
default :
throw new IllegalStateException("String_Node_Str" + item.type);
}
}
GetDataMessage getdata=new GetDataMessage(params);
Iterator<InventoryItem> it=transactions.iterator();
while (it.hasNext()) {
InventoryItem item=it.next();
if (memoryPool == null) {
if (downloadData) {
getdata.addItem(item);
}
}
 else {
if (memoryPool.maybeWasSeen(item.hash)) {
it.remove();
}
 else {
log.debug("String_Node_Str",address,item.hash);
getdata.addItem(item);
}
memoryPool.seen(item.hash,this.getAddress());
}
}
if (blocks.size() > 0 && downloadData && blockChain != null) {
for (InventoryItem item : blocks) {
if (blockChain.isOrphan(item.hash)) {
blockChainDownload(blockChain.getOrphanRoot(item.hash).getHash());
}
 else {
if (!pendingBlockDownloads.contains(item.hash)) {
getdata.addItem(item);
pendingBlockDownloads.add(item.hash);
}
}
}
}
if (!getdata.getItems().isEmpty()) {
sendMessage(getdata);
}
}

Fixed version (ground truth):
private void processInv(InventoryMessage inv) throws IOException {
  List<InventoryItem> items=inv.getItems();
  List<InventoryItem> transactions=new LinkedList<InventoryItem>();
  List<InventoryItem> blocks=new LinkedList<InventoryItem>();
  for (  InventoryItem item : items) {
switch (item.type) {
case Transaction:
      transactions.add(item);
    break;
case Block:
  blocks.add(item);
break;
default :
throw new IllegalStateException("String_Node_Str" + item.type);
}
}
if (transactions.size() == 0 && blocks.size() == 1) {
if (downloadData) {
if (!blockChain.isOrphan(blocks.get(0).hash)) {
blocksAnnounced++;
}
}
 else {
blocksAnnounced++;
}
}
GetDataMessage getdata=new GetDataMessage(params);
Iterator<InventoryItem> it=transactions.iterator();
while (it.hasNext()) {
InventoryItem item=it.next();
if (memoryPool == null) {
if (downloadData) {
getdata.addItem(item);
}
}
 else {
if (memoryPool.maybeWasSeen(item.hash)) {
it.remove();
}
 else {
log.debug("String_Node_Str",address,item.hash);
getdata.addItem(item);
}
memoryPool.seen(item.hash,this.getAddress());
}
}
if (blocks.size() > 0 && downloadData && blockChain != null) {
for (InventoryItem item : blocks) {
if (blockChain.isOrphan(item.hash)) {
blockChainDownload(blockChain.getOrphanRoot(item.hash).getHash());
}
 else {
if (!pendingBlockDownloads.contains(item.hash)) {
getdata.addItem(item);
pendingBlockDownloads.add(item.hash);
}
}
}
}
if (!getdata.getItems().isEmpty()) {
sendMessage(getdata);
}
}
Program: 85907
Project: 85907
Buggy source:
/** 
 * Returns the difference between our best chain height and the peers, which can either be positive if we are behind the peer, or negative if the peer is ahead of us.
 */
public int getPeerBlockHeightDifference(){
  int chainHeight=(int)peerVersionMessage.bestHeight;
  Preconditions.checkState(params.allowEmptyPeerChains || chainHeight > 0,"String_Node_Str",chainHeight);
  return chainHeight - blockChain.getChainHead().getHeight();
}

Fixed version (ground truth):
/** 
 * Returns the difference between our best chain height and the peers, which can either be positive if we are behind the peer, or negative if the peer is ahead of us.
 */
public int getPeerBlockHeightDifference(){
  int chainHeight=(int)getBestHeight();
  Preconditions.checkState(params.allowEmptyPeerChains || chainHeight > 0,"String_Node_Str",chainHeight);
  return chainHeight - blockChain.getChainHead().getHeight();
}
Program: 85908
Project: 85908
Buggy source:
/** 
 * @return the height of the best chain as claimed by peer.
 */
public long getBestHeight(){
  return peerVersionMessage.bestHeight;
}

Fixed version (ground truth):
/** 
 * @return the height of the best chain as claimed by peer: sum of its ver announcement and blocks announced since.
 */
public long getBestHeight(){
  return peerVersionMessage.bestHeight + blocksAnnounced;
}
Program: 85909
Project: 85909
Buggy source:
private synchronized void setDownloadPeer(Peer peer){
  if (downloadPeer != null) {
    log.info("String_Node_Str",downloadPeer);
    downloadPeer.setDownloadData(false);
  }
  downloadPeer=peer;
  if (downloadPeer != null) {
    log.info("String_Node_Str",downloadPeer);
    downloadPeer.setDownloadData(true);
    if (chain != null)     downloadPeer.setFastCatchupTime(fastCatchupTimeSecs);
  }
}

Fixed version (ground truth):
private synchronized void setDownloadPeer(Peer peer){
  if (chain == null)   return;
  if (downloadPeer != null) {
    log.info("String_Node_Str",downloadPeer);
    downloadPeer.setDownloadData(false);
  }
  downloadPeer=peer;
  if (downloadPeer != null) {
    log.info("String_Node_Str",downloadPeer);
    downloadPeer.setDownloadData(true);
    if (chain != null)     downloadPeer.setFastCatchupTime(fastCatchupTimeSecs);
  }
}
Program: 85910
Project: 85910
Buggy source:
/** 
 * Helper method that just sets up a normal Netty ClientBootstrap using the default options, except for a custom thread factory that gives worker threads useful names and lowers their priority (to avoid competing with UI threads). You don't normally need to call this - if you aren't sure what it does, just use the regular constructors for   {@link PeerGroup} that don't take a ClientBootstrap object.
 */
public static ClientBootstrap createClientBootstrap(){
  ExecutorService bossExecutor=Executors.newCachedThreadPool(new PeerGroupThreadFactory());
  ExecutorService workerExecutor=Executors.newCachedThreadPool(new PeerGroupThreadFactory());
  NioClientSocketChannelFactory channelFactory=new NioClientSocketChannelFactory(bossExecutor,workerExecutor);
  ClientBootstrap bs=new ClientBootstrap(channelFactory);
  return bs;
}

Fixed version (ground truth):
/** 
 * Helper method that just sets up a normal Netty ClientBootstrap using the default options, except for a custom thread factory that gives worker threads useful names and lowers their priority (to avoid competing with UI threads). You don't normally need to call this - if you aren't sure what it does, just use the regular constructors for   {@link PeerGroup} that don't take a ClientBootstrap object.
 */
public static ClientBootstrap createClientBootstrap(){
  ExecutorService bossExecutor=Executors.newCachedThreadPool(new PeerGroupThreadFactory());
  ExecutorService workerExecutor=Executors.newCachedThreadPool(new PeerGroupThreadFactory());
  NioClientSocketChannelFactory channelFactory=new NioClientSocketChannelFactory(bossExecutor,workerExecutor);
  ClientBootstrap bs=new ClientBootstrap(channelFactory);
  bs.setOption("String_Node_Str",2000);
  return bs;
}
Program: 85911
Project: 85911
Buggy source:
@Test public void newBlock() throws Exception {
  PeerEventListener listener=control.createMock(PeerEventListener.class);
  Block b1=createFakeBlock(unitTestParams,blockStore).block;
  blockChain.add(b1);
  Block b2=makeSolvedTestBlock(unitTestParams,b1);
  InventoryMessage inv=new InventoryMessage(unitTestParams);
  InventoryItem item=new InventoryItem(InventoryItem.Type.Block,b2.getHash());
  inv.addItem(item);
  expect(listener.onPreMessageReceived(eq(peer),eq(inv))).andReturn(inv);
  expect(listener.onPreMessageReceived(eq(peer),eq(b2))).andReturn(b2);
  listener.onBlocksDownloaded(eq(peer),anyObject(Block.class),eq(108));
  expectLastCall();
  control.replay();
  connect();
  peer.addEventListener(listener);
  inbound(peer,inv);
  inbound(peer,b2);
  control.verify();
  GetDataMessage getdata=(GetDataMessage)event.getValue().getMessage();
  List<InventoryItem> items=getdata.getItems();
  assertEquals(1,items.size());
  assertEquals(b2.getHash(),items.get(0).hash);
  assertEquals(InventoryItem.Type.Block,items.get(0).type);
}

Fixed version (ground truth):
@Test public void newBlock() throws Exception {
  PeerEventListener listener=control.createMock(PeerEventListener.class);
  Block b1=createFakeBlock(unitTestParams,blockStore).block;
  blockChain.add(b1);
  Block b2=makeSolvedTestBlock(unitTestParams,b1);
  InventoryMessage inv=new InventoryMessage(unitTestParams);
  InventoryItem item=new InventoryItem(InventoryItem.Type.Block,b2.getHash());
  inv.addItem(item);
  expect(listener.onPreMessageReceived(eq(peer),eq(inv))).andReturn(inv);
  expect(listener.onPreMessageReceived(eq(peer),eq(b2))).andReturn(b2);
  listener.onBlocksDownloaded(eq(peer),anyObject(Block.class),eq(OTHER_PEER_CHAIN_HEIGHT + 1 - 2));
  expectLastCall();
  control.replay();
  connect();
  peer.addEventListener(listener);
  long height=peer.getBestHeight();
  inbound(peer,inv);
  assertEquals(height + 1,peer.getBestHeight());
  inbound(peer,b2);
  control.verify();
  GetDataMessage getdata=(GetDataMessage)event.getValue().getMessage();
  List<InventoryItem> items=getdata.getItems();
  assertEquals(1,items.size());
  assertEquals(b2.getHash(),items.get(0).hash);
  assertEquals(InventoryItem.Type.Block,items.get(0).type);
}
Program: 85912
Project: 85912
Buggy source:
private void connect(PeerHandler handler,Channel channel,ChannelHandlerContext ctx) throws Exception {
  handler.connectRequested(ctx,new UpstreamChannelStateEvent(channel,ChannelState.CONNECTED,socketAddress));
  VersionMessage peerVersion=new VersionMessage(unitTestParams,110);
  DownstreamMessageEvent versionEvent=new DownstreamMessageEvent(channel,Channels.future(channel),peerVersion,null);
  handler.messageReceived(ctx,versionEvent);
}

Fixed version (ground truth):
private void connect(PeerHandler handler,Channel channel,ChannelHandlerContext ctx) throws Exception {
  handler.connectRequested(ctx,new UpstreamChannelStateEvent(channel,ChannelState.CONNECTED,socketAddress));
  VersionMessage peerVersion=new VersionMessage(unitTestParams,OTHER_PEER_CHAIN_HEIGHT);
  DownstreamMessageEvent versionEvent=new DownstreamMessageEvent(channel,Channels.future(channel),peerVersion,null);
  handler.messageReceived(ctx,versionEvent);
}
Program: 85913
Project: 85913
Buggy source:
@Test public void pingPong() throws Exception {
  control.replay();
  connect();
  Utils.rollMockClock(0);
  assertEquals(Long.MAX_VALUE,peer.getLastPingTime());
  assertEquals(Long.MAX_VALUE,peer.getPingTime());
  ListenableFuture<Long> future=peer.ping();
  Ping pingMsg=(Ping)outbound();
  assertEquals(Long.MAX_VALUE,peer.getLastPingTime());
  assertEquals(Long.MAX_VALUE,peer.getPingTime());
  assertFalse(future.isDone());
  Utils.rollMockClock(5);
  inbound(peer,new Pong(pingMsg.getNonce()));
  assertTrue(future.isDone());
  long elapsed=future.get();
  assertTrue("String_Node_Str" + elapsed,elapsed > 1000);
  assertEquals(elapsed,peer.getLastPingTime());
  assertEquals(elapsed,peer.getPingTime());
  future=peer.ping();
  outbound();
  Utils.rollMockClock(50);
  inbound(peer,new Pong(pingMsg.getNonce()));
  elapsed=future.get();
  assertEquals(elapsed,peer.getLastPingTime());
  assertEquals(14000,peer.getPingTime());
}

Fixed version (ground truth):
@Test public void pingPong() throws Exception {
  control.replay();
  connect();
  Utils.rollMockClock(0);
  assertEquals(Long.MAX_VALUE,peer.getLastPingTime());
  assertEquals(Long.MAX_VALUE,peer.getPingTime());
  ListenableFuture<Long> future=peer.ping();
  Ping pingMsg=(Ping)outbound();
  assertEquals(Long.MAX_VALUE,peer.getLastPingTime());
  assertEquals(Long.MAX_VALUE,peer.getPingTime());
  assertFalse(future.isDone());
  Utils.rollMockClock(5);
  inbound(peer,new Pong(pingMsg.getNonce()));
  assertTrue(future.isDone());
  long elapsed=future.get();
  assertTrue("String_Node_Str" + elapsed,elapsed > 1000);
  assertEquals(elapsed,peer.getLastPingTime());
  assertEquals(elapsed,peer.getPingTime());
  future=peer.ping();
  outbound();
  Utils.rollMockClock(50);
  inbound(peer,new Pong(pingMsg.getNonce()));
  elapsed=future.get();
  assertEquals(elapsed,peer.getLastPingTime());
  assertEquals(7250,peer.getPingTime());
}
Program: 85914
Project: 85914
Buggy source:
/** 
 * Adds a transaction to this block. The nonce and merkle root are invalid after this. 
 */
public void addTransaction(Transaction t){
  unCacheTransactions();
  if (transactions == null) {
    transactions=new ArrayList<Transaction>();
  }
  t.setParent(this);
  if (transactions.size() == 0 && !t.isCoinBase())   throw new RuntimeException("String_Node_Str" + t);
 else   if (transactions.size() > 0 && t.isCoinBase())   throw new RuntimeException("String_Node_Str" + t);
  transactions.add(t);
  adjustLength(t.length);
  merkleRoot=null;
  hash=null;
}

Fixed version (ground truth):
/** 
 * Adds a transaction to this block. The nonce and merkle root are invalid after this. 
 */
public void addTransaction(Transaction t){
  unCacheTransactions();
  if (transactions == null) {
    transactions=new ArrayList<Transaction>();
  }
  t.setParent(this);
  if (transactions.size() == 0 && !t.isCoinBase())   throw new RuntimeException("String_Node_Str" + t);
 else   if (transactions.size() > 0 && t.isCoinBase())   throw new RuntimeException("String_Node_Str" + t);
  transactions.add(t);
  adjustLength(transactions.size(),t.length);
  merkleRoot=null;
  hash=null;
}
Program: 85915
Project: 85915
Buggy source:
/** 
 * Adds a coinbase transaction to the block. This exists for unit tests. 
 */
void addCoinbaseTransaction(byte[] pubKeyTo){
  unCacheTransactions();
  transactions=new ArrayList<Transaction>();
  Transaction coinbase=new Transaction(params);
  coinbase.addInput(new TransactionInput(params,coinbase,new byte[]{(byte)txCounter++}));
  coinbase.addOutput(new TransactionOutput(params,coinbase,Script.createOutputScript(pubKeyTo)));
  transactions.add(coinbase);
}

Fixed version (ground truth):
/** 
 * Adds a coinbase transaction to the block. This exists for unit tests. 
 */
void addCoinbaseTransaction(byte[] pubKeyTo){
  unCacheTransactions();
  transactions=new ArrayList<Transaction>();
  Transaction coinbase=new Transaction(params);
  coinbase.addInput(new TransactionInput(params,coinbase,new byte[]{(byte)txCounter++}));
  coinbase.addOutput(new TransactionOutput(params,coinbase,Script.createOutputScript(pubKeyTo)));
  transactions.add(coinbase);
  coinbase.setParent(this);
  coinbase.length=coinbase.bitcoinSerialize().length;
  adjustLength(transactions.size(),coinbase.length);
}
Program: 85916
Project: 85916
Buggy source:
protected void adjustLength(int adjustment){
  if (length != UNKNOWN_LENGTH)   length+=adjustment;
  if (parent != null)   parent.adjustLength(adjustment);
}

Fixed version (ground truth):
protected void adjustLength(int newArraySize,int adjustment){
  super.adjustLength(newArraySize,adjustment);
  if (parent != null)   parent.adjustLength(newArraySize,adjustment);
}
Program: 85917
Project: 85917
Buggy source:
protected void adjustLength(int adjustment){
  if (length != UNKNOWN_LENGTH)   length=adjustment == UNKNOWN_LENGTH ? UNKNOWN_LENGTH : length + adjustment;
}

Fixed version (ground truth):
protected void adjustLength(int newArraySize,int adjustment){
  if (length == UNKNOWN_LENGTH)   return;
  if (adjustment == UNKNOWN_LENGTH) {
    length=UNKNOWN_LENGTH;
    return;
  }
  length+=adjustment;
  if (newArraySize == 1)   length++;
 else   if (newArraySize != 0)   length+=VarInt.sizeOf(newArraySize) - VarInt.sizeOf(newArraySize - 1);
}
Program: 85918
Project: 85918
Buggy source:
/** 
 * Adds an input directly, with no checking that it's valid.
 */
public void addInput(TransactionInput input){
  unCache();
  input.setParent(this);
  inputs.add(input);
  adjustLength(input.length);
}

Fixed version (ground truth):
/** 
 * Adds an input directly, with no checking that it's valid.
 */
public void addInput(TransactionInput input){
  unCache();
  input.setParent(this);
  inputs.add(input);
  adjustLength(inputs.size(),input.length);
}
Program: 85920
Project: 85920
Buggy source:
private void processHeaders(HeadersMessage m) throws IOException, ProtocolException {
  Preconditions.checkState(!downloadBlockBodies,toString());
  try {
    for (int i=0; i < m.getBlockHeaders().size(); i++) {
      Block header=m.getBlockHeaders().get(i);
      if (header.getTimeSeconds() < fastCatchupTimeSecs) {
        if (blockChain.add(header)) {
          invokeOnBlocksDownloaded(header);
        }
 else {
          throw new ProtocolException("String_Node_Str" + header.getHashAsString());
        }
      }
 else {
        log.info("String_Node_Str",m.getBlockHeaders().size() - i);
        downloadBlockBodies=true;
        blockChainDownload(header.getHash());
        return;
      }
    }
    if (m.getBlockHeaders().size() >= HeadersMessage.MAX_HEADERS)     blockChainDownload(Sha256Hash.ZERO_HASH);
  }
 catch (  VerificationException e) {
    log.warn("String_Node_Str",e);
  }
catch (  ScriptException e) {
    throw new RuntimeException(e);
  }
}

Fixed version (ground truth):
private void processHeaders(HeadersMessage m) throws IOException, ProtocolException {
  Preconditions.checkState(!downloadBlockBodies,toString());
  try {
    for (int i=0; i < m.getBlockHeaders().size(); i++) {
      Block header=m.getBlockHeaders().get(i);
      if (header.getTimeSeconds() < fastCatchupTimeSecs) {
        if (blockChain.add(header)) {
          invokeOnBlocksDownloaded(header);
        }
 else {
          throw new ProtocolException("String_Node_Str" + header.getHashAsString());
        }
      }
 else {
        log.info("String_Node_Str",m.getBlockHeaders().size() - i);
        downloadBlockBodies=true;
        lastGetBlocksBegin=Sha256Hash.ZERO_HASH;
        blockChainDownload(Sha256Hash.ZERO_HASH);
        return;
      }
    }
    if (m.getBlockHeaders().size() >= HeadersMessage.MAX_HEADERS)     blockChainDownload(Sha256Hash.ZERO_HASH);
  }
 catch (  VerificationException e) {
    log.warn("String_Node_Str",e);
  }
catch (  ScriptException e) {
    throw new RuntimeException(e);
  }
}
Program: 85923
Project: 85923
Buggy source:
public void run(){
  log.info("String_Node_Str");
  while (true) {
    try {
      WalletSaveRequest req=walletRefs.poll(5,TimeUnit.SECONDS);
      if (req == null && walletRefs.size() == 0) {
        break;
      }
synchronized (req.wallet) {
        if (req.wallet.dirty) {
          if (req.wallet.autoSave()) {
            break;
          }
        }
      }
    }
 catch (    InterruptedException e) {
      break;
    }
  }
  log.info("String_Node_Str");
synchronized (AutosaveThread.class) {
    Preconditions.checkState(globalThread == this);
    globalThread=null;
  }
}

Fixed version (ground truth):
public void run(){
  log.info("String_Node_Str");
  while (true) {
    try {
      WalletSaveRequest req=walletRefs.poll(5,TimeUnit.SECONDS);
      if (req == null) {
        if (walletRefs.size() == 0) {
          break;
        }
 else {
          continue;
        }
      }
synchronized (req.wallet) {
        if (req.wallet.dirty) {
          if (req.wallet.autoSave()) {
            break;
          }
        }
      }
    }
 catch (    InterruptedException e) {
      log.error("String_Node_Str",e);
      break;
    }
  }
  log.info("String_Node_Str");
synchronized (AutosaveThread.class) {
    Preconditions.checkState(globalThread == this);
    globalThread=null;
  }
  maybeStart();
}
Program: 85924
Project: 85924
Buggy source:
/** 
 * Called by a wallet when it's become dirty (changed). Will start the background thread if needed. 
 */
public static void registerForSave(Wallet wallet,long delayMsec){
  AutosaveThread ats=get();
  ats.walletRefs.put(new WalletSaveRequest(wallet,delayMsec));
}

Fixed version (ground truth):
/** 
 * Called by a wallet when it's become dirty (changed). Will start the background thread if needed. 
 */
public static void registerForSave(Wallet wallet,long delayMsec){
  walletRefs.add(new WalletSaveRequest(wallet,delayMsec));
  maybeStart();
}
Program: 85926
Project: 85926
Buggy source:
private AutosaveThread(){
  this.walletRefs=new DelayQueue<WalletSaveRequest>();
  setDaemon(true);
  setName("String_Node_Str");
  setPriority(Thread.MIN_PRIORITY);
}

Fixed version (ground truth):
private AutosaveThread(){
  setDaemon(true);
  setName("String_Node_Str");
  setPriority(Thread.MIN_PRIORITY);
}
Program: 85928
Project: 85928
Buggy source:
private static void shutdown(){
  try {
    if (peers == null)     return;
    peers.stop();
    saveWallet(walletFile);
    store.close();
  }
 catch (  BlockStoreException e) {
    throw new RuntimeException(e);
  }
}

Fixed version (ground truth):
private static void shutdown(){
  try {
    if (peers == null)     return;
    peers.stop();
    saveWallet(walletFile);
    store.close();
    wallet=null;
  }
 catch (  BlockStoreException e) {
    throw new RuntimeException(e);
  }
}
Program: 85932
Project: 85932
Buggy source:
public void run(){
  log.info("String_Node_Str");
  while (true) {
    try {
      Thread.sleep(delayMs);
    }
 catch (    InterruptedException e) {
    }
    Wallet wallet=walletRef.get();
    if (wallet == null)     break;
synchronized (wallet) {
      if (wallet.dirty) {
        if (wallet.autoSave())         break;
      }
    }
  }
}

Fixed version (ground truth):
public void run(){
  log.info("String_Node_Str");
  while (true) {
    try {
      WalletSaveRequest req=walletRefs.poll(5,TimeUnit.SECONDS);
      if (req == null && walletRefs.size() == 0) {
        break;
      }
synchronized (req.wallet) {
        if (req.wallet.dirty) {
          if (req.wallet.autoSave()) {
            break;
          }
        }
      }
    }
 catch (    InterruptedException e) {
      break;
    }
  }
  log.info("String_Node_Str");
synchronized (AutosaveThread.class) {
    Preconditions.checkState(globalThread == this);
    globalThread=null;
  }
}
Program: 85933
Project: 85933
Buggy source:
private synchronized void queueAutoSave(){
  if (this.autosaveToFile == null)   return;
  if (autosaveThread == null) {
    try {
      saveToFile(autosaveToFile);
    }
 catch (    IOException e) {
      throw new RuntimeException(e);
    }
  }
 else {
    dirty=true;
  }
}

Fixed version (ground truth):
private synchronized void queueAutoSave(){
  if (this.autosaveToFile == null)   return;
  if (autosaveDelayMs == 0) {
    try {
      saveToFile(autosaveToFile);
    }
 catch (    IOException e) {
      throw new RuntimeException(e);
    }
  }
 else {
    if (!dirty) {
      dirty=true;
      AutosaveThread.registerForSave(this,autosaveDelayMs);
    }
  }
}
Program: 85935
Project: 85935
Buggy source:
public AutosaveThread(Wallet wallet,long delayMs){
  this.walletRef=new WeakReference<Wallet>(wallet);
  this.delayMs=delayMs;
  setDaemon(true);
  start();
}

Fixed version (ground truth):
private AutosaveThread(){
  this.walletRefs=new DelayQueue<WalletSaveRequest>();
  setDaemon(true);
  setName("String_Node_Str");
  setPriority(Thread.MIN_PRIORITY);
}
Program: 85936
Project: 85936
Buggy source:
/** 
 * To run a script, first we parse it which breaks it up into chunks representing pushes of data or logical opcodes. Then we can run the parsed chunks. <p/> The reason for this split, instead of just interpreting directly, is to make it easier to reach into a programs structure and pull out bits of data without having to run it. This is necessary to render the to/from addresses of transactions in a user interface. The official client does something similar.
 */
private void parse(byte[] programBytes,int offset,int length) throws ScriptException {
  program=new byte[length];
  System.arraycopy(programBytes,offset,program,0,length);
  offset=0;
  chunks=new ArrayList<ScriptChunk>(10);
  cursor=offset;
  while (cursor < offset + length) {
    int opcode=readByte();
    if (opcode > 0 && opcode < OP_PUSHDATA1) {
      chunks.add(new ScriptChunk(false,getData(opcode)));
    }
 else     if (opcode == OP_PUSHDATA1) {
      int len=readByte();
      chunks.add(new ScriptChunk(false,getData(len)));
    }
 else     if (opcode == OP_PUSHDATA2) {
      int len=readByte() | (readByte() << 8);
      chunks.add(new ScriptChunk(false,getData(len)));
    }
 else     if (opcode == OP_PUSHDATA4) {
      log.error("String_Node_Str");
    }
 else {
      chunks.add(new ScriptChunk(true,new byte[]{(byte)opcode}));
    }
  }
}

Fixed version (ground truth):
/** 
 * To run a script, first we parse it which breaks it up into chunks representing pushes of data or logical opcodes. Then we can run the parsed chunks. <p/> The reason for this split, instead of just interpreting directly, is to make it easier to reach into a programs structure and pull out bits of data without having to run it. This is necessary to render the to/from addresses of transactions in a user interface. The official client does something similar.
 */
private void parse(byte[] programBytes,int offset,int length) throws ScriptException {
  program=new byte[length];
  System.arraycopy(programBytes,offset,program,0,length);
  offset=0;
  chunks=new ArrayList<ScriptChunk>(10);
  cursor=offset;
  while (cursor < offset + length) {
    int opcode=readByte();
    if (opcode >= 0 && opcode < OP_PUSHDATA1) {
      chunks.add(new ScriptChunk(false,getData(opcode)));
    }
 else     if (opcode == OP_PUSHDATA1) {
      int len=readByte();
      chunks.add(new ScriptChunk(false,getData(len)));
    }
 else     if (opcode == OP_PUSHDATA2) {
      int len=readByte() | (readByte() << 8);
      chunks.add(new ScriptChunk(false,getData(len)));
    }
 else     if (opcode == OP_PUSHDATA4) {
      log.error("String_Node_Str");
    }
 else {
      chunks.add(new ScriptChunk(true,new byte[]{(byte)opcode}));
    }
  }
}
Program: 85937
Project: 85937
Buggy source:
public static <E>void invoke(List<E> listeners,EventListenerInvoker<E> invoker){
  if (listeners == null)   return;
synchronized (listeners) {
    for (int i=0; i < listeners.size(); i++) {
      E l=listeners.get(i);
synchronized (l) {
        invoker.invoke(l);
      }
      if (listeners.get(i) != l) {
        i--;
      }
    }
  }
}

Fixed version (ground truth):
public static <E>void invoke(List<E> listeners,EventListenerInvoker<E> invoker){
  if (listeners == null)   return;
synchronized (listeners) {
    for (int i=0; i < listeners.size(); i++) {
      E l=listeners.get(i);
synchronized (l) {
        invoker.invoke(l);
      }
      if (i == listeners.size()) {
        break;
      }
 else       if (listeners.get(i) != l) {
        i--;
      }
    }
  }
}
Program: 85938
Project: 85938
Buggy source:
/** 
 * Uses protobuf serialization to save the wallet to the given file. To learn more about this file format, see  {@link WalletProtobufSerializer}. Writes out first to a temporary file in the same directory and then renames once written.
 */
public synchronized void saveToFile(File f) throws IOException {
  FileOutputStream stream=null;
  File temp;
  try {
    File directory=f.getAbsoluteFile().getParentFile();
    temp=File.createTempFile("String_Node_Str",null,directory);
    stream=new FileOutputStream(temp);
    saveToFileStream(stream);
    stream.flush();
    stream.getFD().sync();
    if (!temp.renameTo(f)) {
      if (System.getProperty("String_Node_Str").toLowerCase().indexOf("String_Node_Str") >= 0) {
        if (f.delete() && temp.renameTo(f))         return;
      }
      throw new IOException("String_Node_Str" + temp + "String_Node_Str"+ f);
    }
  }
  finally {
    if (stream != null) {
      stream.close();
    }
  }
}

Fixed version (ground truth):
/** 
 * Uses protobuf serialization to save the wallet to the given file. To learn more about this file format, see  {@link WalletProtobufSerializer}. Writes out first to a temporary file in the same directory and then renames once written.
 */
public synchronized void saveToFile(File f) throws IOException {
  FileOutputStream stream=null;
  File temp;
  try {
    File directory=f.getAbsoluteFile().getParentFile();
    temp=File.createTempFile("String_Node_Str",null,directory);
    stream=new FileOutputStream(temp);
    saveToFileStream(stream);
    stream.flush();
    stream.getFD().sync();
    stream.close();
    stream=null;
    if (!temp.renameTo(f)) {
      if (System.getProperty("String_Node_Str").toLowerCase().indexOf("String_Node_Str") >= 0) {
        if (f.delete() && temp.renameTo(f))         return;
      }
      throw new IOException("String_Node_Str" + temp + "String_Node_Str"+ f);
    }
  }
  finally {
    if (stream != null) {
      stream.close();
    }
  }
}
Program: 85939
Project: 85939
Buggy source:
/** 
 * Adds a transaction to this block. 
 */
void addTransaction(Transaction t){
  unCacheTransactions();
  if (transactions == null) {
    transactions=new ArrayList<Transaction>();
  }
  t.setParent(this);
  transactions.add(t);
  adjustLength(t.length);
  merkleRoot=null;
  hash=null;
}

Fixed version (ground truth):
/** 
 * Adds a transaction to this block. The nonce and merkle root are invalid after this. 
 */
public void addTransaction(Transaction t){
  unCacheTransactions();
  if (transactions == null) {
    transactions=new ArrayList<Transaction>();
  }
  t.setParent(this);
  if (transactions.size() == 0 && !t.isCoinBase())   throw new RuntimeException("String_Node_Str" + t);
 else   if (transactions.size() > 0 && t.isCoinBase())   throw new RuntimeException("String_Node_Str" + t);
  transactions.add(t);
  adjustLength(t.length);
  merkleRoot=null;
  hash=null;
}
Program: 85941
Project: 85941
Buggy source:
@Test public void isConsistent_duplicates() throws Exception {
  Transaction tx=createFakeTx(params,Utils.toNanoCoins(1,0),myAddress);
  Address someOtherGuy=new ECKey().toAddress(params);
  TransactionOutput output=new TransactionOutput(params,tx,Utils.toNanoCoins(0,5),someOtherGuy);
  tx.addOutput(output);
  wallet.receiveFromBlock(tx,null,BlockChain.NewBlockType.BEST_CHAIN);
  assertTrue(wallet.isConsistent());
  Transaction txClone=new Transaction(params,tx.bitcoinSerialize());
  try {
    wallet.receiveFromBlock(txClone,null,BlockChain.NewBlockType.SIDE_CHAIN);
    fail();
  }
 catch (  IllegalStateException ex) {
  }
}

Fixed version (ground truth):
@Test public void isConsistent_duplicates() throws Exception {
  Transaction tx=createFakeTx(params,Utils.toNanoCoins(1,0),myAddress);
  Address someOtherGuy=new ECKey().toAddress(params);
  TransactionOutput output=new TransactionOutput(params,tx,Utils.toNanoCoins(0,5),someOtherGuy);
  tx.addOutput(output);
  wallet.receiveFromBlock(tx,null,BlockChain.NewBlockType.BEST_CHAIN);
  assertTrue(wallet.isConsistent());
  Transaction txClone=new Transaction(params,tx.bitcoinSerialize());
  try {
    wallet.receiveFromBlock(txClone,null,BlockChain.NewBlockType.BEST_CHAIN);
    fail();
  }
 catch (  IllegalStateException ex) {
  }
}
Program: 85942
Project: 85942
Buggy source:
/** 
 * Connect to a peer by creating a Netty channel to the destination address.
 * @param address destination IP and port
 * @return a ChannelFuture that can be used to wait for the socket to connect.  A socketconnection does not mean that protocol handshake has occured.
 */
public ChannelFuture connectTo(SocketAddress address){
  ChannelFuture future=bootstrap.connect(address);
  TCPNetworkConnection connection=(TCPNetworkConnection)future.getChannel().getPipeline().get("String_Node_Str");
  if (connection != null)   connection.setRemoteAddress(address);
  Peer peer=peerFromChannelFuture(future);
  channelFutures.put(peer,future);
  return future;
}

Fixed version (ground truth):
/** 
 * Connect to a peer by creating a Netty channel to the destination address.
 * @param address destination IP and port
 * @return a ChannelFuture that can be used to wait for the socket to connect.  A socketconnection does not mean that protocol handshake has occured.
 */
public ChannelFuture connectTo(SocketAddress address){
  ChannelFuture future=bootstrap.connect(address);
  TCPNetworkConnection.NetworkHandler networkHandler=(TCPNetworkConnection.NetworkHandler)future.getChannel().getPipeline().get("String_Node_Str");
  if (networkHandler != null) {
    networkHandler.getOwnerObject().setRemoteAddress(address);
  }
  Peer peer=peerFromChannelFuture(future);
  channelFutures.put(peer,future);
  return future;
}
Program: 85943
Project: 85943
Buggy source:
/** 
 * If the transactions outputs are all marked as spent, and it's in the unspent map, move it.
 */
private void maybeMoveTxToSpent(Transaction tx,String context){
  if (tx.isEveryOwnedOutputSpent(this)) {
    if (unspent.remove(tx.getHash()) != null) {
      if (log.isInfoEnabled()) {
        log.info("String_Node_Str" + context + "String_Node_Str");
        log.info("String_Node_Str" + context + "String_Node_Str");
      }
      spent.put(tx.getHash(),tx);
    }
  }
}

Fixed version (ground truth):
/** 
 * If the transactions outputs are all marked as spent, and it's in the unspent map, move it.
 */
private void maybeMoveTxToSpent(Transaction tx,String context){
  if (tx.isEveryOwnedOutputSpent(this)) {
    if (unspent.remove(tx.getHash()) != null) {
      if (log.isInfoEnabled()) {
        log.info("String_Node_Str",tx.getHashAsString(),context);
        log.info("String_Node_Str",tx.getHashAsString(),context);
      }
      spent.put(tx.getHash(),tx);
    }
  }
}
Program: 85945
Project: 85945
Buggy source:
/** 
 * Returns the   {@link StoredBlock} that represents the top of the chain of greatest total work.
 */
StoredBlock getChainHead() throws BlockStoreException ;

Fixed version (ground truth):
/** 
 * Returns the   {@link StoredBlock} that represents the top of the chain of greatest total work. Note that thiscan be arbitrarily expensive, you probably should use  {@link com.google.bitcoin.core.BlockChain#getChainHead()}or perhaps   {@link com.google.bitcoin.core.BlockChain#getBestChainHeight()} which will run in constant time andnot take any heavyweight locks.
 */
StoredBlock getChainHead() throws BlockStoreException ;
Program: 85946
Project: 85946
Buggy source:
private synchronized boolean add(Block block,boolean tryConnecting) throws BlockStoreException, VerificationException, ScriptException {
  if (System.currentTimeMillis() - statsLastTime > 1000) {
    if (statsBlocksAdded > 1)     log.info("String_Node_Str",statsBlocksAdded);
    statsLastTime=System.currentTimeMillis();
    statsBlocksAdded=0;
  }
  if (block.equals(getChainHead().getHeader())) {
    log.debug("String_Node_Str",block.getHash());
    return true;
  }
  boolean contentsImportant=false;
  if (block.transactions != null) {
    contentsImportant=containsRelevantTransactions(block);
  }
  try {
    block.verifyHeader();
    if (contentsImportant)     block.verifyTransactions();
  }
 catch (  VerificationException e) {
    log.error("String_Node_Str",e);
    log.error(block.getHashAsString());
    throw e;
  }
  StoredBlock storedPrev=blockStore.get(block.getPrevBlockHash());
  if (storedPrev == null) {
    checkState(tryConnecting,"String_Node_Str");
    log.warn("String_Node_Str",block.getHashAsString());
    unconnectedBlocks.add(block);
    return false;
  }
 else {
    StoredBlock newStoredBlock=storedPrev.build(block);
    if (params.checkBlockDifficulty)     checkDifficultyTransitions(storedPrev,newStoredBlock);
    blockStore.put(newStoredBlock);
    connectBlock(newStoredBlock,storedPrev,block.transactions);
  }
  if (tryConnecting)   tryConnectingUnconnected();
  statsBlocksAdded++;
  return true;
}

Fixed version (ground truth):
private synchronized boolean add(Block block,boolean tryConnecting) throws BlockStoreException, VerificationException, ScriptException {
  if (System.currentTimeMillis() - statsLastTime > 1000) {
    if (statsBlocksAdded > 1)     log.info("String_Node_Str",statsBlocksAdded);
    statsLastTime=System.currentTimeMillis();
    statsBlocksAdded=0;
  }
  if (block.equals(getChainHead().getHeader())) {
    log.debug("String_Node_Str",block.getHash());
    return true;
  }
  boolean contentsImportant=false;
  if (block.transactions != null) {
    contentsImportant=containsRelevantTransactions(block);
  }
  try {
    block.verifyHeader();
    if (contentsImportant)     block.verifyTransactions();
  }
 catch (  VerificationException e) {
    log.error("String_Node_Str",e);
    log.error(block.getHashAsString());
    throw e;
  }
  StoredBlock storedPrev=blockStore.get(block.getPrevBlockHash());
  if (storedPrev == null) {
    checkState(tryConnecting,"String_Node_Str");
    log.warn("String_Node_Str",block.getHashAsString(),block.getPrevBlockHash());
    unconnectedBlocks.add(block);
    return false;
  }
 else {
    StoredBlock newStoredBlock=storedPrev.build(block);
    checkDifficultyTransitions(storedPrev,newStoredBlock);
    blockStore.put(newStoredBlock);
    connectBlock(newStoredBlock,storedPrev,block.transactions);
  }
  if (tryConnecting)   tryConnectingUnconnected();
  statsBlocksAdded++;
  return true;
}
Program: 85948
Project: 85948
Buggy source:
/** 
 * Sets up the given NetworkParameters with testnet values. 
 */
private static NetworkParameters createTestNet(NetworkParameters n){
  n.proofOfWorkLimit=new BigInteger("String_Node_Str",16);
  n.packetMagic=0xfabfb5daL;
  n.port=18333;
  n.addressHeader=111;
  n.acceptableAddressCodes=new int[]{111};
  n.dumpedPrivateKeyHeader=239;
  n.interval=INTERVAL;
  n.targetTimespan=TARGET_TIMESPAN;
  n.alertSigningKey=SATOSHI_KEY;
  n.genesisBlock=createGenesis(n);
  n.genesisBlock.setTime(1296688602L);
  n.genesisBlock.setDifficultyTarget(0x1d07fff8L);
  n.genesisBlock.setNonce(384568319);
  n.id=ID_TESTNET;
  n.checkBlockDifficulty=false;
  String genesisHash=n.genesisBlock.getHashAsString();
  checkState(genesisHash.equals("String_Node_Str"),genesisHash);
  return n;
}

Fixed version (ground truth):
/** 
 * Sets up the given NetworkParameters with testnet values. 
 */
private static NetworkParameters createTestNet(NetworkParameters n){
  n.proofOfWorkLimit=Utils.decodeCompactBits(0x1d0fffffL);
  n.packetMagic=0xfabfb5daL;
  n.port=18333;
  n.addressHeader=111;
  n.acceptableAddressCodes=new int[]{111};
  n.dumpedPrivateKeyHeader=239;
  n.interval=INTERVAL;
  n.targetTimespan=TARGET_TIMESPAN;
  n.alertSigningKey=SATOSHI_KEY;
  n.genesisBlock=createGenesis(n);
  n.genesisBlock.setTime(1296688602L);
  n.genesisBlock.setDifficultyTarget(0x1d07fff8L);
  n.genesisBlock.setNonce(384568319);
  n.id=ID_TESTNET;
  String genesisHash=n.genesisBlock.getHashAsString();
  checkState(genesisHash.equals("String_Node_Str"),genesisHash);
  return n;
}
Program: 85949
Project: 85949
Buggy source:
/** 
 * Returns a testnet params modified to allow any difficulty target. 
 */
public static NetworkParameters unitTests(){
  NetworkParameters n=new NetworkParameters();
  n=createTestNet(n);
  n.proofOfWorkLimit=new BigInteger("String_Node_Str",16);
  n.genesisBlock.setNonce(2);
  n.genesisBlock.setDifficultyTarget(Block.EASIEST_DIFFICULTY_TARGET);
  n.interval=10;
  n.targetTimespan=200000000;
  n.checkBlockDifficulty=true;
  n.id="String_Node_Str";
  return n;
}

Fixed version (ground truth):
/** 
 * Returns a testnet params modified to allow any difficulty target. 
 */
public static NetworkParameters unitTests(){
  NetworkParameters n=new NetworkParameters();
  n=createTestNet(n);
  n.proofOfWorkLimit=new BigInteger("String_Node_Str",16);
  n.genesisBlock.setNonce(2);
  n.genesisBlock.setDifficultyTarget(Block.EASIEST_DIFFICULTY_TARGET);
  n.interval=10;
  n.targetTimespan=200000000;
  n.id="String_Node_Str";
  return n;
}