nus-yam/ex-repair huggingface dataset:
Program: 20980
Project: 20980
Buggy source:
/** 
 * Stop scanning for devices. This method will be called when your app enters a background state. When your app resumes, startDiscovery will be called.
 */
public void stop(){
  for (  DiscoveryProvider provider : discoveryProviders) {
    provider.stop();
  }
  if (multicastLock.isHeld()) {
    multicastLock.release();
  }
  unregisterBroadcastReceiver();
}

Fixed version (ground truth):
/** 
 * Stop scanning for devices. This method will be called when your app enters a background state. When your app resumes, startDiscovery will be called.
 */
public void stop(){
  if (!mSearching)   return;
  mSearching=false;
  for (  DiscoveryProvider provider : discoveryProviders) {
    provider.stop();
  }
  if (multicastLock.isHeld()) {
    multicastLock.release();
  }
  if (!mShouldResume)   unregisterBroadcastReceiver();
}
Program: 20981
Project: 20981
Buggy source:
@Override public void start(){
  dataTimer=new Timer();
  dataTimer.schedule(new TimerTask(){
    @Override public void run(){
      sendSearch();
    }
  }
,100,RESCAN_INTERVAL);
  responseThread=new Thread(mResponseHandler);
  notifyThread=new Thread(mRespNotifyHandler);
  responseThread.start();
  notifyThread.start();
}

Fixed version (ground truth):
@Override public void start(){
  openSocket();
  dataTimer=new Timer();
  dataTimer.schedule(new TimerTask(){
    @Override public void run(){
      sendSearch();
    }
  }
,100,RESCAN_INTERVAL);
  responseThread=new Thread(mResponseHandler);
  notifyThread=new Thread(mRespNotifyHandler);
  responseThread.start();
  notifyThread.start();
}
Program: 20982
Project: 20982
Buggy source:
@Override public void stop(){
  dataTimer.cancel();
  responseThread.interrupt();
  notifyThread.interrupt();
  mSSDPSocket.close();
}

Fixed version (ground truth):
@Override public void stop(){
  dataTimer.cancel();
  responseThread.interrupt();
  notifyThread.interrupt();
  if (mSSDPSocket != null) {
    mSSDPSocket.close();
    mSSDPSocket=null;
  }
}
Program: 20983
Project: 20983
Buggy source:
public SSDPDiscoveryProvider(Context context){
  this.context=context;
  uuidReg=Pattern.compile("String_Node_Str");
  services=new ConcurrentHashMap<String,ServiceDescription>(8,0.75f,2);
  serviceListeners=new CopyOnWriteArrayList<DiscoveryProviderListener>();
  serviceFilters=new ArrayList<JSONObject>();
  WifiManager wifiMgr=(WifiManager)context.getSystemService(Context.WIFI_SERVICE);
  WifiInfo wifiInfo=wifiMgr.getConnectionInfo();
  int ip=wifiInfo.getIpAddress();
  byte[] ipAddress=Util.convertIpAddress(ip);
  try {
    InetAddress source=InetAddress.getByAddress(ipAddress);
    mSSDPSocket=new SSDPSocket(source);
  }
 catch (  UnknownHostException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
}

Fixed version (ground truth):
public SSDPDiscoveryProvider(Context context){
  this.context=context;
  uuidReg=Pattern.compile("String_Node_Str");
  services=new ConcurrentHashMap<String,ServiceDescription>(8,0.75f,2);
  serviceListeners=new CopyOnWriteArrayList<DiscoveryProviderListener>();
  serviceFilters=new ArrayList<JSONObject>();
}
Program: 20984
Project: 20984
Buggy source:
public JSONObject toJSONObject(){
  JSONObject jsonObj=new JSONObject();
  try {
    jsonObj.put("String_Node_Str",this.getClass().toString());
    jsonObj.put("String_Node_Str",lastDetected);
  }
 catch (  JSONException e) {
    e.printStackTrace();
  }
  return jsonObj;
}

Fixed version (ground truth):
public JSONObject toJSONObject(){
  JSONObject jsonObj=new JSONObject();
  try {
    jsonObj.put("String_Node_Str",this.getClass().toString());
    jsonObj.put("String_Node_Str",lastDetected);
    jsonObj.put("String_Node_Str",serviceUUID);
  }
 catch (  JSONException e) {
    e.printStackTrace();
  }
  return jsonObj;
}
Program: 20986
Project: 20986
Buggy source:
@SuppressWarnings("String_Node_Str") @Override public void run(){
  final ServiceCommand<ResponseListener<Object>> command=(ServiceCommand<ResponseListener<Object>>)mCommand;
  Object payload=command.getPayload();
  HttpRequestBase request=command.getRequest();
  request.addHeader(HttpMessage.USER_AGENT,HttpMessage.UDAP_USER_AGENT);
  HttpResponse response=null;
  if (payload != null && command.getHttpMethod().equalsIgnoreCase(ServiceCommand.TYPE_POST)) {
    HttpEntity entity=null;
    try {
      if (payload instanceof String) {
        entity=new StringEntity((String)payload);
      }
 else       if (payload instanceof JSONObject) {
        entity=new StringEntity(((JSONObject)payload).toString());
      }
    }
 catch (    UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    ((HttpPost)request).setEntity(entity);
  }
  try {
    response=httpClient.execute(request);
    final int code=response.getStatusLine().getStatusCode();
    if (code == 200) {
      HttpEntity entity=response.getEntity();
      final String message=EntityUtils.toString(entity,"String_Node_Str");
      Util.postSuccess(command.getResponseListener(),message);
    }
 else {
      Util.postError(command.getResponseListener(),ServiceCommandError.getError(code));
    }
    response.getEntity().consumeContent();
  }
 catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
}

Fixed version (ground truth):
@SuppressWarnings("String_Node_Str") @Override public void run(){
  final ServiceCommand<ResponseListener<Object>> command=(ServiceCommand<ResponseListener<Object>>)mCommand;
  Object payload=command.getPayload();
  HttpRequestBase request=command.getRequest();
  request.addHeader(HttpMessage.USER_AGENT,HttpMessage.UDAP_USER_AGENT);
  request.addHeader(HttpMessage.CONTENT_TYPE_HEADER,HttpMessage.CONTENT_TYPE);
  HttpResponse response=null;
  if (payload != null && command.getHttpMethod().equalsIgnoreCase(ServiceCommand.TYPE_POST)) {
    HttpEntity entity=null;
    try {
      if (payload instanceof String) {
        entity=new StringEntity((String)payload);
      }
 else       if (payload instanceof JSONObject) {
        entity=new StringEntity(((JSONObject)payload).toString());
      }
    }
 catch (    UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    ((HttpPost)request).setEntity(entity);
  }
  try {
    response=httpClient.execute(request);
    final int code=response.getStatusLine().getStatusCode();
    if (code == 200) {
      HttpEntity entity=response.getEntity();
      final String message=EntityUtils.toString(entity,"String_Node_Str");
      Util.postSuccess(command.getResponseListener(),message);
    }
 else {
      Util.postError(command.getResponseListener(),ServiceCommandError.getError(code));
    }
    response.getEntity().consumeContent();
  }
 catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
}
Program: 20987
Project: 20987
Buggy source:
/** 
 * Registers a commonly-used set of DeviceServices with DiscoveryManager. This method will be called on first call of startDiscovery if no DeviceServices have been registered. - CastDiscoveryProvider + CastService - SSDPDiscoveryProvider + DIALService + DLNAService (limited to LG TVs, currently) + NetcastTVService + RokuService + WebOSTVService
 */
public void registerDefaultDeviceTypes(){
  registerDeviceService(DIALService.class,SSDPDiscoveryProvider.class);
}

Fixed version (ground truth):
/** 
 * Registers a commonly-used set of DeviceServices with DiscoveryManager. This method will be called on first call of startDiscovery if no DeviceServices have been registered. - CastDiscoveryProvider + CastService - SSDPDiscoveryProvider + DIALService + DLNAService (limited to LG TVs, currently) + NetcastTVService + RokuService + WebOSTVService
 */
public void registerDefaultDeviceTypes(){
  registerDeviceService(WebOSTVService.class,SSDPDiscoveryProvider.class);
  registerDeviceService(NetcastTVService.class,SSDPDiscoveryProvider.class);
  registerDeviceService(DIALService.class,SSDPDiscoveryProvider.class);
  registerDeviceService(RokuService.class,SSDPDiscoveryProvider.class);
  registerDeviceService(CastService.class,CastDiscoveryProvider.class);
}
Program: 20988
Project: 20988
Buggy source:
@Override public void launchAppWithInfo(final AppInfo appInfo,Object params,final AppLaunchListener listener){
  ServiceCommand<ResponseListener<Object>> command=new ServiceCommand<ResponseListener<Object>>(this,requestURL(appInfo.getName()),params,new ResponseListener<Object>(){
    @Override public void onError(    ServiceCommandError error){
      Util.postError(listener,new ServiceCommandError(0,"String_Node_Str",null));
    }
    @Override public void onSuccess(    Object object){
      LaunchSession launchSession=LaunchSession.launchSessionForAppId(appInfo.getId());
      launchSession.setAppName(appInfo.getName());
      launchSession.setRawData(object);
      launchSession.setService(DIALService.this);
      Util.postSuccess(listener,launchSession);
    }
  }
);
  command.send();
}

Fixed version (ground truth):
@Override public void launchAppWithInfo(final AppInfo appInfo,Object params,final AppLaunchListener listener){
  ServiceCommand<ResponseListener<Object>> command=new ServiceCommand<ResponseListener<Object>>(this,requestURL(appInfo.getName()),params,new ResponseListener<Object>(){
    @Override public void onError(    ServiceCommandError error){
      Util.postError(listener,new ServiceCommandError(0,"String_Node_Str",null));
    }
    @Override public void onSuccess(    Object object){
      LaunchSession launchSession=LaunchSession.launchSessionForAppId(appInfo.getId());
      launchSession.setAppName(appInfo.getName());
      launchSession.setRawData(object);
      launchSession.setService(DIALService.this);
      launchSession.setSessionType(LaunchSessionType.App);
      Util.postSuccess(listener,launchSession);
    }
  }
);
  command.send();
}
Program: 20989
Project: 20989
Buggy source:
private void probeForAppSupport(){
  List<String> appsToProbe=new ArrayList<String>();
  appsToProbe.add("String_Node_Str");
  appsToProbe.add("String_Node_Str");
  for (  final String appID : appsToProbe) {
    hasApplication(appID,new ResponseListener<Object>(){
      @Override public void onError(      ServiceCommandError error){
      }
      @Override public void onSuccess(      Object object){
        addCapability("String_Node_Str" + appID);
      }
    }
);
  }
}

Fixed version (ground truth):
private void probeForAppSupport(){
  for (  final String appID : registeredApps) {
    hasApplication(appID,new ResponseListener<Object>(){
      @Override public void onError(      ServiceCommandError error){
      }
      @Override public void onSuccess(      Object object){
        addCapability("String_Node_Str" + appID);
      }
    }
);
  }
}
Program: 20990
Project: 20990
Buggy source:
private void probeForAppSupport(){
  getAppList(new AppListListener(){
    @Override public void onError(    ServiceCommandError error){
    }
    @Override public void onSuccess(    List<AppInfo> object){
      List<String> appsToProbe=new ArrayList<String>();
      appsToProbe.add("String_Node_Str");
      appsToProbe.add("String_Node_Str");
      appsToProbe.add("String_Node_Str");
      List<String> appsToAdd=new ArrayList<String>();
      for (      String probe : appsToProbe) {
        for (        AppInfo app : object) {
          if (app.getName().contains(probe)) {
            appsToAdd.add("String_Node_Str" + probe);
          }
        }
      }
      addCapabilities(appsToAdd);
    }
  }
);
}

Fixed version (ground truth):
private void probeForAppSupport(){
  getAppList(new AppListListener(){
    @Override public void onError(    ServiceCommandError error){
    }
    @Override public void onSuccess(    List<AppInfo> object){
      List<String> appsToAdd=new ArrayList<String>();
      for (      String probe : registeredApps) {
        for (        AppInfo app : object) {
          if (app.getName().contains(probe)) {
            appsToAdd.add("String_Node_Str" + probe);
          }
        }
      }
      addCapabilities(appsToAdd);
    }
  }
);
}
Program: 20991
Project: 20991
Buggy source:
@Override public void onSuccess(List<AppInfo> object){
  List<String> appsToProbe=new ArrayList<String>();
  appsToProbe.add("String_Node_Str");
  appsToProbe.add("String_Node_Str");
  appsToProbe.add("String_Node_Str");
  List<String> appsToAdd=new ArrayList<String>();
  for (  String probe : appsToProbe) {
    for (    AppInfo app : object) {
      if (app.getName().contains(probe)) {
        appsToAdd.add("String_Node_Str" + probe);
      }
    }
  }
  addCapabilities(appsToAdd);
}

Fixed version (ground truth):
@Override public void onSuccess(List<AppInfo> object){
  List<String> appsToAdd=new ArrayList<String>();
  for (  String probe : registeredApps) {
    for (    AppInfo app : object) {
      if (app.getName().contains(probe)) {
        appsToAdd.add("String_Node_Str" + probe);
      }
    }
  }
  addCapabilities(appsToAdd);
}
Program: 20992
Project: 20992
Buggy source:
@Override public void launchAppWithInfo(AppInfo appInfo,JSONObject params,Launcher.AppLaunchListener listener){
  String appName=HttpMessage.percentEncoding(appInfo.getName());
  String appId=appInfo.getId();
  String contentId=null;
  if (params != null) {
    try {
      contentId=(String)params.get("String_Node_Str");
    }
 catch (    JSONException e) {
      e.printStackTrace();
    }
  }
  launchApplication(appName,appId,contentId,listener);
}

Fixed version (ground truth):
@Override public void launchAppWithInfo(AppInfo appInfo,Object params,Launcher.AppLaunchListener listener){
  String appName=HttpMessage.percentEncoding(appInfo.getName());
  String appId=appInfo.getId();
  String contentId=null;
  JSONObject mParams=null;
  if (params instanceof JSONObject)   mParams=(JSONObject)params;
  if (mParams != null) {
    try {
      contentId=(String)mParams.get("String_Node_Str");
    }
 catch (    JSONException e) {
      e.printStackTrace();
    }
  }
  launchApplication(appName,appId,contentId,listener);
}
Program: 20993
Project: 20993
Buggy source:
private void setCapabilities(){
  if (DiscoveryManager.getInstance().getPairingLevel() == PairingLevel.ON) {
    appendCapabilites(TextInputControl.Capabilities);
    appendCapabilites(MouseControl.Capabilities);
    appendCapabilites(KeyControl.Capabilities);
    appendCapabilites(PowerControl.Capabilities);
    appendCapabilites(MediaPlayer.Capabilities);
    appendCapabilites(Play,Pause,Stop,Rewind,FastForward,Duration,Position,Seek,MetaData_Title,MetaData_MimeType,Application,Application_Close,Application_List,Browser,Hulu,Netflix,Netflix_Params,YouTube,YouTube_Params,Channel_Up,Channel_Down,Channel_Get,Channel_List,Channel_Subscribe,Get_3D,Set_3D,Subscribe_3D,Picker_Launch,Picker_Close,Volume_Get,Volume_Up_Down,Mute_Get,Mute_Set);
  }
 else {
    appendCapabilites(MediaPlayer.Capabilities);
    appendCapabilites(Play,Pause,Stop,Rewind,FastForward,YouTube,YouTube_Params);
  }
}

Fixed version (ground truth):
private void setCapabilities(){
  if (DiscoveryManager.getInstance().getPairingLevel() == PairingLevel.ON) {
    appendCapabilites(TextInputControl.Capabilities);
    appendCapabilites(MouseControl.Capabilities);
    appendCapabilites(KeyControl.Capabilities);
    appendCapabilites(PowerControl.Capabilities);
    appendCapabilites(MediaPlayer.Capabilities);
    appendCapabilites(Play,Pause,Stop,Rewind,FastForward,Duration,Position,Seek,MetaData_Title,MetaData_MimeType,Application,Application_Close,Application_List,Browser,Hulu,Netflix,Netflix_Params,YouTube,YouTube_Params,AppStore,AppStore_Params,Channel_Up,Channel_Down,Channel_Get,Channel_List,Channel_Subscribe,Get_3D,Set_3D,Subscribe_3D,Picker_Launch,Picker_Close,Volume_Get,Volume_Up_Down,Mute_Get,Mute_Set);
  }
 else {
    appendCapabilites(MediaPlayer.Capabilities);
    appendCapabilites(Play,Pause,Stop,Rewind,FastForward,YouTube,YouTube_Params);
  }
}
Program: 20994
Project: 20994
Buggy source:
private void setCapabilities(){
  appendCapabilites(Application,Application_Params,Application_List,Display_Image,Display_Video,Display_Audio,FastForward,Rewind,Play,Pause,Stop,Back,Down,Home,Left,Right,Up,OK,Send,Send_Delete,Send_Enter);
}

Fixed version (ground truth):
private void setCapabilities(){
  appendCapabilites(Application,Application_Params,Application_List,AppStore,AppStore_Params,Display_Image,Display_Video,Display_Audio,FastForward,Rewind,Play,Pause,Stop,Back,Down,Home,Left,Right,Up,OK,Send,Send_Delete,Send_Enter);
}
Program: 20995
Project: 20995
Buggy source:
@Override public void launchAppWithInfo(final AppInfo appInfo,JSONObject params,final Launcher.AppLaunchListener listener){
  ResponseListener<Object> responseListener=new ResponseListener<Object>(){
    @Override public void onSuccess(    Object response){
      Util.postSuccess(listener,new RokuLaunchSession(RokuService.this,appInfo.getId(),appInfo.getName()));
    }
    @Override public void onError(    ServiceCommandError error){
      Util.postError(listener,error);
    }
  }
;
  String action="String_Node_Str";
  String payload=appInfo.getId();
  String contentId=null;
  if (params != null && params.has("String_Node_Str")) {
    try {
      contentId=params.getString("String_Node_Str");
      payload+="String_Node_Str" + contentId;
    }
 catch (    JSONException e) {
      e.printStackTrace();
    }
  }
  String uri=requestURL(action,payload);
  ServiceCommand<ResponseListener<Object>> request=new ServiceCommand<ResponseListener<Object>>(this,uri,null,responseListener);
  request.send();
}

Fixed version (ground truth):
@Override public void launchAppWithInfo(final AppInfo appInfo,Object params,final Launcher.AppLaunchListener listener){
  ResponseListener<Object> responseListener=new ResponseListener<Object>(){
    @Override public void onSuccess(    Object response){
      Util.postSuccess(listener,new RokuLaunchSession(RokuService.this,appInfo.getId(),appInfo.getName()));
    }
    @Override public void onError(    ServiceCommandError error){
      Util.postError(listener,error);
    }
  }
;
  String action="String_Node_Str";
  String payload=appInfo.getId();
  String contentId=null;
  JSONObject mParams=null;
  if (params instanceof JSONObject)   mParams=(JSONObject)params;
  if (mParams != null && mParams.has("String_Node_Str")) {
    try {
      contentId=mParams.getString("String_Node_Str");
      payload+="String_Node_Str" + contentId;
    }
 catch (    JSONException e) {
      e.printStackTrace();
    }
  }
  String uri=requestURL(action,payload);
  ServiceCommand<ResponseListener<Object>> request=new ServiceCommand<ResponseListener<Object>>(this,uri,null,responseListener);
  request.send();
}
Program: 20996
Project: 20996
Buggy source:
/** 
 * prepare for connection
 * @param conf
 */
public void prepare(ICometConf conf){
  if (conf.channelAllocator == null) {
    conf.channelAllocator=new DefaultChannelAllocator();
  }
  mConf=conf;
  this.mChannel=conf.channelAllocator.allocate();
  this.host=conf.host;
  this.port=conf.port;
  this.url=buildURL(conf.conn_url);
  this.mICometCallback=conf.iCometCallback;
  this.mIConnCallback=conf.iConnCallback;
  this.mStatus=Status.STATUS_READY;
  this.mMsgQueue=new LinkedList<PubMessage>();
}

Fixed version (ground truth):
/** 
 * prepare for connection
 * @param conf
 */
public void prepare(ICometConf conf){
  if (conf.channelAllocator == null) {
    conf.channelAllocator=new DefaultChannelAllocator();
  }
  mConf=conf;
  this.mChannel=conf.channelAllocator.allocate();
  this.host=conf.host;
  this.port=conf.port;
  this.url=buildURL(conf.conn_url);
  this.mICometCallback=conf.iCometCallback;
  this.mIConnCallback=conf.iConnCallback;
  this.mStatus=Status.STATUS_READY;
}
Program: 20997
Project: 20997
Buggy source:
/** 
 * connect to iComet server please call this method in a child thread
 */
public void connect(){
  if (this.mStatus != Status.STATUS_READY) {
    return;
  }
  try {
    mConn=(HttpURLConnection)new URL(this.url).openConnection();
    mConn.setRequestMethod("String_Node_Str");
    mConn.setDoInput(true);
    mConn.setDoOutput(true);
    mConn.setRequestProperty("String_Node_Str","String_Node_Str");
    mConn.connect();
    mInput=new MessageInputStream(mConn.getInputStream());
  }
 catch (  Exception e) {
    if (mConn != null) {
      mConn.disconnect();
    }
    if (mIConnCallback != null) {
      mIConnCallback.onFail(e.getMessage());
    }
    reconnect();
    return;
  }
  this.mStatus=Status.STATUS_CONNCTED;
  if (mIConnCallback != null) {
    if (mReconnTimes == 0) {
      mIConnCallback.onSuccess();
    }
 else {
      mIConnCallback.onReconnectSuccess(mReconnTimes);
    }
  }
}

Fixed version (ground truth):
/** 
 * connect to iComet server please call this method in a child thread
 */
public void connect(){
  if (this.mStatus != Status.STATUS_READY) {
    return;
  }
  try {
    mConn=(HttpURLConnection)new URL(this.url).openConnection();
    mConn.setRequestMethod("String_Node_Str");
    mConn.setDoInput(true);
    mConn.setDoOutput(true);
    mConn.setRequestProperty("String_Node_Str","String_Node_Str");
    mConn.connect();
    mInput=new MessageInputStream(mConn.getInputStream());
  }
 catch (  Exception e) {
    if (mConn != null) {
      mConn.disconnect();
    }
    if (mIConnCallback != null) {
      mIConnCallback.onFail(e.getMessage());
    }
    reconnect();
    return;
  }
  this.mStatus=Status.STATUS_CONNCTED;
  if (mIConnCallback != null) {
    if (mReconnTimes == 0) {
      mIConnCallback.onSuccess();
    }
 else {
      mReconnTimes=0;
      mIConnCallback.onReconnectSuccess(mReconnTimes);
    }
  }
}
Program: 20998
Project: 20998
Buggy source:
public String request(LatLng start,LatLng end,String mode){
  final String url="String_Node_Str" + "String_Node_Str" + start.latitude + "String_Node_Str"+ start.longitude+ "String_Node_Str"+ end.latitude+ "String_Node_Str"+ end.longitude+ "String_Node_Str";
  if (isLogging)   Log.i("String_Node_Str","String_Node_Str" + url);
  new RequestTask().execute(new String[]{url});
  return url;
}

Fixed version (ground truth):
public String request(LatLng start,LatLng end,String mode){
  final String url="String_Node_Str" + "String_Node_Str" + start.latitude + "String_Node_Str"+ start.longitude+ "String_Node_Str"+ end.latitude+ "String_Node_Str"+ end.longitude+ "String_Node_Str"+ mode;
  if (isLogging)   Log.i("String_Node_Str","String_Node_Str" + url);
  new RequestTask().execute(new String[]{url});
  return url;
}
Program: 20999
Project: 20999
Buggy source:
public void isAnimated(){
  isAnimated=false;
}

Fixed version (ground truth):
public boolean isAnimated(){
  return isAnimated;
}
Program: 21000
Project: 21000
Buggy source:
/** 
 * @deprecated replaced with <a href="#engineSetParameter(java.security.spec.AlgorithmParameterSpec)">
 */
@Override protected void engineSetParameter(String param,Object value){
  throw new UnsupportedOperationException("String_Node_Str");
}

Fixed version (ground truth):
/** 
 * @deprecated
 */
@Override protected void engineSetParameter(String param,Object value){
  throw new UnsupportedOperationException("String_Node_Str");
}
Program: 21001
Project: 21001
Buggy source:
/** 
 * Creates a group element for a curve from a given encoded point. <p> A point $(x,y)$ is encoded by storing $y$ in bit 0 to bit 254 and the sign of $x$ in bit 255. $x$ is recovered in the following way: <p><ul> <li>$x = sign(x) * \sqrt{(y^2 - 1) / (d * y^2 + 1)} = sign(x) * \sqrt{u / v}$ with $u = y^2 - 1$ and $v = d * y^2 + 1$. <li>Setting $β = (u * v^3) * (u * v^7)^{((q - 5) / 8)}$ one has $β^2 = \pm(u / v)$. <li>If $v * β = -u$ multiply $β$ with $i=\sqrt{-1}$. <li>Set $x := β$. <li>If $sign(x) \ne$ bit 255 of $s$ then negate $x$.
 * @param curve The curve.
 * @param s The encoded point.
 */
public GroupElement(final Curve curve,final byte[] s){
  FieldElement x, y, yy, u, v, v3, vxx, check;
  y=curve.getField().fromByteArray(s);
  yy=y.square();
  u=yy.subtractOne();
  v=yy.multiply(curve.getD()).addOne();
  v3=v.square().multiply(v);
  x=v3.square().multiply(v).multiply(u);
  x=x.pow22523();
  x=v3.multiply(u).multiply(x);
  vxx=x.square().multiply(v);
  check=vxx.subtract(u);
  if (check.isNonZero()) {
    check=vxx.add(u);
    if (check.isNonZero())     throw new IllegalArgumentException("String_Node_Str");
    x=x.multiply(curve.getI());
  }
  if ((x.isNegative() ? 1 : 0) != Utils.bit(s,curve.getField().getb() - 1)) {
    x=x.negate();
  }
  this.curve=curve;
  this.repr=Representation.P3;
  this.X=x;
  this.Y=y;
  this.Z=curve.getField().ONE;
  this.T=this.X.multiply(this.Y);
}

Fixed version (ground truth):
/** 
 * Creates a group element for a curve from a given encoded point. <p> A point $(x,y)$ is encoded by storing $y$ in bit 0 to bit 254 and the sign of $x$ in bit 255. $x$ is recovered in the following way: </p><ul> <li>$x = sign(x) * \sqrt{(y^2 - 1) / (d * y^2 + 1)} = sign(x) * \sqrt{u / v}$ with $u = y^2 - 1$ and $v = d * y^2 + 1$. <li>Setting $β = (u * v^3) * (u * v^7)^{((q - 5) / 8)}$ one has $β^2 = \pm(u / v)$. <li>If $v * β = -u$ multiply $β$ with $i=\sqrt{-1}$. <li>Set $x := β$. <li>If $sign(x) \ne$ bit 255 of $s$ then negate $x$. </ul>
 * @param curve The curve.
 * @param s The encoded point.
 */
public GroupElement(final Curve curve,final byte[] s){
  FieldElement x, y, yy, u, v, v3, vxx, check;
  y=curve.getField().fromByteArray(s);
  yy=y.square();
  u=yy.subtractOne();
  v=yy.multiply(curve.getD()).addOne();
  v3=v.square().multiply(v);
  x=v3.square().multiply(v).multiply(u);
  x=x.pow22523();
  x=v3.multiply(u).multiply(x);
  vxx=x.square().multiply(v);
  check=vxx.subtract(u);
  if (check.isNonZero()) {
    check=vxx.add(u);
    if (check.isNonZero())     throw new IllegalArgumentException("String_Node_Str");
    x=x.multiply(curve.getI());
  }
  if ((x.isNegative() ? 1 : 0) != Utils.bit(s,curve.getField().getb() - 1)) {
    x=x.negate();
  }
  this.curve=curve;
  this.repr=Representation.P3;
  this.X=x;
  this.Y=y;
  this.Z=curve.getField().ONE;
  this.T=this.X.multiply(this.Y);
}
Program: 21002
Project: 21002
Buggy source:
/** 
 * $h = a * B$ where $a = a[0]+256*a[1]+\dots+256^{31} a[31]$ and $B$ is this point. If its lookup table has not been precomputed, it will be at the start of the method (and cached for later calls). Constant time. <p> Preconditions: (TODO: Check this applies here) $a[31] <= 127$
 * @param a $= a[0]+256*a[1]+\dots+256^{31} a[31]$
 * @return the GroupElement
 */
public GroupElement scalarMultiply(final byte[] a){
  GroupElement t;
  int i;
  final byte[] e=toRadix16(a);
  GroupElement h=this.curve.getZero(Representation.P3);
synchronized (this) {
    for (i=1; i < 64; i+=2) {
      t=select(i / 2,e[i]);
      h=h.madd(t).toP3();
    }
    h=h.dbl().toP2().dbl().toP2().dbl().toP2().dbl().toP3();
    for (i=0; i < 64; i+=2) {
      t=select(i / 2,e[i]);
      h=h.madd(t).toP3();
    }
  }
  return h;
}

Fixed version (ground truth):
/** 
 * $h = a * B$ where $a = a[0]+256*a[1]+\dots+256^{31} a[31]$ and $B$ is this point. If its lookup table has not been precomputed, it will be at the start of the method (and cached for later calls). Constant time. <p> Preconditions: (TODO: Check this applies here) $a[31] \le 127$
 * @param a $= a[0]+256*a[1]+\dots+256^{31} a[31]$
 * @return the GroupElement
 */
public GroupElement scalarMultiply(final byte[] a){
  GroupElement t;
  int i;
  final byte[] e=toRadix16(a);
  GroupElement h=this.curve.getZero(Representation.P3);
synchronized (this) {
    for (i=1; i < 64; i+=2) {
      t=select(i / 2,e[i]);
      h=h.madd(t).toP3();
    }
    h=h.dbl().toP2().dbl().toP2().dbl().toP2().dbl().toP3();
    for (i=0; i < 64; i+=2) {
      t=select(i / 2,e[i]);
      h=h.madd(t).toP3();
    }
  }
  return h;
}
Program: 21003
Project: 21003
Buggy source:
/** 
 * $h = f + g$ <p> TODO-CR BR: $h$ is allocated via new, probably not a good idea. Do we need the copying into temp variables if we do that? <p> Preconditions: <p><ul> <li>$|f|$ bounded by $1.1*2^{25},1.1*2^{24},1.1*2^{25},1.1*2^{24},$ etc. <li>$|g|$ bounded by $1.1*2^{25},1.1*2^{24},1.1*2^{25},1.1*2^{24},$ etc. </ul><p> Postconditions: <p><ul> <li>$|h|$ bounded by $1.1*2^{26},1.1*2^{25},1.1*2^{26},1.1*2^{25},$ etc.
 * @param val The field element to add.
 * @return The field element this + val.
 */
public FieldElement add(FieldElement val){
  int[] g=((Ed25519FieldElement)val).t;
  int[] h=new int[10];
  for (int i=0; i < 10; i++) {
    h[i]=t[i] + g[i];
  }
  return new Ed25519FieldElement(f,h);
}

Fixed version (ground truth):
/** 
 * $h = f + g$ <p> TODO-CR BR: $h$ is allocated via new, probably not a good idea. Do we need the copying into temp variables if we do that? <p> Preconditions: </p><ul> <li>$|f|$ bounded by $1.1*2^{25},1.1*2^{24},1.1*2^{25},1.1*2^{24},$ etc. <li>$|g|$ bounded by $1.1*2^{25},1.1*2^{24},1.1*2^{25},1.1*2^{24},$ etc. </ul><p> Postconditions: </p><ul> <li>$|h|$ bounded by $1.1*2^{26},1.1*2^{25},1.1*2^{26},1.1*2^{25},$ etc. </ul>
 * @param val The field element to add.
 * @return The field element this + val.
 */
public FieldElement add(FieldElement val){
  int[] g=((Ed25519FieldElement)val).t;
  int[] h=new int[10];
  for (int i=0; i < 10; i++) {
    h[i]=t[i] + g[i];
  }
  return new Ed25519FieldElement(f,h);
}
Program: 21004
Project: 21004
Buggy source:
/** 
 * $h = f - g$ <p> Can overlap $h$ with $f$ or $g$. <p> TODO-CR BR: See above. <p> Preconditions: <p><ul> <li>$|f|$ bounded by $1.1*2^{25},1.1*2^{24},1.1*2^{25},1.1*2^{24},$ etc. <li>$|g|$ bounded by $1.1*2^{25},1.1*2^{24},1.1*2^{25},1.1*2^{24},$ etc. </ul><p> Postconditions: <p><ul> <li>$|h|$ bounded by $1.1*2^{26},1.1*2^{25},1.1*2^{26},1.1*2^{25},$ etc.
 * @param val The field element to subtract.
 * @return The field element this - val.
 */
public FieldElement subtract(FieldElement val){
  int[] g=((Ed25519FieldElement)val).t;
  int[] h=new int[10];
  for (int i=0; i < 10; i++) {
    h[i]=t[i] - g[i];
  }
  return new Ed25519FieldElement(f,h);
}

Fixed version (ground truth):
/** 
 * $h = f - g$ <p> Can overlap $h$ with $f$ or $g$. <p> TODO-CR BR: See above. <p> Preconditions: </p><ul> <li>$|f|$ bounded by $1.1*2^{25},1.1*2^{24},1.1*2^{25},1.1*2^{24},$ etc. <li>$|g|$ bounded by $1.1*2^{25},1.1*2^{24},1.1*2^{25},1.1*2^{24},$ etc. </ul><p> Postconditions: </p><ul> <li>$|h|$ bounded by $1.1*2^{26},1.1*2^{25},1.1*2^{26},1.1*2^{25},$ etc. </ul>
 * @param val The field element to subtract.
 * @return The field element this - val.
 */
public FieldElement subtract(FieldElement val){
  int[] g=((Ed25519FieldElement)val).t;
  int[] h=new int[10];
  for (int i=0; i < 10; i++) {
    h[i]=t[i] - g[i];
  }
  return new Ed25519FieldElement(f,h);
}
Program: 21007
Project: 21007
Buggy source:
/** 
 * $h = -f$ <p> TODO-CR BR: see above. <p> Preconditions: <p><ul> <li>$|f|$ bounded by $1.1*2^{25},1.1*2^{24},1.1*2^{25},1.1*2^{24},$ etc. </ul><p> Postconditions: <p><ul> <li>$|h|$ bounded by $1.1*2^{25},1.1*2^{24},1.1*2^{25},1.1*2^{24},$ etc.
 * @return The field element (-1) * this.
 */
public FieldElement negate(){
  int[] h=new int[10];
  for (int i=0; i < 10; i++) {
    h[i]=-t[i];
  }
  return new Ed25519FieldElement(f,h);
}

Fixed version (ground truth):
/** 
 * $h = -f$ <p> TODO-CR BR: see above. <p> Preconditions: </p><ul> <li>$|f|$ bounded by $1.1*2^{25},1.1*2^{24},1.1*2^{25},1.1*2^{24},$ etc. </ul><p> Postconditions: </p><ul> <li>$|h|$ bounded by $1.1*2^{25},1.1*2^{24},1.1*2^{25},1.1*2^{24},$ etc. </ul>
 * @return The field element (-1) * this.
 */
public FieldElement negate(){
  int[] h=new int[10];
  for (int i=0; i < 10; i++) {
    h[i]=-t[i];
  }
  return new Ed25519FieldElement(f,h);
}
Program: 21010
Project: 21010
Buggy source:
/** 
 * Is the FieldElement negative in this encoding? <p> Return true if $x$ is in $\{1,3,5,\dots,q-2\}$<br> Return false if $x$ is in $\{0,2,4,\dots,q-1\}$ <p> Preconditions: <p><ul> <li>$|x|$ bounded by $1.1*2^{26},1.1*2^{25},1.1*2^{26},1.1*2^{25}$, etc.
 * @return true if $x$ is in $\{1,3,5,\dots,q-2\}$, false otherwise.
 */
public boolean isNegative(FieldElement x){
  byte[] s=encode(x);
  return (s[0] & 1) != 0;
}

Fixed version (ground truth):
/** 
 * Is the FieldElement negative in this encoding? <p> Return true if $x$ is in $\{1,3,5,\dots,q-2\}$<br> Return false if $x$ is in $\{0,2,4,\dots,q-1\}$ <p> Preconditions: </p><ul> <li>$|x|$ bounded by $1.1*2^{26},1.1*2^{25},1.1*2^{26},1.1*2^{25}$, etc. </ul>
 * @return true if $x$ is in $\{1,3,5,\dots,q-2\}$, false otherwise.
 */
public boolean isNegative(FieldElement x){
  byte[] s=encode(x);
  return (s[0] & 1) != 0;
}
Program: 21012
Project: 21012
Buggy source:
/** 
 * Specific hash requested, only matching keys will be allowed.
 * @param digest the hash algorithm that keys must have to sign or verify.
 */
public EdDSAEngine(MessageDigest digest){
  this();
  this.digest=digest;
}

Fixed version (ground truth):
/** 
 * Specific EdDSA-internal hash requested, only matching keys will be allowed.
 * @param digest the hash algorithm that keys must have to sign or verify.
 */
public EdDSAEngine(MessageDigest digest){
  this();
  this.digest=digest;
}
Program: 21014
Project: 21014
Buggy source:
public FieldElement(Field f){
  this.f=f;
}

Fixed version (ground truth):
public FieldElement(Field f){
  if (null == f) {
    throw new IllegalArgumentException("String_Node_Str");
  }
  this.f=f;
}
Program: 21015
Project: 21015
Buggy source:
/** 
 * Gets a value indicating whether or not the field element is non-zero.
 * @return 1 if it is non-zero, 0 otherwise.
 */
public boolean isNonZero(){
  byte[] s=toByteArray();
  return Utils.equal(s,zero) == 1;
}

Fixed version (ground truth):
/** 
 * Gets a value indicating whether or not the field element is non-zero.
 * @return 1 if it is non-zero, 0 otherwise.
 */
public boolean isNonZero(){
  final byte[] s=toByteArray();
  return Utils.equal(s,ZERO) == 0;
}
Program: 21016
Project: 21016
Buggy source:
/** 
 * Converts a 32 byte representation to a BigInteger. Value: bytes[0] + 2^8 * bytes[1] + ... + 2^248 * bytes[31]
 * @param bytes The 32 byte representation.
 * @return The BigInteger.
 */
public static BigInteger toBigInteger(final byte[] bytes){
  BigInteger b=BigInteger.ZERO;
  for (int i=0; i < 32; i++) {
    b=b.add(BigInteger.ONE.multiply(BigInteger.valueOf(bytes[i] & 0xff)).shiftLeft(i * 8));
  }
  return b;
}

Fixed version (ground truth):
/** 
 * Converts a field element to a BigInteger.
 * @param f The field element.
 * @return The BigInteger.
 */
public static BigInteger toBigInteger(final FieldElement f){
  return toBigInteger(f.toByteArray());
}
Program: 21017
Project: 21017
Buggy source:
@Test public void decodeReturnsCorrectFieldElement(){
  for (int i=0; i < 10000; i++) {
    final byte[] bytes=new byte[32];
    random.nextBytes(bytes);
    bytes[31]=(byte)(bytes[31] & 0x7f);
    final BigInteger b1=MathUtils.toBigInteger(bytes);
    final Ed25519FieldElement f=(Ed25519FieldElement)MathUtils.getField().getEncoding().decode(bytes);
    final BigInteger b2=MathUtils.toBigInteger(f.t).mod(q);
    Assert.assertThat(b2,IsEqual.equalTo(b1));
  }
}

Fixed version (ground truth):
@Test public void decodeReturnsCorrectFieldElement(){
  for (int i=0; i < 10000; i++) {
    final byte[] bytes=new byte[32];
    random.nextBytes(bytes);
    bytes[31]=(byte)(bytes[31] & 0x7f);
    final BigInteger b1=MathUtils.toBigInteger(bytes);
    final Ed25519FieldElement f=(Ed25519FieldElement)MathUtils.getField().getEncoding().decode(bytes);
    final BigInteger b2=MathUtils.toBigInteger(f.t).mod(MathUtils.getQ());
    Assert.assertThat(b2,IsEqual.equalTo(b1));
  }
}
Program: 21018
Project: 21018
Buggy source:
@Test public void encodeReturnsCorrectByteArray(){
  for (int i=0; i < 10000; i++) {
    final int[] t=new int[10];
    for (int j=0; j < 10; j++) {
      t[j]=random.nextInt(1 << 28) - (1 << 27);
    }
    final FieldElement fieldElement1=new Ed25519FieldElement(MathUtils.getField(),t);
    final BigInteger b=MathUtils.toBigInteger(t);
    final byte[] bytes=MathUtils.getField().getEncoding().encode(fieldElement1);
    Assert.assertThat(bytes,IsEqual.equalTo(MathUtils.toByteArray(b.mod(q))));
  }
}

Fixed version (ground truth):
@Test public void encodeReturnsCorrectByteArray(){
  for (int i=0; i < 10000; i++) {
    final int[] t=new int[10];
    for (int j=0; j < 10; j++) {
      t[j]=random.nextInt(1 << 28) - (1 << 27);
    }
    final FieldElement fieldElement1=new Ed25519FieldElement(MathUtils.getField(),t);
    final BigInteger b=MathUtils.toBigInteger(t);
    final byte[] bytes=MathUtils.getField().getEncoding().encode(fieldElement1);
    Assert.assertThat(bytes,IsEqual.equalTo(MathUtils.toByteArray(b.mod(MathUtils.getQ()))));
  }
}
Program: 21019
Project: 21019
Buggy source:
@SuppressWarnings("String_Node_Str") @Override protected <T extends KeySpec>T engineGetKeySpec(Key key,Class<T> keySpec) throws InvalidKeySpecException {
  if (keySpec.isAssignableFrom(EdDSAPublicKeySpec.class) && key instanceof EdDSAPublicKey) {
    EdDSAPublicKey k=(EdDSAPublicKey)key;
    if (k.getParams() != null) {
      return (T)new EdDSAPublicKeySpec(k.getA(),k.getParams());
    }
  }
 else   if (keySpec.isAssignableFrom(EdDSAPrivateKeySpec.class) && key instanceof EdDSAPrivateKey) {
    EdDSAPrivateKey k=(EdDSAPrivateKey)key;
    if (k.getParams() != null) {
      return (T)new EdDSAPrivateKeySpec(k.getH(),k.geta(),k.getA(),k.getParams());
    }
  }
  throw new InvalidKeySpecException("String_Node_Str" + key + "String_Node_Str"+ keySpec);
}

Fixed version (ground truth):
@SuppressWarnings("String_Node_Str") @Override protected <T extends KeySpec>T engineGetKeySpec(Key key,Class<T> keySpec) throws InvalidKeySpecException {
  if (keySpec.isAssignableFrom(EdDSAPublicKeySpec.class) && key instanceof EdDSAPublicKey) {
    EdDSAPublicKey k=(EdDSAPublicKey)key;
    if (k.getParams() != null) {
      return (T)new EdDSAPublicKeySpec(k.getA(),k.getParams());
    }
  }
 else   if (keySpec.isAssignableFrom(EdDSAPrivateKeySpec.class) && key instanceof EdDSAPrivateKey) {
    EdDSAPrivateKey k=(EdDSAPrivateKey)key;
    if (k.getParams() != null) {
      return (T)new EdDSAPrivateKeySpec(k.getSeed(),k.getH(),k.geta(),k.getA(),k.getParams());
    }
  }
  throw new InvalidKeySpecException("String_Node_Str" + key + "String_Node_Str"+ keySpec);
}
Program: 21020
Project: 21020
Buggy source:
public EdDSAPrivateKeySpec(byte[] h,BigInteger a,GroupElement A,EdDSAParameterSpec spec){
  this.h=h;
  this.a=a;
  this.A=A;
  this.spec=spec;
}

Fixed version (ground truth):
public EdDSAPrivateKeySpec(byte[] seed,byte[] h,BigInteger a,GroupElement A,EdDSAParameterSpec spec){
  this.seed=seed;
  this.h=h;
  this.a=a;
  this.A=A;
  this.spec=spec;
}
Program: 21021
Project: 21021
Buggy source:
@Override protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
  Curve curve=key.getParams().getCurve();
  int b=curve.getField().getb();
  if (sigBytes.length != b / 4)   throw new IllegalArgumentException("String_Node_Str");
  byte[] Rbyte=Arrays.copyOfRange(sigBytes,0,b / 8);
  byte[] Sbyte=Arrays.copyOfRange(sigBytes,b / 8,b / 4);
  digest.update(Rbyte);
  digest.update(((EdDSAPublicKey)key).getAbyte());
  byte[] h=digest.digest(message);
  GroupElement R=key.getParams().getB().doubleScalarMultiplyVariableTime(((EdDSAPublicKey)key).getA(),h,Sbyte);
  if (!R.toByteArray().equals(Rbyte))   return false;
  return true;
}

Fixed version (ground truth):
@Override protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
  Curve curve=key.getParams().getCurve();
  int b=curve.getField().getb();
  if (sigBytes.length != b / 4)   throw new IllegalArgumentException("String_Node_Str");
  byte[] Rbyte=Arrays.copyOfRange(sigBytes,0,b / 8);
  byte[] Sbyte=Arrays.copyOfRange(sigBytes,b / 8,b / 4);
  digest.update(Rbyte);
  digest.update(((EdDSAPublicKey)key).getAbyte());
  byte[] h=digest.digest(message);
  LittleEndianEncoding leEnc=new LittleEndianEncoding();
  h=leEnc.encode(leEnc.decode(h).mod(key.getParams().getL()),b / 8);
  GroupElement R=key.getParams().getB().doubleScalarMultiplyVariableTime(((EdDSAPublicKey)key).getA(),h,Sbyte);
  if (!R.toByteArray().equals(Rbyte))   return false;
  return true;
}
Program: 21022
Project: 21022
Buggy source:
private BigInteger Hint(byte[] h){
  BigInteger hsum=BigInteger.ZERO;
  for (int i=0; i < 2 * key.getParams().getCurve().getField().getb(); i++) {
    hsum=hsum.add(BigInteger.valueOf(2).pow(i).multiply(BigInteger.valueOf(bit(h,i))));
  }
  return hsum;
}

Fixed version (ground truth):
/** 
 * From the Ed25519 paper: Here we interpret 2b-bit strings in little-endian form as integers in {0, 1,..., 2^(2b)-1}.
 * @param h the output of a hash function.
 * @return 2^h
 */
private BigInteger Hint(byte[] h){
  if (h.length != key.getParams().getCurve().getField().getb() / 4)   throw new IllegalArgumentException("String_Node_Str");
  for (int i=0; i < h.length / 2; i++) {
    byte tmp=h[i];
    h[i]=h[h.length - 1 - i];
    h[h.length - 1 - i]=tmp;
  }
  return new BigInteger(1,h);
}
Program: 21023
Project: 21023
Buggy source:
public Field(int b,BigInteger q){
  this.b=b;
  this.q=q;
  this.qm2=q.subtract(Constants.TWO);
  this.qm5=q.subtract(Constants.FIVE);
  this.qp3=q.add(Constants.THREE);
}

Fixed version (ground truth):
public Field(int b,BigInteger q){
  this.b=b;
  this.q=q;
  this.qm2=q.subtract(Constants.TWO);
  this.qm5=q.subtract(Constants.FIVE);
  this.qp3=q.add(Constants.THREE);
  this.mask=Constants.ONE.shiftLeft(b - 1).subtract(Constants.ONE);
}
Program: 21024
Project: 21024
Buggy source:
public boolean isNegative(){
  return bi.compareTo(BigInteger.ZERO) == -1;
}

Fixed version (ground truth):
/** 
 * From the Ed25519 paper: x is negative if the (b-1)-bit encoding of x is lexicographically larger than the (b-1)-bit encoding of -x. If q is an odd prime and the encoding is the little-endian representation of {0, 1,..., q-1} then the negative elements of F_q are {1, 3, 5,..., q-2}.
 * @return
 */
public boolean isNegative(){
  return bi.testBit(0);
}
Program: 21025
Project: 21025
Buggy source:
/** 
 * Translates a byte array containing the two's-complement binary representation of a FieldElement into a FieldElement. The input array is assumed to be in little-endian byte-order: the least significant byte is in the zeroth element.
 * @param val
 */
public FieldElement(Field f,byte[] val){
  if (val.length != f.getb() / 8)   throw new IllegalArgumentException("String_Node_Str");
  byte[] out=new byte[val.length];
  for (int i=0; i < val.length; i++) {
    out[i]=val[val.length - 1 - i];
  }
  out[0]&=0x7f;
  this.f=f;
  this.bi=new BigInteger(out);
}

Fixed version (ground truth):
/** 
 * Decode a FieldElement from its (b-1)-bit encoding. The highest bit is masked out.
 * @param val the (b-1)-bit encoding of a FieldElement.
 * @return the FieldElement represented by 'val'.
 */
public FieldElement(Field f,byte[] val){
  if (val.length != f.getb() / 8)   throw new IllegalArgumentException("String_Node_Str");
  byte[] out=new byte[val.length];
  for (int i=0; i < val.length; i++) {
    out[i]=val[val.length - 1 - i];
  }
  this.f=f;
  this.bi=new BigInteger(1,out).and(f.getMask());
}
Program: 21026
Project: 21026
Buggy source:
/** 
 * Returns a byte array containing the two's-complement representation of this FieldElement. The byte array will be in little-endian byte-order: the least significant byte is in the zeroth element. The array will contain b/8 bytes.
 * @return a byte array containing the two's-complement representation ofthis FieldElement.
 */
public byte[] toByteArray(){
  byte[] in=bi.toByteArray();
  byte[] out=new byte[f.getb() / 8];
  for (int i=0; i < in.length; i++) {
    out[i]=in[in.length - 1 - i];
  }
  for (int i=in.length; i < out.length; i++) {
    out[i]=0;
  }
  return out;
}

Fixed version (ground truth):
/** 
 * Encode a FieldElement in its (b-1)-bit encoding.
 * @return the (b-1)-bit encoding of this FieldElement.
 */
public byte[] toByteArray(){
  byte[] in=bi.and(f.getMask()).toByteArray();
  byte[] out=new byte[f.getb() / 8];
  for (int i=0; i < in.length; i++) {
    out[i]=in[in.length - 1 - i];
  }
  for (int i=in.length; i < out.length; i++) {
    out[i]=0;
  }
  return out;
}
Program: 21027
Project: 21027
Buggy source:
public GroupElement(Curve curve,byte[] s){
  FieldElement x, y, yy, u, v, v3, vxx, check;
  y=curve.fromByteArray(s);
  yy=y.square();
  u=yy.subtractOne();
  v=yy.multiply(curve.getD()).addOne();
  v3=v.square().multiply(v);
  x=v3.square().multiply(v).multiply(u);
  x=x.pow(curve.getField().getQm5().divide(BigInteger.valueOf(8)));
  x=v3.multiply(u).multiply(x);
  vxx=x.square().multiply(v);
  check=vxx.subtract(u);
  if (check.isNonZero()) {
    check=vxx.add(u);
    if (check.isNonZero())     throw new IllegalArgumentException("String_Node_Str");
    x=x.multiply(curve.getI());
  }
  if ((x.isNegative() ? 1 : 0) == (s[s.length - 1] & 0x01)) {
    x=x.negate();
  }
  this.curve=curve;
  repr=Representation.P3;
  X=x;
  Y=y;
  Z=curve.fromBigInteger(Constants.ONE);
  T=X.multiply(Y);
}

Fixed version (ground truth):
public GroupElement(Curve curve,byte[] s){
  FieldElement x, y, yy, u, v, v3, vxx, check;
  y=curve.fromByteArray(s);
  yy=y.square();
  u=yy.subtractOne();
  v=yy.multiply(curve.getD()).addOne();
  v3=v.square().multiply(v);
  x=v3.square().multiply(v).multiply(u);
  x=x.pow(curve.getField().getQm5().divide(BigInteger.valueOf(8)));
  x=v3.multiply(u).multiply(x);
  vxx=x.square().multiply(v);
  check=vxx.subtract(u);
  if (check.isNonZero()) {
    check=vxx.add(u);
    if (check.isNonZero())     throw new IllegalArgumentException("String_Node_Str");
    x=x.multiply(curve.getI());
  }
  if ((x.isNegative() ? 1 : 0) != Utils.bit(s,curve.getField().getb() - 1)) {
    x=x.negate();
  }
  this.curve=curve;
  repr=Representation.P3;
  X=x;
  Y=y;
  Z=curve.fromBigInteger(Constants.ONE);
  T=X.multiply(Y);
}
Program: 21028
Project: 21028
Buggy source:
public byte[] toByteArray(){
switch (repr) {
case P2:
case P3:
    FieldElement recip=Z.invert();
  FieldElement x=X.multiply(recip);
FieldElement y=Y.multiply(recip);
byte[] s=y.toByteArray();
s[s.length - 1]|=(x.isNegative() ? 0x80 : 0);
return s;
default :
return toP2().toByteArray();
}
}

Fixed version (ground truth):
public byte[] toByteArray(){
switch (repr) {
case P2:
case P3:
    FieldElement recip=Z.invert();
  FieldElement x=X.multiply(recip);
FieldElement y=Y.multiply(recip);
byte[] s=y.toByteArray();
s[s.length - 1]|=(x.isNegative() ? (byte)0x80 : 0);
return s;
default :
return toP2().toByteArray();
}
}
Program: 21029
Project: 21029
Buggy source:
@Override public KeyPair generateKeyPair(){
  if (!initialized)   initialize(strength,new SecureRandom());
  byte[] seed=new byte[edParams.getCurve().getField().getb()];
  random.nextBytes(seed);
  EdDSAPrivateKeySpec privKey=new EdDSAPrivateKeySpec(seed,edParams);
  EdDSAPublicKeySpec pubKey=new EdDSAPublicKeySpec(privKey.getA(),edParams);
  return new KeyPair(new EdDSAPublicKey(pubKey),new EdDSAPrivateKey(privKey));
}

Fixed version (ground truth):
@Override public KeyPair generateKeyPair(){
  if (!initialized)   initialize(strength,new SecureRandom());
  byte[] seed=new byte[edParams.getCurve().getField().getb() / 8];
  random.nextBytes(seed);
  EdDSAPrivateKeySpec privKey=new EdDSAPrivateKeySpec(seed,edParams);
  EdDSAPublicKeySpec pubKey=new EdDSAPublicKeySpec(privKey.getA(),edParams);
  return new KeyPair(new EdDSAPublicKey(pubKey),new EdDSAPrivateKey(privKey));
}
Program: 21030
Project: 21030
Buggy source:
private static GroupElement scalarmult(GroupElement P,BigInteger e){
  BigInteger[] t=new BigInteger[9999];
  GroupElement Q;
  t[0]=e;
  int i=1;
  while (true) {
    t[i]=t[i - 1].divide(BigInteger.valueOf(2));
    ;
    if (t[i].equals(BigInteger.ZERO)) {
      break;
    }
    i++;
  }
  GroupElement Pcached=GroupElement.cached(P);
  Q=GroupElement.P2_ZERO;
  for (int j=i; j >= 0; j--) {
    Q=Q.add(GroupElement.cached(Q));
    if (t[j].testBit(0))     Q=Q.add(Pcached);
  }
  return Q;
}

Fixed version (ground truth):
private static GroupElement scalarmult(GroupElement P,BigInteger e){
  BigInteger[] t=new BigInteger[9999];
  GroupElement Q;
  t[0]=e;
  int i=1;
  while (true) {
    t[i]=t[i - 1].divide(BigInteger.valueOf(2));
    ;
    if (t[i].equals(BigInteger.ZERO)) {
      break;
    }
    i++;
  }
  GroupElement Pcached=GroupElement.cached(P);
  Q=GroupElement.P3_ZERO;
  for (int j=i; j >= 0; j--) {
    Q=GroupElement.p3(Q.add(GroupElement.cached(Q)));
    if (t[j].testBit(0))     Q=GroupElement.p3(Q.add(Pcached));
  }
  return Q;
}