input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code @Override protected void init() { super.init(); currentAddress = stringsStartAddress; full = false; currentSegmentIndex = INDEX_NOT_YET_USED; directMemoryService.setMemory(inUseSegmentAddress, totalSegmentCount, (byte) 0x00); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void init() { super.init(); currentAddress = stringsStartAddress; full = false; currentSegmentIndex = INDEX_NOT_YET_USED; //directMemoryService.setMemory(inUseSegmentAddress, totalSegmentCount, (byte) 0x00); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } synchronized (sampleObject) { sampleHeader = directMemoryService.getLong(sampleObject, 0L); } objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); } #location 25 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } sampleHeader = directMemoryService.getLong(sampleObject, 0L); objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } sampleHeader = directMemoryService.getLong(sampleObject, 0L); objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } synchronized (sampleObject) { sampleHeader = directMemoryService.getLong(sampleObject, 0L); } objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected long allocateStringFromOffHeap(String str) { long addressOfStr = JvmUtil.addressOf(str); char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString); int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length); int strSize = stringSize + valueArraySize + JvmUtil.getAddressSize(); // Extra memory for possible aligning long addressMod1 = currentAddress % JvmUtil.getAddressSize(); if (addressMod1 != 0) { currentAddress += (JvmUtil.getAddressSize() - addressMod1); } if (currentAddress + strSize > allocationEndAddress) { return 0; } // Copy string object content to allocated area directMemoryService.copyMemory(addressOfStr, currentAddress, strSize); long valueAddress = currentAddress + stringSize; long addressMod2 = valueAddress % JvmUtil.getAddressSize(); if (addressMod2 != 0) { valueAddress += (JvmUtil.getAddressSize() - addressMod2); } // Copy value array in allocated string to allocated char array directMemoryService.copyMemory( JvmUtil.toNativeAddress( directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)), valueAddress, valueArraySize); // Now, value array in allocated string points to allocated char array directMemoryService.putAddress( currentAddress + valueArrayOffsetInString, JvmUtil.toJvmAddress(valueAddress)); long allocatedStrAddress = currentAddress; currentAddress += strSize; return allocatedStrAddress; } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected long allocateStringFromOffHeap(String str) { long addressOfStr = directMemoryService.addressOf(str); char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString); int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length); int strSize = stringSize + valueArraySize; // + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning long addressMod1 = currentAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod1 != 0) { currentAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod1); } if (currentAddress + strSize > allocationEndAddress) { return 0; } // Copy string object content to allocated area directMemoryService.copyMemory(addressOfStr, currentAddress, strSize); long valueAddress = currentAddress + stringSize; long addressMod2 = valueAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod2 != 0) { valueAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod2); } // Copy value array in allocated string to allocated char array directMemoryService.copyMemory( JvmUtil.toNativeAddress( directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)), valueAddress, valueArraySize); // Now, value array in allocated string points to allocated char array directMemoryService.putAddress( currentAddress + valueArrayOffsetInString, JvmUtil.toJvmAddress(valueAddress)); long allocatedStrAddress = currentAddress; currentAddress += strSize; return allocatedStrAddress; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void objectRetrievedSuccessfullyFromLazyReferencedObjectOffHeapPool() { LazyReferencedObjectOffHeapPool<SampleOffHeapClass> objectPool = offHeapService.createOffHeapPool( new ObjectOffHeapPoolCreateParameterBuilder<SampleOffHeapClass>(). type(SampleOffHeapClass.class). objectCount(ELEMENT_COUNT). referenceType(ObjectPoolReferenceType.LAZY_REFERENCED). build()); for (int i = 0; i < ELEMENT_COUNT; i++) { SampleOffHeapClass obj = objectPool.get(); Assert.assertEquals(0, obj.getOrder()); obj.setOrder(i); Assert.assertEquals(i, obj.getOrder()); } objectPool.reset(); for (int i = 0; i < ELEMENT_COUNT; i++) { SampleOffHeapClass obj = objectPool.getAt(i); Assert.assertEquals(0, obj.getOrder()); obj.setOrder(i); Assert.assertEquals(i, obj.getOrder()); } } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void objectRetrievedSuccessfullyFromLazyReferencedObjectOffHeapPool() { LazyReferencedObjectOffHeapPool<SampleOffHeapClass> objectPool = offHeapService.createOffHeapPool( new ObjectOffHeapPoolCreateParameterBuilder<SampleOffHeapClass>(). type(SampleOffHeapClass.class). objectCount(ELEMENT_COUNT). referenceType(ObjectPoolReferenceType.LAZY_REFERENCED). build()); for (int i = 0; true; i++) { SampleOffHeapClass obj = objectPool.get(); if (obj == null) { break; } Assert.assertEquals(0, obj.getOrder()); obj.setOrder(i); obj.setSampleOffHeapAggregatedClass(new SampleOffHeapAggregatedClass()); Assert.assertEquals(i, obj.getOrder()); } objectPool.reset(); for (int i = 0; i < ELEMENT_COUNT; i++) { SampleOffHeapClass obj = objectPool.getAt(i); Assert.assertEquals(0, obj.getOrder()); obj.setOrder(i); Assert.assertEquals(i, obj.getOrder()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public A getArray() { checkAvailability(); return objectArray; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public A getArray() { checkAvailability(); return getObjectArray(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void init() { super.init(); objectsStartAddress = allocationStartAddress; // Allocated objects must start aligned as address size from start address of allocated address long addressMod = objectsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void init() { super.init(); long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void sizeRetrievedSuccessfully() { final int ENTRY_COUNT = Integer.SIZE - 1; OffHeapJudyHashMap<Integer, Person> map = new OffHeapJudyHashMap<Integer, Person>(Person.class); for (int i = 0; i < ENTRY_COUNT; i++) { map.put(i << i, randomOffHeapPerson(i, map.newElement())); Assert.assertEquals(i + 1, map.size()); } for (int i = 0; i < ENTRY_COUNT; i++) { map.remove(i << i); Assert.assertEquals(ENTRY_COUNT - (i + 1), map.size()); } } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void sizeRetrievedSuccessfully() { final int ENTRY_COUNT = Integer.SIZE - 1; OffHeapJudyHashMap<Integer, Person> map = new OffHeapJudyHashMap<Integer, Person>(Person.class); for (int i = 0; i < ENTRY_COUNT; i++) { map.put(i << i, randomizeOffHeapPerson(i, map.newElement())); Assert.assertEquals(i + 1, map.size()); } for (int i = 0; i < ENTRY_COUNT; i++) { map.remove(i << i); Assert.assertEquals(ENTRY_COUNT - (i + 1), map.size()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); this.currentIndex = 0; int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objStartAddress += (JvmUtil.getAddressSize() - addressMod); } // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, objectCount); // All index is object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress); } #location 31 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); this.currentIndex = 0; int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objectsStartAddress += (JvmUtil.getAddressSize() - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte( allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, objectCount); // All index is object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; sampleStr = new String(); sampleStrAddress = JvmUtil.addressOf(sampleStr); sampleCharArray = new char[0]; init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } } #location 22 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; segmentCount = allocationSize / STRING_SEGMENT_SIZE; long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE; if (segmentCountMod != 0) { segmentCount++; } inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; if (blockCountMod != 0) { inUseBlockCount++; fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1); } else { fullValueOfLastBlock = BLOCK_IS_FULL_VALUE; } inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleHeader = directMemoryService.getInt(new String(), 0L); init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected long allocateStringFromOffHeap(String str) { long addressOfStr = JvmUtil.addressOf(str); char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString); int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length); int strSize = stringSize + valueArraySize + JvmUtil.getAddressSize(); // Extra memory for possible aligning long addressMod1 = currentAddress % JvmUtil.getAddressSize(); if (addressMod1 != 0) { currentAddress += (JvmUtil.getAddressSize() - addressMod1); } if (currentAddress + strSize > allocationEndAddress) { return 0; } // Copy string object content to allocated area directMemoryService.copyMemory(addressOfStr, currentAddress, strSize); long valueAddress = currentAddress + stringSize; long addressMod2 = valueAddress % JvmUtil.getAddressSize(); if (addressMod2 != 0) { valueAddress += (JvmUtil.getAddressSize() - addressMod2); } // Copy value array in allocated string to allocated char array directMemoryService.copyMemory( JvmUtil.toNativeAddress( directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)), valueAddress, valueArraySize); // Now, value array in allocated string points to allocated char array directMemoryService.putAddress( currentAddress + valueArrayOffsetInString, JvmUtil.toJvmAddress(valueAddress)); long allocatedStrAddress = currentAddress; currentAddress += strSize; return allocatedStrAddress; } #location 35 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected long allocateStringFromOffHeap(String str) { long addressOfStr = directMemoryService.addressOf(str); char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString); int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length); int strSize = stringSize + valueArraySize; // + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning long addressMod1 = currentAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod1 != 0) { currentAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod1); } if (currentAddress + strSize > allocationEndAddress) { return 0; } // Copy string object content to allocated area directMemoryService.copyMemory(addressOfStr, currentAddress, strSize); long valueAddress = currentAddress + stringSize; long addressMod2 = valueAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod2 != 0) { valueAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod2); } // Copy value array in allocated string to allocated char array directMemoryService.copyMemory( JvmUtil.toNativeAddress( directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)), valueAddress, valueArraySize); // Now, value array in allocated string points to allocated char array directMemoryService.putAddress( currentAddress + valueArrayOffsetInString, JvmUtil.toJvmAddress(valueAddress)); long allocatedStrAddress = currentAddress; currentAddress += strSize; return allocatedStrAddress; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void packetSentRegardless(SocketFactory sf, ByteArrayOutputStream baos) { ApnsConnectionImpl connection = new ApnsConnectionImpl(sf, "localhost", 80); connection.DELAY_IN_MS = 0; connection.sendMessage(msg); Assert.assertArrayEquals(msg.marshall(), baos.toByteArray()); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code private void packetSentRegardless(SocketFactory sf, ByteArrayOutputStream baos) { ApnsConnectionImpl connection = new ApnsConnectionImpl(sf, "localhost", 80); connection.DELAY_IN_MS = 0; connection.sendMessage(msg); Assert.assertArrayEquals(msg.marshall(), baos.toByteArray()); connection.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private synchronized Socket socket() throws NetworkIOException { if (reconnectPolicy.shouldReconnect()) { Utilities.close(socket); socket = null; } if (socket == null || socket.isClosed()) { try { if (proxy == null) { socket = factory.createSocket(host, port); } else if (proxy.type() == Proxy.Type.HTTP) { TlsTunnelBuilder tunnelBuilder = new TlsTunnelBuilder(); socket = tunnelBuilder.build((SSLSocketFactory) factory, proxy, host, port); } else { boolean success = false; Socket proxySocket = null; try { proxySocket = new Socket(proxy); proxySocket.connect(new InetSocketAddress(host, port)); socket = ((SSLSocketFactory) factory).createSocket(proxySocket, host, port, false); success = true; } finally { if (!success) { Utilities.close(proxySocket); } } } if (errorDetection) { monitorSocket(socket); } reconnectPolicy.reconnected(); logger.debug("Made a new connection to APNS"); } catch (IOException e) { logger.error("Couldn't connect to APNS server", e); throw new NetworkIOException(e); } } return socket; } #location 30 #vulnerability type RESOURCE_LEAK
#fixed code private synchronized Socket socket() throws NetworkIOException { if (reconnectPolicy.shouldReconnect()) { Utilities.close(socket); socket = null; } if (socket == null || socket.isClosed()) { try { if (proxy == null) { socket = factory.createSocket(host, port); } else if (proxy.type() == Proxy.Type.HTTP) { TlsTunnelBuilder tunnelBuilder = new TlsTunnelBuilder(); socket = tunnelBuilder.build((SSLSocketFactory) factory, proxy, host, port); } else { boolean success = false; Socket proxySocket = null; try { proxySocket = new Socket(proxy); proxySocket.connect(new InetSocketAddress(host, port)); socket = ((SSLSocketFactory) factory).createSocket(proxySocket, host, port, false); success = true; } finally { if (!success) { Utilities.close(proxySocket); } } } socket.setSoTimeout(readTimeout); socket.setKeepAlive(true); if (errorDetection) { monitorSocket(socket); } reconnectPolicy.reconnected(); logger.debug("Made a new connection to APNS"); } catch (IOException e) { logger.error("Couldn't connect to APNS server", e); throw new NetworkIOException(e); } } return socket; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public ApnsServiceBuilder withCert(String fileName, String password) { try { return withCert(new FileInputStream(fileName), password); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public ApnsServiceBuilder withCert(String fileName, String password) { FileInputStream stream = null; try { stream = new FileInputStream(fileName); return withCert(stream, password); } catch (FileNotFoundException e) { throw new RuntimeException(e); } finally { Utilities.close(stream); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private synchronized Socket socket() throws NetworkIOException { if (reconnectPolicy.shouldReconnect()) { Utilities.close(socket); socket = null; } if (socket == null || socket.isClosed()) { try { if (proxy == null) { socket = factory.createSocket(host, port); } else if (proxy.type() == Proxy.Type.HTTP) { TlsTunnelBuilder tunnelBuilder = new TlsTunnelBuilder(); socket = tunnelBuilder.build((SSLSocketFactory) factory, proxy, host, port); } else { boolean success = false; Socket proxySocket = null; try { proxySocket = new Socket(proxy); proxySocket.connect(new InetSocketAddress(host, port)); socket = ((SSLSocketFactory) factory).createSocket(proxySocket, host, port, false); success = true; } finally { if (!success) { Utilities.close(proxySocket); } } } if (errorDetection) { monitorSocket(socket); } reconnectPolicy.reconnected(); logger.debug("Made a new connection to APNS"); } catch (IOException e) { logger.error("Couldn't connect to APNS server", e); throw new NetworkIOException(e); } } return socket; } #location 29 #vulnerability type RESOURCE_LEAK
#fixed code private synchronized Socket socket() throws NetworkIOException { if (reconnectPolicy.shouldReconnect()) { Utilities.close(socket); socket = null; } if (socket == null || socket.isClosed()) { try { if (proxy == null) { socket = factory.createSocket(host, port); } else if (proxy.type() == Proxy.Type.HTTP) { TlsTunnelBuilder tunnelBuilder = new TlsTunnelBuilder(); socket = tunnelBuilder.build((SSLSocketFactory) factory, proxy, host, port); } else { boolean success = false; Socket proxySocket = null; try { proxySocket = new Socket(proxy); proxySocket.connect(new InetSocketAddress(host, port)); socket = ((SSLSocketFactory) factory).createSocket(proxySocket, host, port, false); success = true; } finally { if (!success) { Utilities.close(proxySocket); } } } socket.setSoTimeout(readTimeout); socket.setKeepAlive(true); if (errorDetection) { monitorSocket(socket); } reconnectPolicy.reconnected(); logger.debug("Made a new connection to APNS"); } catch (IOException e) { logger.error("Couldn't connect to APNS server", e); throw new NetworkIOException(e); } } return socket; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void packetSentRegardless(SocketFactory sf, ByteArrayOutputStream baos) { ApnsConnection connection = new ApnsConnection(sf, "localhost", 80); connection.DELAY_IN_MS = 0; connection.sendMessage(msg); Assert.assertArrayEquals(msg.marshall(), baos.toByteArray()); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code private void packetSentRegardless(SocketFactory sf, ByteArrayOutputStream baos) { ApnsConnectionImpl connection = new ApnsConnectionImpl(sf, "localhost", 80); connection.DELAY_IN_MS = 0; connection.sendMessage(msg); Assert.assertArrayEquals(msg.marshall(), baos.toByteArray()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void parse(NulsByteBuffer byteBuffer) throws NulsException { this.setHeader(byteBuffer.readNulsData(new EventHeader())); // version = new NulsVersion(byteBuffer.readShort()); bestBlockHeight = byteBuffer.readVarInt(); bestBlockHash = new String(byteBuffer.readByLengthByte()); nulsVersion = new String(byteBuffer.readByLengthByte()); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected void parse(NulsByteBuffer byteBuffer) throws NulsException { this.setHeader(byteBuffer.readNulsData(new EventHeader())); // version = new NulsVersion(byteBuffer.readShort()); bestBlockHeight = byteBuffer.readVarInt(); bestBlockHash = byteBuffer.readString(); nulsVersion = byteBuffer.readString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void checkGenesisBlock() throws IOException { Block genesisBlock = NulsContext.getInstance().getGenesisBlock(); genesisBlock.verify(); Block localGenesisBlock = this.blockService.getGengsisBlock(); if (null == localGenesisBlock) { this.blockService.saveBlock(genesisBlock); return; } localGenesisBlock.verify(); System.out.println(genesisBlock.size()+"===="+localGenesisBlock.size()); String logicHash = genesisBlock.getHeader().getHash().getDigestHex(); System.out.println(logicHash); String localHash = localGenesisBlock.getHeader().getHash().getDigestHex(); System.out.println(localHash); if (!logicHash.equals(localHash)) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR); } } #location 16 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void checkGenesisBlock() throws IOException { Block genesisBlock = NulsContext.getInstance().getGenesisBlock(); genesisBlock.verify(); Block localGenesisBlock = this.blockService.getGengsisBlock(); if (null == localGenesisBlock) { this.blockService.saveBlock(genesisBlock); return; } localGenesisBlock.verify(); String logicHash = genesisBlock.getHeader().getHash().getDigestHex(); String localHash = localGenesisBlock.getHeader().getHash().getDigestHex(); if (!logicHash.equals(localHash)) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized PocMeetingRound resetCurrentMeetingRound() { Block currentBlock = NulsContext.getInstance().getBestBlock(); BlockRoundData currentRoundData = new BlockRoundData(currentBlock.getHeader().getExtend()); PocMeetingRound currentRound = ROUND_MAP.get(currentRoundData.getRoundIndex()); boolean needCalcRound = false; do { if (null == currentRound) { needCalcRound = true; break; } if (currentRound.getEndTime() < TimeService.currentTimeMillis()) { needCalcRound = true; break; } boolean thisIsLastBlockOfRound = currentRoundData.getPackingIndexOfRound() == currentRoundData.getConsensusMemberCount(); if (currentRound.getIndex() == currentRoundData.getRoundIndex() && !thisIsLastBlockOfRound) { needCalcRound = false; break; } if (currentRound.getIndex() == (currentRoundData.getRoundIndex() + 1) && thisIsLastBlockOfRound) { needCalcRound = false; break; } needCalcRound = true; } while (false); PocMeetingRound resultRound = null; if (needCalcRound) { if (null != ROUND_MAP.get(currentRoundData.getRoundIndex() + 1)) { resultRound = ROUND_MAP.get(currentRoundData.getRoundIndex() + 1); } else { resultRound = calcNextRound(currentBlock, currentRoundData); } } if (resultRound.getPreRound() == null) { resultRound.setPreRound(ROUND_MAP.get(currentRoundData.getRoundIndex() + 1)); } List<Account> accountList = accountService.getAccountList(); resultRound.calcLocalPacker(accountList); this.currentRound = resultRound; return resultRound; } #location 35 #vulnerability type NULL_DEREFERENCE
#fixed code public synchronized PocMeetingRound resetCurrentMeetingRound() { Block currentBlock = NulsContext.getInstance().getBestBlock(); BlockRoundData currentRoundData = new BlockRoundData(currentBlock.getHeader().getExtend()); PocMeetingRound currentRound = ROUND_MAP.get(currentRoundData.getRoundIndex()); boolean needCalcRound = false; do { if (null == currentRound) { needCalcRound = true; break; } if (currentRound.getEndTime() < TimeService.currentTimeMillis()) { needCalcRound = true; break; } boolean thisIsLastBlockOfRound = currentRoundData.getPackingIndexOfRound() == currentRoundData.getConsensusMemberCount(); if (currentRound.getIndex() == currentRoundData.getRoundIndex() && !thisIsLastBlockOfRound) { needCalcRound = false; break; } if (currentRound.getIndex() == (currentRoundData.getRoundIndex() + 1) && thisIsLastBlockOfRound) { needCalcRound = false; break; } needCalcRound = true; } while (false); PocMeetingRound resultRound = null; if (needCalcRound) { if (null != ROUND_MAP.get(currentRoundData.getRoundIndex() + 1)) { resultRound = ROUND_MAP.get(currentRoundData.getRoundIndex() + 1); } else { resultRound = calcNextRound(currentBlock, currentRoundData); } } if (resultRound.getPreRound() == null) { resultRound.setPreRound(ROUND_MAP.get(currentRoundData.getRoundIndex() + 1)); } List<Account> accountList = accountService.getAccountList(); resultRound.calcLocalPacker(accountList); this.currentRound = resultRound; ROUND_MAP.put(resultRound.getIndex(),currentRound); return resultRound; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Block getHighestBlock() { BlockHeaderChain chain = bifurcateProcessor.getApprovingChain(); if (null == chain) { return null; } HeaderDigest headerDigest = chain.getLastHd(); return this.getBlock(headerDigest.getHash()); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public Block getHighestBlock() { BlockHeaderChain chain = bifurcateProcessor.getApprovingChain(); if (null == chain) { return null; } HeaderDigest headerDigest = chain.getLastHd(); if(null==headerDigest){ return null; } return this.getBlock(headerDigest.getHash()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void init() { NulsContext.getServiceBean(AccountLedgerService.class).init(); //load local account list into cache } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void init() { //load local account list into cache }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public ValidateResult validate(BlockHeader header, List<Transaction> txs) { if (header.getHeight() == 0) { return ValidateResult.getSuccessResult(); } BlockRoundData roundData = new BlockRoundData(header.getExtend()); Block preBlock = getBlockService().getBlock(header.getPreHash().getDigestHex()); if (null == preBlock) { //When a block does not exist, it is temporarily validated. return ValidateResult.getSuccessResult(); } BlockRoundData preRoundData = new BlockRoundData(preBlock.getHeader().getExtend()); PocMeetingRound localPreRoundData = getRoundDataOrCalc(preBlock.getHeader(), preBlock.getHeader().getHeight(), preRoundData); PocMeetingRound localThisRoundData = null; if (localPreRoundData.getIndex() == roundData.getRoundIndex()) { localThisRoundData = localPreRoundData; } else { localThisRoundData = getRoundDataOrCalc(header, header.getHeight(), roundData); //Verify that the time of the two turns is correct. ValidateResult result = checkThisRound(localPreRoundData, localThisRoundData, roundData, header); if (result.isFailed()) { return result; } } if (roundData.getConsensusMemberCount() != localThisRoundData.getMemberCount()) { return ValidateResult.getFailedResult("The round data of the block is wrong!"); } if (roundData.getRoundIndex() == (localPreRoundData.getIndex() + 1) && roundData.getRoundStartTime() != localPreRoundData.getEndTime()) { return ValidateResult.getFailedResult("The round data of the block is wrong!"); } PocMeetingMember member = localThisRoundData.getMember(roundData.getPackingIndexOfRound()); if (null == member) { return ValidateResult.getFailedResult("Cannot find the packing member!"); } if (member.getIndexOfRound() != roundData.getPackingIndexOfRound() || !member.getPackingAddress().equals(header.getPackingAddress())) { ValidateResult vr = ValidateResult.getFailedResult("It's not the address's turn to pack the block!"); vr.setObject(header); vr.setLevel(SeverityLevelEnum.FLAGRANT_FOUL); return vr; } if (null == txs) { return ValidateResult.getSuccessResult(); } YellowPunishTransaction yellowPunishTx = null; for (Transaction tx : txs) { if (tx.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) { if (yellowPunishTx == null) { yellowPunishTx = (YellowPunishTransaction) tx; } else { return ValidateResult.getFailedResult("There are too many yellow punish transactions!"); } } } //when the blocks are continuous boolean isContinuous = preRoundData.getRoundIndex() == roundData.getRoundIndex() && preRoundData.getPackingIndexOfRound() == (roundData.getPackingIndexOfRound() - 1); isContinuous = isContinuous || (preRoundData.getRoundIndex() == (roundData.getRoundIndex() - 1) && preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount() && roundData.getPackingIndexOfRound() == 1); //Too long intervals will not be penalized. boolean longTimeAgo = preRoundData.getRoundIndex() < (roundData.getRoundIndex() - 1); if (longTimeAgo && yellowPunishTx == null) { return ValidateResult.getSuccessResult(); } if (isContinuous) { if (yellowPunishTx == null) { return ValidateResult.getSuccessResult(); } else { return ValidateResult.getFailedResult("the block shouldn't has any yellow punish tx!"); } } else { if (null == yellowPunishTx) { return ValidateResult.getFailedResult("It should be a yellow punish tx here!"); } if (yellowPunishTx.getTxData().getHeight() != header.getHeight()) { return ValidateResult.getFailedResult("The yellow punish tx's height is wrong!"); } int interval = 0; if (roundData.getRoundIndex() == preRoundData.getRoundIndex()) { interval = roundData.getPackingIndexOfRound() - preRoundData.getPackingIndexOfRound() - 1; } else if ((roundData.getRoundIndex() - 1) == preRoundData.getRoundIndex()) { interval = preRoundData.getConsensusMemberCount() - preRoundData.getPackingIndexOfRound() + roundData.getPackingIndexOfRound() - 1; } if (interval != yellowPunishTx.getTxData().getAddressList().size()) { return ValidateResult.getFailedResult("The count of YellowPunishTx is wrong,it should be " + interval); } else { long roundIndex = preRoundData.getRoundIndex(); long indexOfRound = preRoundData.getPackingIndexOfRound() + 1; List<String> addressList = new ArrayList<>(); while (true) { PocMeetingRound round = getRoundData(roundIndex); if (null == round) { break; } if (roundIndex == roundData.getRoundIndex() && roundData.getPackingIndexOfRound() <= indexOfRound) { break; } if (round.getMemberCount() < indexOfRound) { roundIndex++; indexOfRound = 1; continue; } PocMeetingMember meetingMember = round.getMember(interval); if (null == meetingMember) { return ValidateResult.getFailedResult("the round data has error!"); } addressList.add(meetingMember.getAgentAddress()); indexOfRound++; } if (addressList.size() != yellowPunishTx.getTxData().getAddressList().size()) { return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!address list size is wrong!"); } for (String address : addressList) { if (!yellowPunishTx.getTxData().getAddressList().contains(address)) { return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!It has wrong address"); } } } } return checkCoinBaseTx(header, txs, roundData, localThisRoundData); } #location 92 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public ValidateResult validate(BlockHeader header, List<Transaction> txs) { if (header.getHeight() == 0) { return ValidateResult.getSuccessResult(); } BlockRoundData roundData = new BlockRoundData(header.getExtend()); Block preBlock = getBlockService().getBlock(header.getPreHash().getDigestHex()); if (null == preBlock) { //When a block does not exist, it is temporarily validated. return ValidateResult.getSuccessResult(); } calc(preBlock); BlockRoundData preRoundData = new BlockRoundData(preBlock.getHeader().getExtend()); PocMeetingRound localThisRoundData = this.currentRound; PocMeetingRound localPreRoundData; if (preRoundData.getRoundIndex() == roundData.getRoundIndex()) { localPreRoundData = localThisRoundData; } else { localPreRoundData = localThisRoundData.getPreRound(); } if (roundData.getConsensusMemberCount() != localThisRoundData.getMemberCount()) { return ValidateResult.getFailedResult("The round data of the block is wrong!"); } if (roundData.getRoundIndex() == (localPreRoundData.getIndex() + 1) && roundData.getRoundStartTime() != localPreRoundData.getEndTime()) { return ValidateResult.getFailedResult("The round data of the block is wrong!"); } PocMeetingMember member = localThisRoundData.getMember(roundData.getPackingIndexOfRound()); if (null == member) { return ValidateResult.getFailedResult("Cannot find the packing member!"); } if (member.getIndexOfRound() != roundData.getPackingIndexOfRound() || !member.getPackingAddress().equals(header.getPackingAddress())) { ValidateResult vr = ValidateResult.getFailedResult("It's not the address's turn to pack the block!"); vr.setObject(header); vr.setLevel(SeverityLevelEnum.FLAGRANT_FOUL); return vr; } if (null == txs) { return ValidateResult.getSuccessResult(); } YellowPunishTransaction yellowPunishTx = null; for (Transaction tx : txs) { if (tx.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) { if (yellowPunishTx == null) { yellowPunishTx = (YellowPunishTransaction) tx; } else { return ValidateResult.getFailedResult("There are too many yellow punish transactions!"); } } } //when the blocks are continuous boolean isContinuous = preRoundData.getRoundIndex() == roundData.getRoundIndex() && preRoundData.getPackingIndexOfRound() == (roundData.getPackingIndexOfRound() - 1); isContinuous = isContinuous || (preRoundData.getRoundIndex() == (roundData.getRoundIndex() - 1) && preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount() && roundData.getPackingIndexOfRound() == 1); //Too long intervals will not be penalized. boolean longTimeAgo = preRoundData.getRoundIndex() < (roundData.getRoundIndex() - 1); if (longTimeAgo && yellowPunishTx == null) { return ValidateResult.getSuccessResult(); } if (isContinuous) { if (yellowPunishTx == null) { return ValidateResult.getSuccessResult(); } else { return ValidateResult.getFailedResult("the block shouldn't has any yellow punish tx!"); } } else { if (null == yellowPunishTx) { return ValidateResult.getFailedResult("It should be a yellow punish tx here!"); } if (yellowPunishTx.getTxData().getHeight() != header.getHeight()) { return ValidateResult.getFailedResult("The yellow punish tx's height is wrong!"); } int interval = 0; if (roundData.getRoundIndex() == preRoundData.getRoundIndex()) { interval = roundData.getPackingIndexOfRound() - preRoundData.getPackingIndexOfRound() - 1; } else if ((roundData.getRoundIndex() - 1) == preRoundData.getRoundIndex()) { interval = preRoundData.getConsensusMemberCount() - preRoundData.getPackingIndexOfRound() + roundData.getPackingIndexOfRound() - 1; } if (interval != yellowPunishTx.getTxData().getAddressList().size()) { return ValidateResult.getFailedResult("The count of YellowPunishTx is wrong,it should be " + interval); } else { long roundIndex = preRoundData.getRoundIndex(); long indexOfRound = preRoundData.getPackingIndexOfRound() + 1; List<String> addressList = new ArrayList<>(); while (true) { PocMeetingRound round = getRoundData(roundIndex); if (null == round) { break; } if (roundIndex == roundData.getRoundIndex() && roundData.getPackingIndexOfRound() <= indexOfRound) { break; } if (round.getMemberCount() < indexOfRound) { roundIndex++; indexOfRound = 1; continue; } PocMeetingMember meetingMember = round.getMember(interval); if (null == meetingMember) { return ValidateResult.getFailedResult("the round data has error!"); } addressList.add(meetingMember.getAgentAddress()); indexOfRound++; } if (addressList.size() != yellowPunishTx.getTxData().getAddressList().size()) { return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!address list size is wrong!"); } for (String address : addressList) { boolean contains = false; for (Address addressObj : yellowPunishTx.getTxData().getAddressList()) { if (addressObj.getBase58().equals(address)) { contains = true; break; } } if (!contains) { return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!It has wrong address"); } } } } return checkCoinBaseTx(header, txs, roundData, localThisRoundData); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void init() { accountService = NulsContext.getInstance().getService(AccountService.class); //default local account List<Account> list = this.accountService.getLocalAccountList(); if (null != list && !list.isEmpty()) { Locla_acount_id = list.get(0).getId(); } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public void init() { accountService = AccountServiceImpl.getInstance(); //default local account List<Account> list = this.accountService.getLocalAccountList(); if (null != list && !list.isEmpty()) { Locla_acount_id = list.get(0).getId(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void destroy() { System.out.println("---------peer destory:" + this.getIp()); lock.lock(); try { this.status = Peer.CLOSE; if (this.writeTarget != null) { this.writeTarget.closeConnection(); this.writeTarget = null; } } finally { lock.unlock(); } //todo check failCount and save or remove from database //this.failCount ++; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void destroy() { lock.lock(); try { this.status = Peer.CLOSE; if (this.writeTarget != null) { this.writeTarget.closeConnection(); this.writeTarget = null; } } finally { lock.unlock(); } //todo check failCount and save or remove from database //this.failCount ++; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void rollbackHeaderDigest(String hash) { for (int i = 0; i < headerDigestList.size(); i++) { HeaderDigest headerDigest = headerDigestList.get(i); if (headerDigest.getHash().equals(hash)) { headerDigestList.remove(headerDigest); for (int x = i + 1; x < headerDigestList.size(); x++) { headerDigestList.remove(x); } this.lastHd = null; break; } } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void rollbackHeaderDigest(String hash) { for (int i = 0; i < headerDigestList.size(); i++) { HeaderDigest headerDigest = headerDigestList.get(i); if (headerDigest.getHash().equals(hash)) { headerDigestList.remove(headerDigest); for (int x = i + 1; x < headerDigestList.size(); x++) { headerDigestList.remove(x); } break; } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void parse(NulsByteBuffer buffer) throws NulsException { magicNumber = (int) buffer.readVarInt(); severPort = (int) buffer.readVarInt(); port = severPort; ip = new String(buffer.readByLengthByte()); this.groupSet = ConcurrentHashMap.newKeySet(); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void parse(NulsByteBuffer buffer) throws NulsException { magicNumber = buffer.readUint32(); severPort = buffer.readUint16(); port = severPort; ip = buffer.readString(); this.groupSet = ConcurrentHashMap.newKeySet(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void reSendLocalTx() throws NulsException { List<Transaction> txList = getLedgerService().getWaitingTxList(); List<Transaction> helpList = new ArrayList<>(); for (Transaction tx : txList) { if (TimeService.currentTimeMillis() - tx.getTime() < DateUtil.MINUTE_TIME * 2) { continue; } ValidateResult result = ledgerService.verifyTx(tx, helpList); if (result.isFailed()) { getLocalDataService().deleteUnCofirmTx(tx.getHash().getDigestHex()); continue; } Transaction transaction = getLedgerService().getTx(tx.getHash()); if (transaction != null) { getLocalDataService().deleteUnCofirmTx(tx.getHash().getDigestHex()); continue; } helpList.add(tx); TransactionEvent event = new TransactionEvent(); event.setEventBody(tx); getEventBroadcaster().publishToLocal(event); } } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code private void reSendLocalTx() throws NulsException { List<Transaction> txList = getLedgerCacheService().getUnconfirmTxList(); List<Transaction> helpList = new ArrayList<>(); for (Transaction tx : txList) { if (TimeService.currentTimeMillis() - tx.getTime() < DateUtil.MINUTE_TIME * 2) { continue; } ValidateResult result = getLedgerService().verifyTx(tx, helpList); if (result.isFailed()) { getLocalDataService().deleteUnCofirmTx(tx.getHash().getDigestHex()); ledgerCacheService.removeLocalTx(tx.getHash().getDigestHex()); continue; } Transaction transaction = getLedgerService().getTx(tx.getHash()); if (transaction != null) { getLocalDataService().deleteUnCofirmTx(tx.getHash().getDigestHex()); ledgerCacheService.removeLocalTx(tx.getHash().getDigestHex()); continue; } helpList.add(tx); TransactionEvent event = new TransactionEvent(); event.setEventBody(tx); getEventBroadcaster().publishToLocal(event); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void start() { consensusManager.init(); NulsContext.getInstance().setBestBlock(NulsContext.getServiceBean(BlockService.class).getLocalBestBlock()); this.registerHandlers(); this.consensusManager.startMaintenanceWork(); consensusManager.joinConsensusMeeting(); consensusManager.startPersistenceWork(); Log.info("the POC consensus module is started!"); TaskManager.createAndRunThread(this.getModuleId(),"block-cache-check",new BlockCacheCheckThread()); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void start() { consensusManager.init(); this.registerHandlers(); this.consensusManager.startMaintenanceWork(); consensusManager.joinConsensusMeeting(); consensusManager.startPersistenceWork(); Log.info("the POC consensus module is started!"); TaskManager.createAndRunThread(this.getModuleId(),"block-cache-check",new BlockCacheCheckThread()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Block doPacking(PocMeetingMember self, PocMeetingRound round) throws NulsException, IOException { Block bestBlock = this.blockService.getBestBlock(); List<Transaction> allTxList = txCacheManager.getTxList(); allTxList.sort(TxTimeComparator.getInstance()); BlockData bd = new BlockData(); bd.setHeight(bestBlock.getHeader().getHeight() + 1); bd.setPreHash(bestBlock.getHeader().getHash()); BlockRoundData roundData = new BlockRoundData(); roundData.setRoundIndex(round.getIndex()); roundData.setConsensusMemberCount(round.getMemberCount()); roundData.setPackingIndexOfRound(self.getPackingIndexOfRound()); roundData.setRoundStartTime(round.getStartTime()); StringBuilder str = new StringBuilder(); str.append(self.getPackingAddress()); str.append(" ,order:" + self.getPackingIndexOfRound()); str.append(",packTime:" + new Date(self.getPackEndTime())); str.append("\n"); BlockLog.debug("pack round:" + str); bd.setRoundData(roundData); List<Integer> outTxList = new ArrayList<>(); List<Transaction> packingTxList = new ArrayList<>(); List<NulsDigestData> outHashList = new ArrayList<>(); long totalSize = 0L; for (int i = 0; i < allTxList.size(); i++) { if ((self.getPackEndTime() - TimeService.currentTimeMillis()) <= 500L) { break; } Transaction tx = allTxList.get(i); tx.setBlockHeight(bd.getHeight()); if ((totalSize + tx.size()) >= PocConsensusConstant.MAX_BLOCK_SIZE) { break; } outHashList.add(tx.getHash()); ValidateResult result = tx.verify(); if (result.isFailed()) { Log.error(result.getMessage()); outTxList.add(i); continue; } try { ledgerService.approvalTx(tx); } catch (Exception e) { Log.error(e); outTxList.add(i); continue; } packingTxList.add(tx); totalSize += tx.size(); confirmingTxCacheManager.putTx(tx); } txCacheManager.removeTx(outHashList); if (totalSize < PocConsensusConstant.MAX_BLOCK_SIZE) { addOrphanTx(packingTxList, totalSize, self,bd.getHeight()); } addConsensusTx(bestBlock, packingTxList, self, round); bd.setTxList(packingTxList); Log.info("txCount:" + packingTxList.size()); Block newBlock = ConsensusTool.createBlock(bd, round.getLocalPacker()); System.out.printf("========height:" + newBlock.getHeader().getHeight() + ",time:" + DateUtil.convertDate(new Date(newBlock.getHeader().getTime())) + ",packEndTime:" + DateUtil.convertDate(new Date(self.getPackEndTime()))); ValidateResult result = newBlock.verify(); if (result.isFailed()) { Log.warn("packing block error:" + result.getMessage()); for (Transaction tx : newBlock.getTxs()) { ledgerService.rollbackTx(tx); } return null; } return newBlock; } #location 63 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code private Block doPacking(PocMeetingMember self, PocMeetingRound round) throws NulsException, IOException { Block bestBlock = this.blockService.getBestBlock(); List<Transaction> allTxList = txCacheManager.getTxList(); allTxList.sort(TxTimeComparator.getInstance()); BlockData bd = new BlockData(); bd.setHeight(bestBlock.getHeader().getHeight() + 1); bd.setPreHash(bestBlock.getHeader().getHash()); BlockRoundData roundData = new BlockRoundData(); roundData.setRoundIndex(round.getIndex()); roundData.setConsensusMemberCount(round.getMemberCount()); roundData.setPackingIndexOfRound(self.getPackingIndexOfRound()); roundData.setRoundStartTime(round.getStartTime()); bd.setRoundData(roundData); List<Integer> outTxList = new ArrayList<>(); List<Transaction> packingTxList = new ArrayList<>(); List<NulsDigestData> outHashList = new ArrayList<>(); long totalSize = 0L; for (int i = 0; i < allTxList.size(); i++) { if ((self.getPackEndTime() - TimeService.currentTimeMillis()) <= 500L) { break; } Transaction tx = allTxList.get(i); tx.setBlockHeight(bd.getHeight()); if ((totalSize + tx.size()) >= PocConsensusConstant.MAX_BLOCK_SIZE) { break; } outHashList.add(tx.getHash()); ValidateResult result = tx.verify(); if (result.isFailed()) { Log.error(result.getMessage()); outTxList.add(i); BlockLog.info("discard tx:" + tx.getHash()); continue; } try { ledgerService.approvalTx(tx); } catch (Exception e) { Log.error(e); outTxList.add(i); BlockLog.info("discard tx:" + tx.getHash()); continue; } packingTxList.add(tx); totalSize += tx.size(); confirmingTxCacheManager.putTx(tx); } txCacheManager.removeTx(outHashList); if (totalSize < PocConsensusConstant.MAX_BLOCK_SIZE) { addOrphanTx(packingTxList, totalSize, self, bd.getHeight()); } addConsensusTx(bestBlock, packingTxList, self, round); bd.setTxList(packingTxList); Block newBlock = ConsensusTool.createBlock(bd, round.getLocalPacker()); ValidateResult result = newBlock.verify(); if (result.isFailed()) { BlockLog.warn("packing block error:" + result.getMessage()); for (Transaction tx : newBlock.getTxs()) { ledgerService.rollbackTx(tx); } return null; } return newBlock; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean createQueue(String queueName, long maxSize, int latelySecond) { try { InchainFQueue queue = new InchainFQueue(queueName, maxSize); QueueManager.initQueue(queueName, queue, latelySecond); return true; } catch (Exception e) { Log.error("", e); return false; } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public boolean createQueue(String queueName, long maxSize, int latelySecond) { try { NulsFQueue queue = new NulsFQueue(queueName, maxSize); QueueManager.initQueue(queueName, queue, latelySecond); return true; } catch (Exception e) { Log.error("", e); return false; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean downloadedBlock(String nodeId, Block block) { try { NodeDownloadingStatus status = nodeStatusMap.get(nodeId); if (null == status) { return false; } if (!status.containsHeight(block.getHeader().getHeight())) { return false; } ValidateResult result1 = block.verify(); if (result1.isFailed() && result1.getErrorCode() != ErrorCode.ORPHAN_TX && result1.getErrorCode() != ErrorCode.ORPHAN_BLOCK) { Log.info("recieve a block wrong!:" + nodeId + ",blockHash:" + block.getHeader().getHash()); this.nodeIdList.remove(nodeId); if (nodeIdList.isEmpty()) { working = false; } return true; } blockMap.put(block.getHeader().getHeight(), block); status.downloaded(block.getHeader().getHeight()); status.setUpdateTime(TimeService.currentTimeMillis()); if (status.finished()) { this.queueService.offer(queueId, nodeId); } } catch (Exception e) { Log.error(e); } return true; } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean downloadedBlock(String nodeId, Block block) { if(!this.working){ return false; } try { NodeDownloadingStatus status = nodeStatusMap.get(nodeId); if (null == status) { return false; } if (!status.containsHeight(block.getHeader().getHeight())) { return false; } ValidateResult result1 = block.verify(); if (result1.isFailed() && result1.getErrorCode() != ErrorCode.ORPHAN_TX && result1.getErrorCode() != ErrorCode.ORPHAN_BLOCK) { Log.info("recieve a block wrong!:" + nodeId + ",blockHash:" + block.getHeader().getHash()); this.nodeIdList.remove(nodeId); if (nodeIdList.isEmpty()) { working = false; } return true; } blockMap.put(block.getHeader().getHeight(), block); status.downloaded(block.getHeader().getHeight()); status.setUpdateTime(TimeService.currentTimeMillis()); if (status.finished()) { this.queueService.offer(queueId, nodeId); } } catch (Exception e) { Log.error(e); } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean canPersistence() { return bifurcateProcessor.getLongestChain().size()> PocConsensusConstant.CONFIRM_BLOCK_COUNT; } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean canPersistence() { return null != bifurcateProcessor.getLongestChain() && bifurcateProcessor.getLongestChain().size() > PocConsensusConstant.CONFIRM_BLOCK_COUNT; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void getMemoryTxs() throws Exception { assertNotNull(service); Transaction tx = new TestTransaction(); tx.setTime(0l); assertEquals(tx.getHash().getDigestHex(), "08001220d194faf5b314f54c3a299ca9ea086f3f8856c75dc44a1e0c43bcc4d80b47909c"); Result result = service.newTx(tx); assertNotNull(result); assertTrue(result.isSuccess()); assertFalse(result.isFailed()); List<Transaction> memoryTxs = service.getMemoryTxs(); assertNotNull(memoryTxs); assertEquals(1, memoryTxs.size()); tx = memoryTxs.get(0); assertNotNull(tx); assertEquals(tx.getHash().getDigestHex(), "08001220d194faf5b314f54c3a299ca9ea086f3f8856c75dc44a1e0c43bcc4d80b47909c"); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void getMemoryTxs() throws Exception { assertNotNull(service); Transaction tx = new TestTransaction(); tx.setTime(0l); assertEquals(tx.getHash().getDigestHex(), "0020c7f397ae78f2c1d12b3edc916e8112bcac576a98444c4c26034c207c9a7ad281"); Result result = service.newTx(tx); assertNotNull(result); assertTrue(result.isSuccess()); assertFalse(result.isFailed()); List<Transaction> memoryTxs = service.getMemoryTxs(); assertNotNull(memoryTxs); assertEquals(1, memoryTxs.size()); tx = memoryTxs.get(0); assertNotNull(tx); assertEquals(tx.getHash().getDigestHex(), "0020c7f397ae78f2c1d12b3edc916e8112bcac576a98444c4c26034c207c9a7ad281"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { SocketChannel channel = (SocketChannel) ctx.channel(); String nodeId = IpUtil.getNodeId(channel.remoteAddress()); Log.debug(" ---------------------- server channelInactive ------------------------- " + nodeId); String channelId = ctx.channel().id().asLongText(); NioChannelMap.remove(channelId); Node node = getNetworkService().getNode(nodeId); if (node != null) { if (channelId.equals(node.getChannelId())) { // System.out.println("------------ sever channelInactive remove node-------------" + node.getId()); getNetworkService().removeNode(nodeId); } else { Log.debug("--------------channel id different----------------------"); Log.debug(node.getChannelId()); Log.debug(channelId); } } } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { SocketChannel channel = (SocketChannel) ctx.channel(); String nodeId = IpUtil.getNodeId(channel.remoteAddress()); Log.debug(" ---------------------- server channelInactive ------------------------- " + nodeId); String channelId = ctx.channel().id().asLongText(); NioChannelMap.remove(channelId); Node node = networkService.getNode(nodeId); if (node != null) { if (channelId.equals(node.getChannelId())) { // System.out.println("------------ sever channelInactive remove node-------------" + node.getId()); networkService.removeNode(nodeId); } else { Log.info("--------------server channel id different----------------------"); Log.info("--------node:" + node.getId() + ",type:" + node.getType()); Log.info(node.getChannelId()); Log.info(channelId); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void parse(NulsByteBuffer byteBuffer) throws NulsException { alias = new String(byteBuffer.readByLengthByte()); address = new Address(new String(byteBuffer.readByLengthByte())); encryptedPriKey = byteBuffer.readByLengthByte(); pubKey = byteBuffer.readByLengthByte(); status = (int)(byteBuffer.readVarInt()); extend = byteBuffer.readByLengthByte(); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected void parse(NulsByteBuffer byteBuffer) throws NulsException { address = Address.fromHashs(byteBuffer.readByLengthByte()); alias = new String(byteBuffer.readByLengthByte()); encryptedPriKey = byteBuffer.readByLengthByte(); pubKey = byteBuffer.readByLengthByte(); status = (int) (byteBuffer.readByte()); extend = byteBuffer.readByLengthByte(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @DbSession public void onRollback(StopAgentTransaction tx) { Transaction joinTx = ledgerService.getTx(tx.getTxData()); if (joinTx.getType() == TransactionConstant.TX_TYPE_REGISTER_AGENT) { RegisterAgentTransaction raTx = (RegisterAgentTransaction) joinTx; Consensus<Agent> ca = raTx.getTxData(); ca.getExtend().setBlockHeight(raTx.getBlockHeight()); ca.getExtend().setStatus(ConsensusStatusEnum.WAITING.getCode()); AgentPo agentPo = ConsensusTool.agentToPojo(ca); agentPo.setBlockHeight(joinTx.getBlockHeight()); agentPo.setDelHeight(0L); this.agentDataService.updateSelective(agentPo); // this.ledgerService.unlockTxRollback(tx.getTxData().getDigestHex()); UpdateDepositByAgentIdParam dpo = new UpdateDepositByAgentIdParam(); dpo.setAgentId(ca.getHexHash()); dpo.setOldDelHeight(joinTx.getBlockHeight()); dpo.setNewDelHeight(0L); this.depositDataService.updateSelectiveByAgentHash(dpo); //cache deposit Map<String, Object> params = new HashMap<>(); params.put("agentHash", raTx.getTxData().getHexHash()); List<DepositPo> polist = this.depositDataService.getList(params); if (null != polist) { for (DepositPo po : polist) { Consensus<Deposit> cd = ConsensusTool.fromPojo(po); this.ledgerService.unlockTxRollback(po.getTxHash()); } } //todo CancelConsensusNotice notice = new CancelConsensusNotice(); // notice.setEventBody(tx); // NulsContext.getServiceBean(EventBroadcaster.class).publishToLocal(notice); Consensus<Agent> agent = manager.getAgentById(ca.getHexHash()); agent.setDelHeight(0L); manager.putAgent(agent); List<Consensus<Deposit>> depositList = manager.getAllDepositList(); for(Consensus<Deposit> depositConsensus:depositList){ if(!depositConsensus.getExtend().getAgentHash().equals(agent.getHexHash())){ continue; } if(depositConsensus.getExtend().getBlockHeight()>joinTx.getBlockHeight()){ continue; } if(depositConsensus.getDelHeight()<tx.getBlockHeight()){ continue; } depositConsensus.setDelHeight(0L); manager.putDeposit(depositConsensus); } return; } PocJoinConsensusTransaction pjcTx = (PocJoinConsensusTransaction) joinTx; Consensus<Deposit> cd = pjcTx.getTxData(); cd.getExtend().setStatus(ConsensusStatusEnum.IN.getCode()); DepositPo dpo = new DepositPo(); dpo.setId(cd.getHexHash()); dpo.setDelHeight(0L); this.depositDataService.updateSelective(dpo); StopConsensusNotice notice = new StopConsensusNotice(); notice.setEventBody(tx); NulsContext.getServiceBean(EventBroadcaster.class).publishToLocal(notice); this.ledgerService.unlockTxRollback(tx.getTxData().getDigestHex()); Consensus<Deposit> depositConsensus = manager.getDepositById(cd.getHexHash()); depositConsensus.setDelHeight(0L); manager.putDeposit(depositConsensus); } #location 67 #vulnerability type NULL_DEREFERENCE
#fixed code @Override @DbSession public void onRollback(StopAgentTransaction tx) { Transaction joinTx = ledgerService.getTx(tx.getTxData()); RegisterAgentTransaction raTx = (RegisterAgentTransaction) joinTx; Consensus<Agent> ca = raTx.getTxData(); ca.getExtend().setBlockHeight(raTx.getBlockHeight()); ca.getExtend().setStatus(ConsensusStatusEnum.WAITING.getCode()); AgentPo agentPo = ConsensusTool.agentToPojo(ca); agentPo.setBlockHeight(joinTx.getBlockHeight()); agentPo.setDelHeight(0L); this.agentDataService.updateSelective(agentPo); // this.ledgerService.unlockTxRollback(tx.getTxData().getDigestHex()); UpdateDepositByAgentIdParam dpo = new UpdateDepositByAgentIdParam(); dpo.setAgentId(ca.getHexHash()); dpo.setOldDelHeight(joinTx.getBlockHeight()); dpo.setNewDelHeight(0L); this.depositDataService.updateSelectiveByAgentHash(dpo); //cache deposit Map<String, Object> params = new HashMap<>(); params.put("agentHash", raTx.getTxData().getHexHash()); List<DepositPo> polist = this.depositDataService.getList(params); if (null != polist) { for (DepositPo po : polist) { Consensus<Deposit> cd = ConsensusTool.fromPojo(po); this.ledgerService.unlockTxRollback(po.getTxHash()); } } //todo CancelConsensusNotice notice = new CancelConsensusNotice(); // notice.setEventBody(tx); // NulsContext.getServiceBean(EventBroadcaster.class).publishToLocal(notice); Consensus<Agent> agent = manager.getAgentById(ca.getHexHash()); agent.setDelHeight(0L); manager.putAgent(agent); List<Consensus<Deposit>> depositList = manager.getAllDepositList(); for (Consensus<Deposit> depositConsensus : depositList) { if (!depositConsensus.getExtend().getAgentHash().equals(agent.getHexHash())) { continue; } if (depositConsensus.getExtend().getBlockHeight() > joinTx.getBlockHeight()) { continue; } if (depositConsensus.getDelHeight() < tx.getBlockHeight()) { continue; } depositConsensus.setDelHeight(0L); manager.putDeposit(depositConsensus); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Result exportAccount(String address, String password) { Account account = null; if (!StringUtils.isBlank(address)) { account = accountCacheService.getAccountByAddress(address); if (account == null) { return Result.getFailed(ErrorCode.DATA_NOT_FOUND); } } if (!account.decrypt(password)) { return Result.getFailed(ErrorCode.PASSWORD_IS_WRONG); } Result result = backUpFile(""); if (!result.isSuccess()) { return result; } return exportAccount(account, (File) result.getObject()); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Result exportAccount(String address, String password) { Account account = null; if (!StringUtils.isBlank(address)) { account = accountCacheService.getAccountByAddress(address); if (account == null) { return Result.getFailed(ErrorCode.DATA_NOT_FOUND); } if (account.isEncrypted()) { if (!StringUtils.validPassword(password) || !account.decrypt(password)) { return Result.getFailed(ErrorCode.PASSWORD_IS_WRONG); } } } Result result = backUpFile(""); if (!result.isSuccess()) { return result; } return exportAccount(account, (File) result.getObject()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { SocketChannel channel = (SocketChannel) ctx.channel(); String nodeId = IpUtil.getNodeId(channel.remoteAddress()); Log.debug("---------------------- server channelRegistered ------------------------- " + nodeId); String remoteIP = channel.remoteAddress().getHostString(); Map<String, Node> nodeMap = null; //getNetworkService().getNodes(); for (Node node : nodeMap.values()) { if (node.getIp().equals(remoteIP)) { if (node.getType() == Node.OUT) { String localIP = InetAddress.getLocalHost().getHostAddress(); boolean isLocalServer = IpUtil.judgeIsLocalServer(localIP, remoteIP); if (!isLocalServer) { ctx.channel().close(); return; } else { // System.out.println("----------------sever client register each other remove node-----------------" + node.getId()); getNetworkService().removeNode(node.getId()); } } } } // if has a node with same ip, and it's a out node, close this channel // if More than 10 in nodes of the same IP, close this channel int count = 0; for (Node n : nodeMap.values()) { if (n.getIp().equals(remoteIP)) { count++; if (count >= NetworkConstant.SAME_IP_MAX_COUNT) { ctx.channel().close(); return; } } } } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { SocketChannel channel = (SocketChannel) ctx.channel(); String nodeId = IpUtil.getNodeId(channel.remoteAddress()); Log.debug("---------------------- server channelRegistered ------------------------- " + nodeId); String remoteIP = channel.remoteAddress().getHostString(); Map<String, Node> nodeMap = networkService.getNodes(); //getNetworkService().getNodes(); for (Node node : nodeMap.values()) { if (node.getIp().equals(remoteIP)) { if (node.getType() == Node.OUT) { String localIP = InetAddress.getLocalHost().getHostAddress(); boolean isLocalServer = IpUtil.judgeIsLocalServer(localIP, remoteIP); if (!isLocalServer) { ctx.channel().close(); return; } else { // System.out.println("----------------sever client register each other remove node-----------------" + node.getId()); getNetworkService().removeNode(node.getId()); } } } } // if has a node with same ip, and it's a out node, close this channel // if More than 10 in nodes of the same IP, close this channel int count = 0; for (Node n : nodeMap.values()) { if (n.getIp().equals(remoteIP)) { count++; if (count >= NetworkConstant.SAME_IP_MAX_COUNT) { ctx.channel().close(); return; } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onEvent(BlockEvent event, String fromId) { Block block = event.getEventBody(); if (null == block) { Log.warn("recieved a null blockEvent form " + fromId); return; } //BlockLog.debug("download("+fromId+") block height:" + block.getHeader().getHeight() + ", preHash:" + block.getHeader().getPreHash() + " , hash:" + block.getHeader().getHash() + ", address:" + block.getHeader().getPackingAddress()); // if (BlockBatchDownloadUtils.getInstance().downloadedBlock(fromId, block)) { // return; // } //blockCacheManager.addBlock(block, true, fromId); for (Transaction tx : block.getTxs()) { Transaction cachedTx = ConfirmingTxCacheManager.getInstance().getTx(tx.getHash()); if (null == cachedTx) { cachedTx = ReceivedTxCacheManager.getInstance().getTx(tx.getHash()); } if (null == cachedTx) { cachedTx = OrphanTxCacheManager.getInstance().getTx(tx.getHash()); } if (cachedTx != null && cachedTx.getStatus() != tx.getStatus()) { tx.setStatus(cachedTx.getStatus()); if(!(tx instanceof AbstractCoinTransaction)){ continue; } AbstractCoinTransaction coinTx = (AbstractCoinTransaction) tx; AbstractCoinTransaction cachedCoinTx = (AbstractCoinTransaction) cachedTx; coinTx.setCoinData(cachedCoinTx.getCoinData()); // Log.error("the transaction status is wrong!"); } } DownloadCacheHandler.receiveBlock(block); } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void onEvent(BlockEvent event, String fromId) { Block block = event.getEventBody(); if (null == block) { Log.warn("recieved a null blockEvent form " + fromId); return; } for (Transaction tx : block.getTxs()) { Transaction cachedTx = txCacheManager.getTx(tx.getHash()); if (cachedTx != null && cachedTx.getStatus() != tx.getStatus()) { tx.setStatus(cachedTx.getStatus()); if (!(tx instanceof AbstractCoinTransaction)) { continue; } AbstractCoinTransaction coinTx = (AbstractCoinTransaction) tx; AbstractCoinTransaction cachedCoinTx = (AbstractCoinTransaction) cachedTx; coinTx.setCoinData(cachedCoinTx.getCoinData()); // Log.error("the transaction status is wrong!"); } } DownloadCacheHandler.receiveBlock(block); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean containsKey(String cacheTitle, K key) { boolean result = this.cacheManager.getCache(cacheTitle).containsKey(key); return result; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean containsKey(String cacheTitle, K key) { Cache cache = this.cacheManager.getCache(cacheTitle); if (cache == null) { return false; } boolean result = cache.containsKey(key); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void start() { List<Node> nodes = discoverHandler.getLocalNodes(network.maxOutCount()); if (nodes == null && nodes.isEmpty()) { nodes = getSeedNodes(); } for (Node node : nodes) { node.setType(Node.OUT); node.setStatus(Node.WAIT); addNodeToGroup(NetworkConstant.NETWORK_NODE_OUT_GROUP, node); } running = true; TaskManager.createAndRunThread(NulsConstant.MODULE_ID_NETWORK, "NetworkNodeManager", this); discoverHandler.start(); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public void start() { List<Node> nodes = discoverHandler.getLocalNodes(network.maxOutCount()); if (nodes == null || nodes.isEmpty()) { nodes = getSeedNodes(); } for (Node node : nodes) { node.setType(Node.OUT); node.setStatus(Node.WAIT); addNodeToGroup(NetworkConstant.NETWORK_NODE_OUT_GROUP, node); } running = true; TaskManager.createAndRunThread(NulsConstant.MODULE_ID_NETWORK, "NetworkNodeManager", this); discoverHandler.start(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized void syncBlock() { this.status = MaintenanceStatus.DOWNLOADING; BestCorrectBlock bestCorrectBlock = checkLocalBestCorrentBlock(); boolean doit = false; long startHeight = 1; do { if (null == bestCorrectBlock.getLocalBestBlock() && bestCorrectBlock.getNetBestBlockInfo() == null) { doit = true; BlockInfo blockInfo = BEST_HEIGHT_FROM_NET.request(-1); bestCorrectBlock.setNetBestBlockInfo(blockInfo); break; } startHeight = bestCorrectBlock.getLocalBestBlock().getHeader().getHeight() + 1; long interval = TimeService.currentTimeMillis() - bestCorrectBlock.getLocalBestBlock().getHeader().getTime(); if (interval < (PocConsensusConstant.BLOCK_TIME_INTERVAL_SECOND * 2000)) { doit = false; break; } if (null == bestCorrectBlock.getNetBestBlockInfo()) { bestCorrectBlock.setNetBestBlockInfo(BEST_HEIGHT_FROM_NET.request(0)); } if (null == bestCorrectBlock.getNetBestBlockInfo()) { break; } if (bestCorrectBlock.getNetBestBlockInfo().getBestHeight() > bestCorrectBlock.getLocalBestBlock().getHeader().getHeight()) { doit = true; break; } } while (false); if (null == bestCorrectBlock.getNetBestBlockInfo()) { return; } if (doit) { downloadBlocks(bestCorrectBlock.getNetBestBlockInfo().getNodeIdList(), startHeight, bestCorrectBlock.getNetBestBlockInfo().getBestHeight()); } else { this.status = MaintenanceStatus.SUCCESS; } } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code public synchronized void syncBlock() { this.status = MaintenanceStatus.DOWNLOADING; while (true) { BestCorrectBlock bestCorrectBlock = checkLocalBestCorrentBlock(); boolean doit = false; long startHeight = 1; do { if (null == bestCorrectBlock.getLocalBestBlock() && bestCorrectBlock.getNetBestBlockInfo() == null) { doit = true; BlockInfo blockInfo = BEST_HEIGHT_FROM_NET.request(-1); bestCorrectBlock.setNetBestBlockInfo(blockInfo); break; } startHeight = bestCorrectBlock.getLocalBestBlock().getHeader().getHeight() + 1; long interval = TimeService.currentTimeMillis() - bestCorrectBlock.getLocalBestBlock().getHeader().getTime(); if (interval < (PocConsensusConstant.BLOCK_TIME_INTERVAL_SECOND * 2000)) { doit = false; break; } if (null == bestCorrectBlock.getNetBestBlockInfo()) { bestCorrectBlock.setNetBestBlockInfo(BEST_HEIGHT_FROM_NET.request(0)); } if (null == bestCorrectBlock.getNetBestBlockInfo()) { break; } if (bestCorrectBlock.getNetBestBlockInfo().getBestHeight() > bestCorrectBlock.getLocalBestBlock().getHeader().getHeight()) { doit = true; break; } } while (false); if (null == bestCorrectBlock.getNetBestBlockInfo()) { return; } if (doit) { downloadBlocks(bestCorrectBlock.getNetBestBlockInfo().getNodeIdList(), startHeight, bestCorrectBlock.getNetBestBlockInfo().getBestHeight()); } else { break; } long start = TimeService.currentTimeMillis(); //todo long timeout = (bestCorrectBlock.getNetBestBlockInfo().getBestHeight()-startHeight+1)*100; while (NulsContext.getInstance().getBestHeight()<bestCorrectBlock.getNetBestBlockInfo().getBestHeight()){ if(TimeService.currentTimeMillis()>(timeout+start)){ break; } try { Thread.sleep(1000); } catch (InterruptedException e) { Log.error(e); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void checkIt() { int maxSize = 0; BlockHeaderChain longestChain = null; StringBuilder str = new StringBuilder("++++++++++++++++++++++++chain info:"); for (BlockHeaderChain chain : chainList) { str.append("+++++++++++\nchain:start-" + chain.getHeaderDigestList().get(0).getHeight() + ", end-" + chain.getHeaderDigestList().get(chain.size() - 1).getHeight()); int listSize = chain.size(); if (maxSize < listSize) { maxSize = listSize; longestChain = chain; } else if (maxSize == listSize) { HeaderDigest hd = chain.getLastHd(); HeaderDigest hd_long = longestChain.getLastHd(); if (hd.getTime() < hd_long.getTime()) { longestChain = chain; } } } if (tempIndex % 10 == 0) { BlockLog.info(str.toString()); tempIndex++; } if (this.approvingChain != null || !this.approvingChain.getId().equals(longestChain.getId())) { BlockService blockService = NulsContext.getServiceBean(BlockService.class); for (int i=approvingChain.size()-1;i>=0;i--) { HeaderDigest hd = approvingChain.getHeaderDigestList().get(i); try { blockService.rollbackBlock(hd.getHash()); } catch (NulsException e) { Log.error(e); } } for(int i=0;i<longestChain.getHeaderDigestList().size();i++){ HeaderDigest hd = longestChain.getHeaderDigestList().get(i); blockService.approvalBlock(hd.getHash()); } } this.approvingChain = longestChain; Set<String> rightHashSet = new HashSet<>(); Set<String> removeHashSet = new HashSet<>(); for (int i = chainList.size() - 1; i >= 0; i--) { BlockHeaderChain chain = chainList.get(i); if (chain.size() < (maxSize - 6)) { removeHashSet.addAll(chain.getHashSet()); this.chainList.remove(chain); } else { rightHashSet.addAll(chain.getHashSet()); } } for (String hash : removeHashSet) { if (!rightHashSet.contains(hash)) { confirmingBlockCacheManager.removeBlock(hash); } } } #location 33 #vulnerability type NULL_DEREFERENCE
#fixed code private void checkIt() { int maxSize = 0; BlockHeaderChain longestChain = null; StringBuilder str = new StringBuilder("++++++++++++++++++++++++chain info:"); for (BlockHeaderChain chain : chainList) { str.append("+++++++++++\nchain:start-" + chain.getHeaderDigestList().get(0).getHeight() + ", end-" + chain.getHeaderDigestList().get(chain.size() - 1).getHeight()); int listSize = chain.size(); if (maxSize < listSize) { maxSize = listSize; longestChain = chain; } else if (maxSize == listSize) { HeaderDigest hd = chain.getLastHd(); HeaderDigest hd_long = longestChain.getLastHd(); if (hd.getTime() < hd_long.getTime()) { longestChain = chain; } } } if (tempIndex % 10 == 0) { BlockLog.info(str.toString()); tempIndex++; } if (this.approvingChain != null && !this.approvingChain.getId().equals(longestChain.getId())) { BlockService blockService = NulsContext.getServiceBean(BlockService.class); for (int i=approvingChain.size()-1;i>=0;i--) { HeaderDigest hd = approvingChain.getHeaderDigestList().get(i); try { blockService.rollbackBlock(hd.getHash()); } catch (NulsException e) { Log.error(e); } } for(int i=0;i<longestChain.getHeaderDigestList().size();i++){ HeaderDigest hd = longestChain.getHeaderDigestList().get(i); blockService.approvalBlock(hd.getHash()); } } this.approvingChain = longestChain; Set<String> rightHashSet = new HashSet<>(); Set<String> removeHashSet = new HashSet<>(); for (int i = chainList.size() - 1; i >= 0; i--) { BlockHeaderChain chain = chainList.get(i); if (chain.size() < (maxSize - 6)) { removeHashSet.addAll(chain.getHashSet()); this.chainList.remove(chain); } else { rightHashSet.addAll(chain.getHashSet()); } } for (String hash : removeHashSet) { if (!rightHashSet.contains(hash)) { confirmingBlockCacheManager.removeBlock(hash); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void recalc(Block bestBlock) { this.currentRound = null; this.previousRound = null; this.calc(bestBlock); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private void recalc(Block bestBlock) { this.currentRound = null; this.calc(bestBlock); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public LockNulsTransaction createLockNulsTx(CoinTransferData transferData, String password, String remark) throws Exception { LockNulsTransaction tx = new LockNulsTransaction(transferData, password); if (StringUtils.isNotBlank(remark)) { tx.setRemark(remark.getBytes(NulsContext.DEFAULT_ENCODING)); } tx.setHash(NulsDigestData.calcDigestData(tx.serialize())); tx.setSign(getAccountService().signData(tx.getHash(), password)); return tx; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public LockNulsTransaction createLockNulsTx(CoinTransferData transferData, String password, String remark) throws Exception { LockNulsTransaction tx = new LockNulsTransaction(transferData, password); if (StringUtils.isNotBlank(remark)) { tx.setRemark(remark.getBytes(NulsContext.DEFAULT_ENCODING)); } tx.setHash(NulsDigestData.calcDigestData(tx.serialize())); AccountService accountService = getAccountService(); if (transferData.getFrom().isEmpty()) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR); } Account account = accountService.getAccount(transferData.getFrom().get(0)); tx.setSign(accountService.signData(tx.getHash(), account, password)); return tx; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public PocMeetingRound getCurrentRound() { if (needReSet) { return null; } List<Account> accountList = accountService.getAccountList(); currentRound.calcLocalPacker(accountList); return currentRound; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public PocMeetingRound getCurrentRound() { List<Account> accountList = accountService.getAccountList(); currentRound.calcLocalPacker(accountList); return currentRound; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ValidateResult verifyCoinData(AbstractCoinTransaction tx, List<Transaction> txList) { if (txList == null || txList.isEmpty()) { //It's all an orphan that can go here return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX); } UtxoData data = (UtxoData) tx.getCoinData(); Map<String, UtxoOutput> outputMap = getAllOutputMap(txList); for (int i = 0; i < data.getInputs().size(); i++) { UtxoInput input = data.getInputs().get(i); UtxoOutput output = ledgerCacheService.getUtxo(input.getKey()); if (output == null && tx.getStatus() == TxStatusEnum.UNCONFIRM) { output = outputMap.get(input.getKey()); if (null == output) { return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX); } } else if (output == null) { return ValidateResult.getFailedResult(ErrorCode.UTXO_NOT_FOUND); } if (tx.getStatus() == TxStatusEnum.UNCONFIRM) { if (tx.getType() == TransactionConstant.TX_TYPE_STOP_AGENT) { if (output.getStatus() != OutPutStatusEnum.UTXO_CONSENSUS_LOCK) { return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE); } } else if (!output.isUsable()) { return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE); } } // else if (tx.getStatus() == TxStatusEnum.AGREED) { // if (!output.isSpend()) { // return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE); // } // } byte[] owner = output.getOwner(); P2PKHScriptSig p2PKHScriptSig = null; try { p2PKHScriptSig = P2PKHScriptSig.createFromBytes(tx.getScriptSig()); } catch (NulsException e) { return ValidateResult.getFailedResult(ErrorCode.DATA_ERROR); } byte[] user = p2PKHScriptSig.getSignerHash160(); if (!Arrays.equals(owner, user)) { return ValidateResult.getFailedResult(ErrorCode.INVALID_INPUT); } return ValidateResult.getSuccessResult(); } return ValidateResult.getSuccessResult(); } #location 33 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public ValidateResult verifyCoinData(AbstractCoinTransaction tx, List<Transaction> txList) { if (txList == null || txList.isEmpty()) { //It's all an orphan that can go here return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX); } UtxoData data = (UtxoData) tx.getCoinData(); Map<String, UtxoOutput> outputMap = getAllOutputMap(txList); for (int i = 0; i < data.getInputs().size(); i++) { UtxoInput input = data.getInputs().get(i); UtxoOutput output = ledgerCacheService.getUtxo(input.getKey()); if (output == null && tx.getStatus() == TxStatusEnum.UNCONFIRM) { output = outputMap.get(input.getKey()); if (null == output) { return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX); } } else if (output == null) { return ValidateResult.getFailedResult(ErrorCode.UTXO_NOT_FOUND); } if (tx.getStatus() == TxStatusEnum.UNCONFIRM) { if (tx.getType() == TransactionConstant.TX_TYPE_STOP_AGENT) { if (output.getStatus() != OutPutStatusEnum.UTXO_CONSENSUS_LOCK) { return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE); } } else if (output.getStatus() != OutPutStatusEnum.UTXO_UNSPENT) { return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE); } } // else if (tx.getStatus() == TxStatusEnum.AGREED) { // if (!output.isSpend()) { // return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE); // } // } byte[] owner = output.getOwner(); P2PKHScriptSig p2PKHScriptSig = null; try { p2PKHScriptSig = P2PKHScriptSig.createFromBytes(tx.getScriptSig()); } catch (NulsException e) { return ValidateResult.getFailedResult(ErrorCode.DATA_ERROR); } byte[] user = p2PKHScriptSig.getSignerHash160(); if (!Arrays.equals(owner, user)) { return ValidateResult.getFailedResult(ErrorCode.INVALID_INPUT); } return ValidateResult.getSuccessResult(); } return ValidateResult.getSuccessResult(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void approve(CoinData coinData, Transaction tx) throws NulsException { //spent the transaction specified output in the cache when the newly received transaction is approved. UtxoData utxoData = (UtxoData) coinData; for (UtxoInput input : utxoData.getInputs()) { input.setTxHash(tx.getHash()); } for (UtxoOutput output : utxoData.getOutputs()) { output.setTxHash(tx.getHash()); } List<UtxoOutput> unSpends = new ArrayList<>(); Set<String> addressSet = new HashSet<>(); try { //update inputs referenced utxo status for (int i = 0; i < utxoData.getInputs().size(); i++) { UtxoInput input = utxoData.getInputs().get(i); UtxoOutput unSpend = ledgerCacheService.getUtxo(input.getKey()); if (null == unSpend) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "the output is not exist!"); } if (!unSpend.isUsable()) { throw new NulsRuntimeException(ErrorCode.UTXO_UNUSABLE); } if (OutPutStatusEnum.UTXO_CONFIRM_UNSPEND == unSpend.getStatus()) { unSpend.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == unSpend.getStatus()) { unSpend.setStatus(OutPutStatusEnum.UTXO_UNCONFIRM_SPEND); } unSpends.add(unSpend); addressSet.add(unSpend.getAddress()); } //cache new utxo ,it is unConfirm approveProcessOutput(utxoData.getOutputs(), tx, addressSet); } catch (Exception e) { //rollback for (UtxoOutput output : unSpends) { if (OutPutStatusEnum.UTXO_CONFIRM_SPEND.equals(output.getStatus())) { ledgerCacheService.updateUtxoStatus(output.getKey(), OutPutStatusEnum.UTXO_CONFIRM_UNSPEND, OutPutStatusEnum.UTXO_CONFIRM_SPEND); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND.equals(output.getStatus())) { ledgerCacheService.updateUtxoStatus(output.getKey(), OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND, OutPutStatusEnum.UTXO_UNCONFIRM_SPEND); } } // remove cache new utxo for (int i = 0; i < utxoData.getOutputs().size(); i++) { UtxoOutput output = utxoData.getOutputs().get(i); ledgerCacheService.removeUtxo(output.getKey()); } throw e; } finally { //calc balance for (String address : addressSet) { UtxoTransactionTool.getInstance().calcBalance(address, false); } } } #location 35 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void approve(CoinData coinData, Transaction tx) throws NulsException { //spent the transaction specified output in the cache when the newly received transaction is approved. UtxoData utxoData = (UtxoData) coinData; for (UtxoInput input : utxoData.getInputs()) { input.setTxHash(tx.getHash()); } for (UtxoOutput output : utxoData.getOutputs()) { output.setTxHash(tx.getHash()); } List<UtxoOutput> unSpends = new ArrayList<>(); Set<String> addressSet = new HashSet<>(); try { lock.lock(); //update inputs referenced utxo status for (int i = 0; i < utxoData.getInputs().size(); i++) { UtxoInput input = utxoData.getInputs().get(i); UtxoOutput unSpend = ledgerCacheService.getUtxo(input.getKey()); if (null == unSpend) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "the output is not exist!"); } if (!unSpend.isUsable()) { throw new NulsRuntimeException(ErrorCode.UTXO_UNUSABLE); } if (OutPutStatusEnum.UTXO_CONFIRM_UNSPEND == unSpend.getStatus()) { unSpend.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == unSpend.getStatus()) { unSpend.setStatus(OutPutStatusEnum.UTXO_UNCONFIRM_SPEND); } unSpends.add(unSpend); addressSet.add(unSpend.getAddress()); } //cache new utxo ,it is unConfirm approveProcessOutput(utxoData.getOutputs(), tx, addressSet); } catch (Exception e) { //rollback for (UtxoOutput output : unSpends) { if (OutPutStatusEnum.UTXO_CONFIRM_SPEND.equals(output.getStatus())) { ledgerCacheService.updateUtxoStatus(output.getKey(), OutPutStatusEnum.UTXO_CONFIRM_UNSPEND, OutPutStatusEnum.UTXO_CONFIRM_SPEND); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND.equals(output.getStatus())) { ledgerCacheService.updateUtxoStatus(output.getKey(), OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND, OutPutStatusEnum.UTXO_UNCONFIRM_SPEND); } } // remove cache new utxo for (int i = 0; i < utxoData.getOutputs().size(); i++) { UtxoOutput output = utxoData.getOutputs().get(i); ledgerCacheService.removeUtxo(output.getKey()); } throw e; } finally { lock.unlock(); //calc balance for (String address : addressSet) { UtxoTransactionTool.getInstance().calcBalance(address, false); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void sendMessage(AbstractNetworkMessage networkMessage) throws IOException { if (this.getStatus() == Peer.CLOSE) { return; } if (writeTarget == null) { throw new NotYetConnectedException(); } if (this.status != Peer.HANDSHAKE && !isHandShakeMessage(networkMessage)) { throw new NotYetConnectedException(); } byte[] data = networkMessage.serialize(); NulsMessage message = new NulsMessage(network.packetMagic(), NulsMessageHeader.NETWORK_MESSAGE, data); sendMessage(message); } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void sendMessage(AbstractNetworkMessage networkMessage) throws IOException { if (this.getStatus() == Peer.CLOSE) { return; } if (writeTarget == null) { throw new NotYetConnectedException(); } if (this.status != Peer.HANDSHAKE && !isHandShakeMessage(networkMessage)) { throw new NotYetConnectedException(); } lock.lock(); try { byte[] data = networkMessage.serialize(); NulsMessage message = new NulsMessage(network.packetMagic(), NulsMessageHeader.NETWORK_MESSAGE, data); this.writeTarget.write(message.serialize()); } finally { lock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public ValidateResult validate(BlockHeader header, List<Transaction> txs) { if (header.getHeight() == 0) { return ValidateResult.getSuccessResult(); } BlockRoundData roundData = new BlockRoundData(header.getExtend()); Block preBlock = getBlockService().getBlock(header.getPreHash().getDigestHex()); if (null == preBlock) { //When a block does not exist, it is temporarily validated. return ValidateResult.getSuccessResult(); } calc(preBlock); BlockRoundData preRoundData = new BlockRoundData(preBlock.getHeader().getExtend()); PocMeetingRound localThisRoundData = this.currentRound; PocMeetingRound localPreRoundData; if (preRoundData.getRoundIndex() == roundData.getRoundIndex()) { localPreRoundData = localThisRoundData; } else { localPreRoundData = localThisRoundData.getPreRound(); if (localPreRoundData == null) { localPreRoundData = calcCurrentRound(preBlock.getHeader(),preBlock.getHeader().getHeight(),preRoundData); } } if (roundData.getConsensusMemberCount() != localThisRoundData.getMemberCount()) { return ValidateResult.getFailedResult("The round data of the block is wrong!"); } if (roundData.getRoundIndex() == (localPreRoundData.getIndex() + 1) && roundData.getRoundStartTime() != localPreRoundData.getEndTime()) { return ValidateResult.getFailedResult("The round data of the block is wrong!"); } PocMeetingMember member = localThisRoundData.getMember(roundData.getPackingIndexOfRound()); if (null == member) { return ValidateResult.getFailedResult("Cannot find the packing member!"); } if (member.getIndexOfRound() != roundData.getPackingIndexOfRound() || !member.getPackingAddress().equals(header.getPackingAddress())) { ValidateResult vr = ValidateResult.getFailedResult("It's not the address's turn to pack the block!"); vr.setObject(header); vr.setLevel(SeverityLevelEnum.FLAGRANT_FOUL); return vr; } if (null == txs) { return ValidateResult.getSuccessResult(); } YellowPunishTransaction yellowPunishTx = null; for (Transaction tx : txs) { if (tx.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) { if (yellowPunishTx == null) { yellowPunishTx = (YellowPunishTransaction) tx; } else { return ValidateResult.getFailedResult("There are too many yellow punish transactions!"); } } } //when the blocks are continuous boolean isContinuous = preRoundData.getRoundIndex() == roundData.getRoundIndex() && preRoundData.getPackingIndexOfRound() == (roundData.getPackingIndexOfRound() - 1); isContinuous = isContinuous || (preRoundData.getRoundIndex() == (roundData.getRoundIndex() - 1) && preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount() && roundData.getPackingIndexOfRound() == 1); //Too long intervals will not be penalized. boolean longTimeAgo = preRoundData.getRoundIndex() < (roundData.getRoundIndex() - 1); if (longTimeAgo && yellowPunishTx == null) { return ValidateResult.getSuccessResult(); } if (isContinuous) { if (yellowPunishTx == null) { return ValidateResult.getSuccessResult(); } else { return ValidateResult.getFailedResult("the block shouldn't has any yellow punish tx!"); } } else { if (null == yellowPunishTx) { return ValidateResult.getFailedResult("It should be a yellow punish tx here!"); } if (yellowPunishTx.getTxData().getHeight() != header.getHeight()) { return ValidateResult.getFailedResult("The yellow punish tx's height is wrong!"); } int interval = 0; if (roundData.getRoundIndex() == preRoundData.getRoundIndex()) { interval = roundData.getPackingIndexOfRound() - preRoundData.getPackingIndexOfRound() - 1; } else if ((roundData.getRoundIndex() - 1) == preRoundData.getRoundIndex()) { interval = preRoundData.getConsensusMemberCount() - preRoundData.getPackingIndexOfRound() + roundData.getPackingIndexOfRound() - 1; } if (interval != yellowPunishTx.getTxData().getAddressList().size()) { return ValidateResult.getFailedResult("The count of YellowPunishTx is wrong,it should be " + interval); } else { long roundIndex = preRoundData.getRoundIndex(); long indexOfRound = preRoundData.getPackingIndexOfRound() + 1; List<String> addressList = new ArrayList<>(); while (true) { PocMeetingRound round = getRoundData(roundIndex); if (null == round) { break; } if (roundIndex == roundData.getRoundIndex() && roundData.getPackingIndexOfRound() <= indexOfRound) { break; } if (round.getMemberCount() < indexOfRound) { roundIndex++; indexOfRound = 1; continue; } PocMeetingMember meetingMember = round.getMember(interval); if (null == meetingMember) { return ValidateResult.getFailedResult("the round data has error!"); } addressList.add(meetingMember.getAgentAddress()); indexOfRound++; } if (addressList.size() != yellowPunishTx.getTxData().getAddressList().size()) { return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!address list size is wrong!"); } for (String address : addressList) { boolean contains = false; for (Address addressObj : yellowPunishTx.getTxData().getAddressList()) { if (addressObj.getBase58().equals(address)) { contains = true; break; } } if (!contains) { return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!It has wrong address"); } } } } return checkCoinBaseTx(header, txs, roundData, localThisRoundData); } #location 90 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public ValidateResult validate(BlockHeader header, List<Transaction> txs) { if (header.getHeight() == 0) { return ValidateResult.getSuccessResult(); } BlockRoundData roundData = new BlockRoundData(header.getExtend()); Block preBlock = getBlockService().getBlock(header.getPreHash().getDigestHex()); if (null == preBlock) { //When a block does not exist, it is temporarily validated. return ValidateResult.getSuccessResult(); } calc(preBlock); BlockRoundData preRoundData = new BlockRoundData(preBlock.getHeader().getExtend()); PocMeetingRound localThisRoundData = this.currentRound; PocMeetingRound localPreRoundData; if (preRoundData.getRoundIndex() == roundData.getRoundIndex()) { localPreRoundData = localThisRoundData; } else { localPreRoundData = localThisRoundData.getPreRound(); if (localPreRoundData == null) { localPreRoundData = calcCurrentRound(preBlock.getHeader(), preBlock.getHeader().getHeight(), preRoundData); } } if (roundData.getConsensusMemberCount() != localThisRoundData.getMemberCount()) { return ValidateResult.getFailedResult("The round data of the block is wrong!"); } if (roundData.getRoundIndex() == (localPreRoundData.getIndex() + 1) && roundData.getRoundStartTime() != localPreRoundData.getEndTime()) { return ValidateResult.getFailedResult("The round data of the block is wrong!"); } PocMeetingMember member = localThisRoundData.getMember(roundData.getPackingIndexOfRound()); if (null == member) { return ValidateResult.getFailedResult("Cannot find the packing member!"); } if (member.getIndexOfRound() != roundData.getPackingIndexOfRound() || !member.getPackingAddress().equals(header.getPackingAddress())) { ValidateResult vr = ValidateResult.getFailedResult("It's not the address's turn to pack the block!"); vr.setObject(header); vr.setLevel(SeverityLevelEnum.FLAGRANT_FOUL); return vr; } if (null == txs) { return ValidateResult.getSuccessResult(); } YellowPunishTransaction yellowPunishTx = null; for (Transaction tx : txs) { if (tx.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) { if (yellowPunishTx == null) { yellowPunishTx = (YellowPunishTransaction) tx; } else { return ValidateResult.getFailedResult("There are too many yellow punish transactions!"); } } } //when the blocks are continuous boolean isContinuous = preRoundData.getRoundIndex() == roundData.getRoundIndex() && preRoundData.getPackingIndexOfRound() == (roundData.getPackingIndexOfRound() - 1); isContinuous = isContinuous || (preRoundData.getRoundIndex() == (roundData.getRoundIndex() - 1) && preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount() && roundData.getPackingIndexOfRound() == 1); //Too long intervals will not be penalized. boolean longTimeAgo = preRoundData.getRoundIndex() < (roundData.getRoundIndex() - 1); if (longTimeAgo && yellowPunishTx == null) { return ValidateResult.getSuccessResult(); } if (isContinuous) { if (yellowPunishTx == null) { return ValidateResult.getSuccessResult(); } else { return ValidateResult.getFailedResult("the block shouldn't has any yellow punish tx!"); } } else { if (null == yellowPunishTx) { return ValidateResult.getFailedResult("It should be a yellow punish tx here!"); } if (yellowPunishTx.getTxData().getHeight() != header.getHeight()) { return ValidateResult.getFailedResult("The yellow punish tx's height is wrong!"); } int interval = 0; if (roundData.getRoundIndex() == preRoundData.getRoundIndex()) { interval = roundData.getPackingIndexOfRound() - preRoundData.getPackingIndexOfRound() - 1; } else if ((roundData.getRoundIndex() - 1) == preRoundData.getRoundIndex()) { interval = preRoundData.getConsensusMemberCount() - preRoundData.getPackingIndexOfRound() + roundData.getPackingIndexOfRound() - 1; } if (interval != yellowPunishTx.getTxData().getAddressList().size()) { return ValidateResult.getFailedResult("The count of YellowPunishTx is wrong,it should be " + interval); } else { long roundIndex = preRoundData.getRoundIndex(); int indexOfRound = 0; if (preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount()) { roundIndex++; indexOfRound = 1; } else { indexOfRound = preRoundData.getPackingIndexOfRound() + 1; } List<String> addressList = new ArrayList<>(); while (true) { PocMeetingRound tempRound; if (roundIndex == roundData.getRoundIndex()) { tempRound = localThisRoundData; } else if (roundIndex == (roundData.getRoundIndex() - 1)) { tempRound = localPreRoundData; } else { break; } if (tempRound == null) { break; } if (tempRound.getIndex() > roundData.getRoundIndex()) { break; } if (tempRound.getIndex() == roundData.getRoundIndex() && indexOfRound >= roundData.getPackingIndexOfRound()) { break; } if (indexOfRound >= tempRound.getMemberCount()) { roundIndex++; indexOfRound = 1; continue; } PocMeetingMember smo; try { smo = tempRound.getMember(indexOfRound); if (null == member) { break; } } catch (Exception e) { break; } indexOfRound++; addressList.add(smo.getAgentAddress()); } if (addressList.size() != yellowPunishTx.getTxData().getAddressList().size()) { return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!address list size is wrong!"); } for (String address : addressList) { boolean contains = false; for (Address addressObj : yellowPunishTx.getTxData().getAddressList()) { if (addressObj.getBase58().equals(address)) { contains = true; break; } } if (!contains) { return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!It has wrong address"); } } } } return checkCoinBaseTx(header, txs, roundData, localThisRoundData); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public NetworkEventResult process(BaseEvent networkEvent, Node node) { NodeEvent event = (NodeEvent) networkEvent; // String key = event.getHeader().getEventType() + "-" + node.getIp(); // if (cacheService.existEvent(key)) { // networkService.removeNode(node.getId()); // return null; // } // cacheService.putEvent(key, event, false); for (Node newNode : event.getEventBody().getNodes()) { newNode.setType(Node.OUT); newNode.setStatus(Node.WAIT); getNetworkService().addNodeToGroup(NetworkConstant.NETWORK_NODE_OUT_GROUP, newNode); } return null; } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public NetworkEventResult process(BaseEvent networkEvent, Node node) { NodeEvent event = (NodeEvent) networkEvent; Map<String, Node> outNodes = networkService.getNodeGroup(NetworkConstant.NETWORK_NODE_OUT_GROUP).getNodes(); boolean exist = false; for (Node newNode : event.getEventBody().getNodes()) { exist = false; for (Node outNode : outNodes.values()) { if (outNode.getIp().equals(node.getIp())) { exist = true; break; } } if (!exist) { newNode.setType(Node.OUT); newNode.setStatus(Node.WAIT); getNetworkService().addNodeToGroup(NetworkConstant.NETWORK_NODE_OUT_GROUP, newNode); } } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onEvent(BlockHeaderEvent event, String fromId) { if (DistributedBlockInfoRequestUtils.getInstance().addBlockHeader(fromId, event.getEventBody())) { return; } BlockHeader header = event.getEventBody(); ValidateResult result = header.verify(); if (result.isFailed()) { networkService.removeNode(fromId); return; } blockCacheManager.cacheBlockHeader(header); GetSmallBlockEvent getSmallBlockEvent = new GetSmallBlockEvent(); BasicTypeData<Long> data = new BasicTypeData<>(header.getHeight()); getSmallBlockEvent.setEventBody(data); eventBroadcaster.sendToNode(getSmallBlockEvent, fromId); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void onEvent(BlockHeaderEvent event, String fromId) { if (DistributedBlockInfoRequestUtils.getInstance().addBlockHeader(fromId, event.getEventBody())) { return; } BlockHeader header = event.getEventBody(); blockCacheManager.cacheBlockHeader(header); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { SocketChannel channel = (SocketChannel) ctx.channel(); String nodeId = IpUtil.getNodeId(channel.remoteAddress()); // Log.debug(" ---------------------- server channelRead ------------------------- " + nodeId); Node node = getNetworkService().getNode(nodeId); if (node != null && node.isAlive()) { ByteBuf buf = (ByteBuf) msg; byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); buf.release(); ByteBuffer buffer = ByteBuffer.allocate(bytes.length); buffer.put(bytes); // getNetworkService().receiveMessage(buffer, node); } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { SocketChannel channel = (SocketChannel) ctx.channel(); String nodeId = IpUtil.getNodeId(channel.remoteAddress()); // Log.debug(" ---------------------- server channelRead ------------------------- " + nodeId); Node node = networkService.getNode(nodeId); if (node != null && node.isAlive()) { ByteBuf buf = (ByteBuf) msg; byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); buf.release(); ByteBuffer buffer = ByteBuffer.allocate(bytes.length); buffer.put(bytes); // getNetworkService().receiveMessage(buffer, node); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Result<Integer> saveUnconfirmedTransaction(Transaction tx) { return saveTransaction(tx, TransactionInfo.UNCONFIRMED); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public Result<Integer> saveUnconfirmedTransaction(Transaction tx) { saveLock.lock(); try { ValidateResult result1 = tx.verify(); if (result1.isFailed()) { return result1; } result1 = this.ledgerService.verifyCoinData(tx, this.getAllUnconfirmedTransaction().getData()); if (result1.isFailed()) { return result1; } return saveTransaction(tx, TransactionInfo.UNCONFIRMED); } finally { saveLock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onEvent(TransactionEvent event, String fromId) { Transaction tx = event.getEventBody(); if (null == tx) { return; } ValidateResult result = tx.verify(); if (result.isFailed()) { if (result.getLevel() == SeverityLevelEnum.NORMAL_FOUL) { networkService.removeNode(fromId); } else if (result.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) { networkService.removeNode(fromId); } } cacheManager.putTx(tx); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void onEvent(TransactionEvent event, String fromId) { Transaction tx = event.getEventBody(); if (null == tx) { return; } ValidateResult result = tx.verify(); if (result.isFailed()) { if (result.getLevel() == SeverityLevelEnum.NORMAL_FOUL) { networkService.blackNode(fromId,NodePo.YELLOW); } else if (result.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) { networkService.blackNode(fromId, NodePo.BLACK); } } cacheManager.putTx(tx); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Account getAccount(String address) { AssertUtil.canNotEmpty(address, ""); Account account = accountCacheService.getAccountByAddress(address); if (account == null) { AliasPo aliasPo = aliasDataService.getByAddress(address); if (aliasPo != null) { try { account = new Account(); account.setAddress(Address.fromHashs(address)); account.setAlias(aliasPo.getAlias()); } catch (NulsException e) { e.printStackTrace(); } } } return account; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public Account getAccount(String address) { AssertUtil.canNotEmpty(address, ""); Account account = accountCacheService.getAccountByAddress(address); return account; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public BlockInfo request(long start, long end, long split) { lock.lock(); this.startTime = TimeService.currentTimeMillis(); requesting = true; hashesMap.clear(); calcMap.clear(); this.start = start; this.end = end; this.split = split; GetBlocksHashRequest event = new GetBlocksHashRequest(start, end, split); nodeIdList = this.eventBroadcaster.broadcastAndCache(event, false); if (nodeIdList.isEmpty()) { Log.error("get best height from net faild!"); lock.unlock(); throw new NulsRuntimeException(ErrorCode.NET_MESSAGE_ERROR, "broadcast faild!"); } return this.getBlockInfo(); } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public BlockInfo request(long start, long end, long split) { lock.lock(); this.startTime = TimeService.currentTimeMillis(); requesting = true; hashesMap.clear(); calcMap.clear(); this.start = start; this.end = end; this.split = split; GetBlocksHashRequest event = new GetBlocksHashRequest(start, end, split); nodeIdList = this.eventBroadcaster.broadcastAndCache(event, false); if (nodeIdList.isEmpty()) { Log.error("get best height from net faild!"); lock.unlock(); return null; } return this.getBlockInfo(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code boolean verifyPublicKey(){ //verify the public-KEY-hashes are the same byte[] publicKey = scriptSig.getPublicKey(); NulsDigestData digestData = NulsDigestData.calcDigestData(publicKey,NulsDigestData.DIGEST_ALG_SHA160); if(Arrays.equals(digestData.getDigestBytes(),script.getPublicKeyDigest().getDigestBytes())){ return true; } return false; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code boolean verifyPublicKey(){ //verify the public-KEY-hashes are the same byte[] publicKey = scriptSig.getPublicKey(); byte[] reedmAccount = Utils.sha256hash160(Utils.sha256hash160(publicKey)); if(Arrays.equals(reedmAccount,script.getPublicKeyDigest().getDigestBytes())){ return true; } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void init() { try { NetworkContext.setNetworkConfig(ConfigLoader.loadProperties(NetworkConstant.NETWORK_PROPERTIES)); } catch (IOException e) { Log.error(e); throw new NulsRuntimeException(ErrorCode.IO_ERROR); } this.registerService(NetworkServiceImpl.class); networkService = NulsContext.getServiceBean(NetworkService.class); networkService.init(); this.registerEvent(); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void init() { try { NetworkContext.setNetworkConfig(ConfigLoader.loadProperties(NetworkConstant.NETWORK_PROPERTIES)); } catch (IOException e) { Log.error(e); throw new NulsRuntimeException(ErrorCode.IO_ERROR); } this.registerService(NetworkServiceImpl.class); networkService = NulsContext.getServiceBean(NetworkService.class); this.registerEvent(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean containsSpend(String key) { for (int i = 0; i < unSpends.size(); i++) { UtxoOutput output = unSpends.get(i); if (key.equals(output.getTxHash().getDigestHex() + "-" + output.getIndex())) { return true; } } return false; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean containsSpend(String key) { for (int i = 0; i < unSpends.size(); i++) { UtxoOutput output = unSpends.get(i); if (key.equals(output.getKey())) { return true; } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { SocketChannel channel = (SocketChannel) ctx.channel(); String nodeId = IpUtil.getNodeId(channel.remoteAddress()); Log.debug("---------------------- server channelRegistered ------------------------- " + nodeId); String remoteIP = channel.remoteAddress().getHostString(); // String remoteId = IpUtil.getNodeId(channel.remoteAddress()); // Node node = getNetworkService().getNode(remoteId); // if (node != null) { // if (node.getStatus() == Node.CONNECT) { // ctx.channel().close(); // return; // } // //When nodes try to connect to each other but not connected, select one of the smaller IP addresses as the server //// if (node.getType() == Node.OUT) { //// String localIP = InetAddress.getLocalHost().getHostAddress(); //// boolean isLocalServer = IpUtil.judgeIsLocalServer(localIP, remoteIP); //// //// if (!isLocalServer) { //// ctx.channel().close(); //// return; //// } else { //// getNetworkService().removeNode(remoteId); //// } //// } // } else { // if has a node with same ip, and it's a out node, close this channel // if More than 10 in nodes of the same IP, close this channel int count = 0; for (Node n : getNetworkService().getNodes().values()) { if (n.getIp().equals(remoteIP)) { count++; if (count >= Node.SAME_IP_MAX_COUNT) { ctx.channel().close(); return; } // // if (n.getType() == Node.OUT && n.getStatus() == Node.HANDSHAKE) { // ctx.channel().close(); // return; // } else { // count++; // if (count == 10) { // ctx.channel().close(); // return; // } // } } } } #location 30 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { SocketChannel channel = (SocketChannel) ctx.channel(); String nodeId = IpUtil.getNodeId(channel.remoteAddress()); // Log.info("---------------------- server channelRegistered ------------------------- " + nodeId); String remoteIP = channel.remoteAddress().getHostString(); NodeGroup outGroup = networkService.getNodeGroup(NetworkConstant.NETWORK_NODE_OUT_GROUP); for (Node node : outGroup.getNodes().values()) { if (node.getIp().equals(remoteIP)) { String localIP = InetAddress.getLocalHost().getHostAddress(); boolean isLocalServer = IpUtil.judgeIsLocalServer(localIP, remoteIP); if (!isLocalServer) { ctx.channel().close(); return; } else { getNetworkService().removeNode(node.getId()); } } } // if has a node with same ip, and it's a out node, close this channel // if More than 10 in nodes of the same IP, close this channel int count = 0; for (Node n : getNetworkService().getNodes().values()) { if (n.getIp().equals(remoteIP)) { count++; if (count >= Node.SAME_IP_MAX_COUNT) { ctx.channel().close(); return; } // // if (n.getType() == Node.OUT && n.getStatus() == Node.HANDSHAKE) { // ctx.channel().close(); // return; // } else { // count++; // if (count == 10) { // ctx.channel().close(); // return; // } // } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public NetworkEventResult process(BaseEvent networkEvent, Node node) { VersionEvent event = (VersionEvent) networkEvent; // String key = event.getHeader().getEventType() + "-" + node.getId(); // if (cacheService.existEvent(key)) { // Log.info("----------VersionEventHandler cacheService existEvent--------"); // getNetworkService().removeNode(node.getId()); // return null; // } // cacheService.putEvent(key, event, true); if (event.getBestBlockHeight() < 0) { throw new NetworkMessageException(ErrorCode.NET_MESSAGE_ERROR); } node.setVersionMessage(event); checkVersion(event.getNulsVersion()); if (!node.isHandShake()) { node.setStatus(Node.HANDSHAKE); String oldId = node.getId(); node.setId(null); node.setPort(event.getExternalPort()); getNetworkService().changeNodeFromMap(oldId, node); node.setLastTime(TimeService.currentTimeMillis()); getNodeDao().saveChange(NodeTransferTool.toPojo(node)); } return null; } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public NetworkEventResult process(BaseEvent networkEvent, Node node) { VersionEvent event = (VersionEvent) networkEvent; // String key = event.getHeader().getEventType() + "-" + node.getId(); // if (cacheService.existEvent(key)) { // Log.info("----------VersionEventHandler cacheService existEvent--------"); // getNetworkService().removeNode(node.getId()); // return null; // } // cacheService.putEvent(key, event, true); if (event.getBestBlockHeight() < 0) { throw new NetworkMessageException(ErrorCode.NET_MESSAGE_ERROR); } node.setVersionMessage(event); checkVersion(event.getNulsVersion()); if (!node.isHandShake()) { node.setStatus(Node.HANDSHAKE); node.setSeverPort(event.getSeverPort()); node.setLastTime(TimeService.currentTimeMillis()); getNodeDao().saveChange(NodeTransferTool.toPojo(node)); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void approve(CoinData coinData, Transaction tx) throws NulsException { //spent the transaction specified output in the cache when the newly received transaction is approved. UtxoData utxoData = (UtxoData) coinData; for (UtxoInput input : utxoData.getInputs()) { input.setTxHash(tx.getHash()); } for (UtxoOutput output : utxoData.getOutputs()) { output.setTxHash(tx.getHash()); } List<UtxoOutput> unSpends = new ArrayList<>(); Set<String> addressSet = new HashSet<>(); try { //update inputs referenced utxo status for (int i = 0; i < utxoData.getInputs().size(); i++) { UtxoInput input = utxoData.getInputs().get(i); UtxoOutput unSpend = ledgerCacheService.getUtxo(input.getKey()); if (null == unSpend) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "the output is not exist!"); } if (!unSpend.isUsable()) { throw new NulsRuntimeException(ErrorCode.UTXO_UNUSABLE); } if (OutPutStatusEnum.UTXO_CONFIRM_UNSPEND == unSpend.getStatus()) { unSpend.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == unSpend.getStatus()) { unSpend.setStatus(OutPutStatusEnum.UTXO_UNCONFIRM_SPEND); } unSpends.add(unSpend); addressSet.add(unSpend.getAddress()); } //cache new utxo ,it is unConfirm approveProcessOutput(utxoData.getOutputs(), tx, addressSet); } catch (Exception e) { //rollback for (UtxoOutput output : unSpends) { if (OutPutStatusEnum.UTXO_CONFIRM_SPEND.equals(output.getStatus())) { ledgerCacheService.updateUtxoStatus(output.getKey(), OutPutStatusEnum.UTXO_CONFIRM_UNSPEND, OutPutStatusEnum.UTXO_CONFIRM_SPEND); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND.equals(output.getStatus())) { ledgerCacheService.updateUtxoStatus(output.getKey(), OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND, OutPutStatusEnum.UTXO_UNCONFIRM_SPEND); } } // remove cache new utxo for (int i = 0; i < utxoData.getOutputs().size(); i++) { UtxoOutput output = utxoData.getOutputs().get(i); ledgerCacheService.removeUtxo(output.getKey()); } throw e; } finally { //calc balance for (String address : addressSet) { UtxoTransactionTool.getInstance().calcBalance(address, false); } } } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void approve(CoinData coinData, Transaction tx) throws NulsException { //spent the transaction specified output in the cache when the newly received transaction is approved. UtxoData utxoData = (UtxoData) coinData; for (UtxoInput input : utxoData.getInputs()) { input.setTxHash(tx.getHash()); } for (UtxoOutput output : utxoData.getOutputs()) { output.setTxHash(tx.getHash()); } List<UtxoOutput> unSpends = new ArrayList<>(); Set<String> addressSet = new HashSet<>(); try { lock.lock(); //update inputs referenced utxo status for (int i = 0; i < utxoData.getInputs().size(); i++) { UtxoInput input = utxoData.getInputs().get(i); UtxoOutput unSpend = ledgerCacheService.getUtxo(input.getKey()); if (null == unSpend) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "the output is not exist!"); } if (!unSpend.isUsable()) { throw new NulsRuntimeException(ErrorCode.UTXO_UNUSABLE); } if (OutPutStatusEnum.UTXO_CONFIRM_UNSPEND == unSpend.getStatus()) { unSpend.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == unSpend.getStatus()) { unSpend.setStatus(OutPutStatusEnum.UTXO_UNCONFIRM_SPEND); } unSpends.add(unSpend); addressSet.add(unSpend.getAddress()); } //cache new utxo ,it is unConfirm approveProcessOutput(utxoData.getOutputs(), tx, addressSet); } catch (Exception e) { //rollback for (UtxoOutput output : unSpends) { if (OutPutStatusEnum.UTXO_CONFIRM_SPEND.equals(output.getStatus())) { ledgerCacheService.updateUtxoStatus(output.getKey(), OutPutStatusEnum.UTXO_CONFIRM_UNSPEND, OutPutStatusEnum.UTXO_CONFIRM_SPEND); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND.equals(output.getStatus())) { ledgerCacheService.updateUtxoStatus(output.getKey(), OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND, OutPutStatusEnum.UTXO_UNCONFIRM_SPEND); } } // remove cache new utxo for (int i = 0; i < utxoData.getOutputs().size(); i++) { UtxoOutput output = utxoData.getOutputs().get(i); ledgerCacheService.removeUtxo(output.getKey()); } throw e; } finally { lock.unlock(); //calc balance for (String address : addressSet) { UtxoTransactionTool.getInstance().calcBalance(address, false); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public ValidateResult validate(BlockHeader header, List<Transaction> txs) { if (header.getHeight() == 0) { return ValidateResult.getSuccessResult(); } BlockRoundData roundData = new BlockRoundData(header.getExtend()); Block preBlock = getBlockService().getBlock(header.getPreHash().getDigestHex()); if (null == preBlock) { //When a block does not exist, it is temporarily validated. return ValidateResult.getSuccessResult(); } calc(preBlock); BlockRoundData preRoundData = new BlockRoundData(preBlock.getHeader().getExtend()); PocMeetingRound localThisRoundData = this.currentRound; PocMeetingRound localPreRoundData; if (preRoundData.getRoundIndex() == roundData.getRoundIndex()) { localPreRoundData = localThisRoundData; } else { localPreRoundData = localThisRoundData.getPreRound(); if (localPreRoundData == null) { localPreRoundData = calcCurrentRound(preBlock.getHeader(), preBlock.getHeader().getHeight(), preRoundData); } } if (roundData.getConsensusMemberCount() != localThisRoundData.getMemberCount()) { return ValidateResult.getFailedResult("The round data of the block is wrong!"); } if (roundData.getRoundIndex() == (localPreRoundData.getIndex() + 1) && roundData.getRoundStartTime() != localPreRoundData.getEndTime()) { return ValidateResult.getFailedResult("The round data of the block is wrong!"); } PocMeetingMember member = localThisRoundData.getMember(roundData.getPackingIndexOfRound()); if (null == member) { return ValidateResult.getFailedResult("Cannot find the packing member!"); } if (member.getIndexOfRound() != roundData.getPackingIndexOfRound() || !member.getPackingAddress().equals(header.getPackingAddress())) { ValidateResult vr = ValidateResult.getFailedResult("It's not the address's turn to pack the block!"); vr.setObject(header); vr.setLevel(SeverityLevelEnum.FLAGRANT_FOUL); return vr; } if (null == txs) { return ValidateResult.getSuccessResult(); } YellowPunishTransaction yellowPunishTx = null; for (Transaction tx : txs) { if (tx.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) { if (yellowPunishTx == null) { yellowPunishTx = (YellowPunishTransaction) tx; } else { return ValidateResult.getFailedResult("There are too many yellow punish transactions!"); } } } //when the blocks are continuous boolean isContinuous = preRoundData.getRoundIndex() == roundData.getRoundIndex() && preRoundData.getPackingIndexOfRound() == (roundData.getPackingIndexOfRound() - 1); isContinuous = isContinuous || (preRoundData.getRoundIndex() == (roundData.getRoundIndex() - 1) && preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount() && roundData.getPackingIndexOfRound() == 1); //Too long intervals will not be penalized. boolean longTimeAgo = preRoundData.getRoundIndex() < (roundData.getRoundIndex() - 1); if (longTimeAgo && yellowPunishTx == null) { return ValidateResult.getSuccessResult(); } if (isContinuous) { if (yellowPunishTx == null) { return ValidateResult.getSuccessResult(); } else { return ValidateResult.getFailedResult("the block shouldn't has any yellow punish tx!"); } } else { if (null == yellowPunishTx) { return ValidateResult.getFailedResult("It should be a yellow punish tx here!"); } if (yellowPunishTx.getTxData().getHeight() != header.getHeight()) { return ValidateResult.getFailedResult("The yellow punish tx's height is wrong!"); } int interval = 0; if (roundData.getRoundIndex() == preRoundData.getRoundIndex()) { interval = roundData.getPackingIndexOfRound() - preRoundData.getPackingIndexOfRound() - 1; } else if ((roundData.getRoundIndex() - 1) == preRoundData.getRoundIndex()) { interval = preRoundData.getConsensusMemberCount() - preRoundData.getPackingIndexOfRound() + roundData.getPackingIndexOfRound() - 1; } if (interval != yellowPunishTx.getTxData().getAddressList().size()) { return ValidateResult.getFailedResult("The count of YellowPunishTx is wrong,it should be " + interval); } else { long roundIndex = preRoundData.getRoundIndex(); int indexOfRound = 0; if (preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount()) { roundIndex++; indexOfRound = 1; } else { indexOfRound = preRoundData.getPackingIndexOfRound() + 1; } List<String> addressList = new ArrayList<>(); while (true) { PocMeetingRound tempRound; if (roundIndex == roundData.getRoundIndex()) { tempRound = localThisRoundData; } else if (roundIndex == (roundData.getRoundIndex() - 1)) { tempRound = localPreRoundData; } else { break; } if (tempRound == null) { break; } if (tempRound.getIndex() > roundData.getRoundIndex()) { break; } if (tempRound.getIndex() == roundData.getRoundIndex() && indexOfRound >= roundData.getPackingIndexOfRound()) { break; } if (indexOfRound >= tempRound.getMemberCount()) { roundIndex++; indexOfRound = 1; continue; } PocMeetingMember smo; try { smo = tempRound.getMember(indexOfRound); if (null == member) { break; } } catch (Exception e) { break; } indexOfRound++; addressList.add(smo.getAgentAddress()); } if (addressList.size() != yellowPunishTx.getTxData().getAddressList().size()) { return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!address list size is wrong!"); } for (String address : addressList) { boolean contains = false; for (Address addressObj : yellowPunishTx.getTxData().getAddressList()) { if (addressObj.getBase58().equals(address)) { contains = true; break; } } if (!contains) { return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!It has wrong address"); } } } } return checkCoinBaseTx(header, txs, roundData, localThisRoundData); } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public ValidateResult validate(BlockHeader header, List<Transaction> txs) { if (header.getHeight() == 0) { return ValidateResult.getSuccessResult(); } BlockRoundData roundData = new BlockRoundData(header.getExtend()); Block preBlock = getBlockService().getBlock(header.getPreHash().getDigestHex()); if (null == preBlock) { //When a block does not exist, it is temporarily validated. return ValidateResult.getSuccessResult(); } BlockRoundData preRoundData = new BlockRoundData(preBlock.getHeader().getExtend()); PocMeetingRound localThisRoundData = calcCurrentRound(header, header.getHeight(), roundData); PocMeetingRound localPreRoundData = calcCurrentRound(preBlock.getHeader(), preBlock.getHeader().getHeight(), preRoundData); if (roundData.getConsensusMemberCount() != localThisRoundData.getMemberCount()) { return ValidateResult.getFailedResult("The round data of the block is wrong!"); } if (roundData.getRoundIndex() == (localPreRoundData.getIndex() + 1) && roundData.getRoundStartTime() != localPreRoundData.getEndTime()) { return ValidateResult.getFailedResult("The round data of the block is wrong!"); } PocMeetingMember member = localThisRoundData.getMember(roundData.getPackingIndexOfRound()); if (null == member) { return ValidateResult.getFailedResult("Cannot find the packing member!"); } if (member.getIndexOfRound() != roundData.getPackingIndexOfRound() || !member.getPackingAddress().equals(header.getPackingAddress())) { ValidateResult vr = ValidateResult.getFailedResult("It's not the address's turn to pack the block!"); vr.setObject(header); vr.setLevel(SeverityLevelEnum.FLAGRANT_FOUL); return vr; } if (null == txs) { return ValidateResult.getSuccessResult(); } YellowPunishTransaction yellowPunishTx = null; for (Transaction tx : txs) { if (tx.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) { if (yellowPunishTx == null) { yellowPunishTx = (YellowPunishTransaction) tx; } else { return ValidateResult.getFailedResult("There are too many yellow punish transactions!"); } } } //when the blocks are continuous boolean isContinuous = preRoundData.getRoundIndex() == roundData.getRoundIndex() && preRoundData.getPackingIndexOfRound() == (roundData.getPackingIndexOfRound() - 1); isContinuous = isContinuous || (preRoundData.getRoundIndex() == (roundData.getRoundIndex() - 1) && preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount() && roundData.getPackingIndexOfRound() == 1); //Too long intervals will not be penalized. boolean longTimeAgo = preRoundData.getRoundIndex() < (roundData.getRoundIndex() - 1); if (longTimeAgo && yellowPunishTx == null) { return ValidateResult.getSuccessResult(); } if (isContinuous) { if (yellowPunishTx == null) { return ValidateResult.getSuccessResult(); } else { return ValidateResult.getFailedResult("the block shouldn't has any yellow punish tx!"); } } else { if (null == yellowPunishTx) { return ValidateResult.getFailedResult("It should be a yellow punish tx here!"); } if (yellowPunishTx.getTxData().getHeight() != header.getHeight()) { return ValidateResult.getFailedResult("The yellow punish tx's height is wrong!"); } int interval = 0; if (roundData.getRoundIndex() == preRoundData.getRoundIndex()) { interval = roundData.getPackingIndexOfRound() - preRoundData.getPackingIndexOfRound() - 1; } else if ((roundData.getRoundIndex() - 1) == preRoundData.getRoundIndex()) { interval = preRoundData.getConsensusMemberCount() - preRoundData.getPackingIndexOfRound() + roundData.getPackingIndexOfRound() - 1; } if (interval != yellowPunishTx.getTxData().getAddressList().size()) { return ValidateResult.getFailedResult("The count of YellowPunishTx is wrong,it should be " + interval); } else { long roundIndex = preRoundData.getRoundIndex(); int indexOfRound = 0; if (preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount()) { roundIndex++; indexOfRound = 1; } else { indexOfRound = preRoundData.getPackingIndexOfRound() + 1; } List<String> addressList = new ArrayList<>(); while (true) { PocMeetingRound tempRound; if (roundIndex == roundData.getRoundIndex()) { tempRound = localThisRoundData; } else if (roundIndex == (roundData.getRoundIndex() - 1)) { tempRound = localPreRoundData; } else { break; } if (tempRound == null) { break; } if (tempRound.getIndex() > roundData.getRoundIndex()) { break; } if (tempRound.getIndex() == roundData.getRoundIndex() && indexOfRound >= roundData.getPackingIndexOfRound()) { break; } if (indexOfRound >= tempRound.getMemberCount()) { roundIndex++; indexOfRound = 1; continue; } PocMeetingMember smo; try { smo = tempRound.getMember(indexOfRound); if (null == member) { break; } } catch (Exception e) { break; } indexOfRound++; addressList.add(smo.getAgentAddress()); } if (addressList.size() != yellowPunishTx.getTxData().getAddressList().size()) { return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!address list size is wrong!"); } for (String address : addressList) { boolean contains = false; for (Address addressObj : yellowPunishTx.getTxData().getAddressList()) { if (addressObj.getBase58().equals(address)) { contains = true; break; } } if (!contains) { return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!It has wrong address"); } } } } return checkCoinBaseTx(header, txs, roundData, localThisRoundData); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int getChainId(String chainName) { return chain_id_map.get(chainName); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public int getChainId(String chainName) { return CHAIN_ID_MAP.get(chainName); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String getPwd(){ System.out.print("Please enter the password, if the account has no password directly return.\nEnter your password:"); ConsoleReader reader = null; try { reader = new ConsoleReader(); String pwd = reader.readLine('*'); return pwd; } catch (IOException e) { return null; }finally { try { if(!reader.delete()){ reader.close(); } } catch (IOException e) { e.printStackTrace(); } } } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code public static String getPwd() { return getPwd(null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void processMessage(NulsMessage message) throws IOException { if (message.getHeader().getHeadType() == NulsMessageHeader.EVENT_MESSAGE) { try { System.out.println("------receive message:" + Hex.encode(message.serialize())); } catch (IOException e) { e.printStackTrace(); } if (this.status != Peer.HANDSHAKE) { return; } if (checkBroadcastExist(message.getData())) { return; } eventProcessorService.dispatch(message.getData(), this.getHash()); } else { byte[] networkHeader = new byte[NetworkDataHeader.NETWORK_HEADER_SIZE]; System.arraycopy(message.getData(), 0, networkHeader, 0, NetworkDataHeader.NETWORK_HEADER_SIZE); NetworkDataHeader header; BaseNetworkData networkMessage; try { header = new NetworkDataHeader(new NulsByteBuffer(networkHeader)); networkMessage = BaseNetworkData.transfer(header.getType(), message.getData()); } catch (NulsException e) { Log.error("networkMessage transfer error:", e); this.destroy(); return; } if (this.status != Peer.HANDSHAKE && !isHandShakeMessage(networkMessage)) { return; } asynExecute(networkMessage); } } #location 31 #vulnerability type NULL_DEREFERENCE
#fixed code public void processMessage(NulsMessage message) throws IOException { //todo if (true) { try { System.out.println("------receive message:" + Hex.encode(message.serialize())); } catch (IOException e) { e.printStackTrace(); } if (this.status != Peer.HANDSHAKE) { return; } if (checkBroadcastExist(message.getData())) { return; } eventProcessorService.dispatch(message.getData(), this.getHash()); } else { byte[] networkHeader = new byte[NetworkDataHeader.NETWORK_HEADER_SIZE]; System.arraycopy(message.getData(), 0, networkHeader, 0, NetworkDataHeader.NETWORK_HEADER_SIZE); NetworkDataHeader header; BaseNetworkData networkMessage; try { header = new NetworkDataHeader(new NulsByteBuffer(networkHeader)); networkMessage = BaseNetworkData.transfer(header.getType(), message.getData()); } catch (NulsException e) { Log.error("networkMessage transfer error:", e); this.destroy(); return; } if (this.status != Peer.HANDSHAKE && !isHandShakeMessage(networkMessage)) { return; } asynExecute(networkMessage); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean downloadedBlock(String nodeId, Block block) { System.out.println("downloaded:"+block.getHeader().getHeight()); NodeDownloadingStatus status = nodeStatusMap.get(nodeId); if (null == status) { return false; } if (!status.containsHeight(block.getHeader().getHeight())) { return false; } blockMap.put(block.getHeader().getHeight(), block); status.downloaded(block.getHeader().getHeight()); status.setUpdateTime(System.currentTimeMillis()); if (status.finished()) { this.queueService.offer(queueId, nodeId); } verify(); return true; } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean downloadedBlock(String nodeId, Block block) { System.out.println("downloaded:" + block.getHeader().getHeight()); NodeDownloadingStatus status = nodeStatusMap.get(nodeId); if (null == status) { return false; } if (!status.containsHeight(block.getHeader().getHeight())) { return false; } blockMap.put(block.getHeader().getHeight(), block); status.downloaded(block.getHeader().getHeight()); status.setUpdateTime(System.currentTimeMillis()); if (status.finished()) { this.queueService.offer(queueId, nodeId); } verify(); return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onEvent(DisruptorData<ProcessData<E>> processDataDisruptorMessage, long l, boolean b) { try { BaseMessage message = processDataDisruptorMessage.getData().getData(); if (null == message || message.getHeader() == null) { return; } messageCacheService.cacheRecievedMessageHash(message.getHash()); //todo test if (message.getHeader().getModuleId() == ProtocolConstant.MODULE_ID_PROTOCOL && message.getHeader().getMsgType() == ProtocolConstant.MESSAGE_TYPE_NEW_BLOCK) { SmallBlockMessage smallBlockMessage = (SmallBlockMessage) message; Log.warn("rcv-msg:" + smallBlockMessage.getMsgBody().getHeader().getHash().toString()); } boolean commonDigestTx = message.getHeader().getMsgType() == MessageBusConstant.MSG_TYPE_COMMON_MSG_HASH_MSG && message.getHeader().getModuleId() == MessageBusConstant.MODULE_ID_MESSAGE_BUS; if (!commonDigestTx) { return; } if (messageCacheService.kownTheMessage(((CommonDigestMessage) message).getMsgBody())) { Log.info("discard:{}," + ((CommonDigestMessage) message).getMsgBody(), processDataDisruptorMessage.getData().getNode().getId()); processDataDisruptorMessage.setStoped(true); } else if (messageCacheService.kownTheMessage(message.getHash())) { Log.info("discard2:{}," + message.getClass(), processDataDisruptorMessage.getData().getNode().getId()); processDataDisruptorMessage.setStoped(true); } } catch (Exception e) { Log.error(e); } } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void onEvent(DisruptorData<ProcessData<E>> processDataDisruptorMessage, long l, boolean b) { try { BaseMessage message = processDataDisruptorMessage.getData().getData(); if (null == message || message.getHeader() == null) { return; } //todo test if (message.getHeader().getModuleId() == ProtocolConstant.MODULE_ID_PROTOCOL && message.getHeader().getMsgType() == ProtocolConstant.MESSAGE_TYPE_NEW_BLOCK) { SmallBlockMessage smallBlockMessage = (SmallBlockMessage) message; Log.warn("rcv-msg:" + smallBlockMessage.getMsgBody().getHeader().getHash().toString()); } boolean commonDigestTx = message.getHeader().getMsgType() == MessageBusConstant.MSG_TYPE_COMMON_MSG_HASH_MSG && message.getHeader().getModuleId() == MessageBusConstant.MODULE_ID_MESSAGE_BUS; if (!commonDigestTx) { messageCacheService.cacheRecievedMessageHash(message.getHash()); return; } if (messageCacheService.kownTheMessage(((CommonDigestMessage) message).getMsgBody())) { Log.info("discard:{}," + ((CommonDigestMessage) message).getMsgBody(), processDataDisruptorMessage.getData().getNode().getId()); processDataDisruptorMessage.setStoped(true); } else if (messageCacheService.kownTheMessage(message.getHash())) { Log.info("discard2:{}," + message.getClass(), processDataDisruptorMessage.getData().getNode().getId()); processDataDisruptorMessage.setStoped(true); } else { messageCacheService.cacheRecievedMessageHash(message.getHash()); } } catch (Exception e) { Log.error(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ValidateResult validate(Block block) { if (block.getHeader().getTxCount() != block.getTxs().size()) { return ValidateResult.getFailedResult("txCount is wrong!"); } int count = 0; for (Transaction tx : block.getTxs()) { ValidateResult result = tx.verify(); if (null==result||result.isFailed()) { if(result.getErrorCode()== ErrorCode.ORPHAN_TX){ return result; } return ValidateResult.getFailedResult("there is wrong transaction!msg:"+result.getMessage()); } if (tx.getType() == TransactionConstant.TX_TYPE_COIN_BASE) { count++; } } if (count > 1) { return ValidateResult.getFailedResult("coinbase transaction must only one!"); } return ValidateResult.getSuccessResult(); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public ValidateResult validate(Block block) { if (block.getHeader().getTxCount() != block.getTxs().size()) { return ValidateResult.getFailedResult("txCount is wrong!"); } int count = 0; List<Transaction> txList = new ArrayList<>(); for (Transaction tx : block.getTxs()) { ValidateResult result = tx.verify(); if(result.isFailed()&&result.getErrorCode()== ErrorCode.ORPHAN_TX){ AbstractCoinTransaction coinTx = (AbstractCoinTransaction) tx; result = coinTx.getCoinDataProvider().verifyCoinData(coinTx,txList); if(result.isSuccess()){ coinTx.setSkipInputValidator(true); result = coinTx.verify(); coinTx.setSkipInputValidator(false); } } if (null==result||result.isFailed()) { if(result.getErrorCode()== ErrorCode.ORPHAN_TX){ return result; } return ValidateResult.getFailedResult("there is wrong transaction!msg:"+result.getMessage()); } if (tx.getType() == TransactionConstant.TX_TYPE_COIN_BASE) { count++; } txList.add(tx); } if (count > 1) { return ValidateResult.getFailedResult("coinbase transaction must only one!"); } return ValidateResult.getSuccessResult(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void init() { //load five(CACHE_COUNT) round from db on the start time ; Block bestBlock = getBestBlock(); BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend()); boolean updateCacheStatus = true; for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) { Block firstBlock = getBlockService().getRoundFirstBlock(i - 1); BlockRoundData preRoundData = new BlockRoundData(firstBlock.getHeader().getExtend()); PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, preRoundData.getRoundEndTime(), updateCacheStatus); ROUND_MAP.put(round.getIndex(), round); Log.debug("load the round data index:{}", round.getIndex()); updateCacheStatus = false; } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public void init() { lock.lock(); try { realInit(); } finally { lock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean verifyBaseTx(Block block, MeetingRound currentRound, MeetingMember member) { if(5176 == block.getHeader().getHeight()) { System.out.println("in the bug"); } List<Transaction> txs = block.getTxs(); Transaction tx = txs.get(0); if (tx.getType() != TransactionConstant.TX_TYPE_COIN_BASE) { BlockLog.debug("Coinbase transaction order wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); // Log.error("Coinbase transaction order wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); return false; } YellowPunishTransaction yellowPunishTx = null; for (int i = 1; i < txs.size(); i++) { Transaction transaction = txs.get(i); if (transaction.getType() == TransactionConstant.TX_TYPE_COIN_BASE) { BlockLog.debug("Coinbase transaction more than one! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); // Log.error("Coinbase transaction more than one! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); return false; } if (null == yellowPunishTx && transaction.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) { yellowPunishTx = (YellowPunishTransaction) transaction; } else if (null != yellowPunishTx && transaction.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) { BlockLog.debug("Yellow punish transaction more than one! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); // Log.error("Yellow punish transaction more than one! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); return false; } } CoinBaseTransaction coinBaseTransaction = ConsensusTool.createCoinBaseTx(member, block.getTxs(), currentRound, block.getHeader().getHeight() + PocConsensusConstant.COINBASE_UNLOCK_HEIGHT); if (null == coinBaseTransaction || !tx.getHash().equals(coinBaseTransaction.getHash())) { BlockLog.debug("the coin base tx is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); Log.error("the coin base tx is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); Log.error("Pierre-error-test: tx is <" + tx.toString() + ">, coinBaseTransaction is <" + coinBaseTransaction.toString() + ">"); return false; } try { YellowPunishTransaction yellowPunishTransaction = ConsensusTool.createYellowPunishTx(chain.getBestBlock(), member, currentRound); if (yellowPunishTransaction == yellowPunishTx) { return true; } else if (yellowPunishTransaction == null || yellowPunishTx == null) { BlockLog.debug("The yellow punish tx is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); // Log.error("The yellow punish tx is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); return false; } else if (!yellowPunishTransaction.getHash().equals(yellowPunishTx.getHash())) { BlockLog.debug("The yellow punish tx's hash is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); // Log.error("The yellow punish tx's hash is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); return false; } } catch (Exception e) { BlockLog.debug("The tx's wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex(), e); // Log.error("The tx's wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex(), e); return false; } return true; } #location 33 #vulnerability type NULL_DEREFERENCE
#fixed code private boolean verifyBaseTx(Block block, MeetingRound currentRound, MeetingMember member) { List<Transaction> txs = block.getTxs(); Transaction tx = txs.get(0); if (tx.getType() != TransactionConstant.TX_TYPE_COIN_BASE) { BlockLog.debug("Coinbase transaction order wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); // Log.error("Coinbase transaction order wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); return false; } YellowPunishTransaction yellowPunishTx = null; for (int i = 1; i < txs.size(); i++) { Transaction transaction = txs.get(i); if (transaction.getType() == TransactionConstant.TX_TYPE_COIN_BASE) { BlockLog.debug("Coinbase transaction more than one! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); // Log.error("Coinbase transaction more than one! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); return false; } if (null == yellowPunishTx && transaction.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) { yellowPunishTx = (YellowPunishTransaction) transaction; } else if (null != yellowPunishTx && transaction.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) { BlockLog.debug("Yellow punish transaction more than one! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); // Log.error("Yellow punish transaction more than one! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); return false; } } CoinBaseTransaction coinBaseTransaction = ConsensusTool.createCoinBaseTx(member, block.getTxs(), currentRound, block.getHeader().getHeight() + PocConsensusConstant.COINBASE_UNLOCK_HEIGHT); if (null == coinBaseTransaction || !tx.getHash().equals(coinBaseTransaction.getHash())) { BlockLog.debug("the coin base tx is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); Log.error("the coin base tx is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); return false; } try { YellowPunishTransaction yellowPunishTransaction = ConsensusTool.createYellowPunishTx(chain.getBestBlock(), member, currentRound); if (yellowPunishTransaction == yellowPunishTx) { return true; } else if (yellowPunishTransaction == null || yellowPunishTx == null) { BlockLog.debug("The yellow punish tx is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); // Log.error("The yellow punish tx is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); return false; } else if (!yellowPunishTransaction.getHash().equals(yellowPunishTx.getHash())) { BlockLog.debug("The yellow punish tx's hash is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); // Log.error("The yellow punish tx's hash is wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex()); return false; } } catch (Exception e) { BlockLog.debug("The tx's wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex(), e); // Log.error("The tx's wrong! height: " + block.getHeader().getHeight() + " , hash : " + block.getHeader().getHash().getDigestHex(), e); return false; } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @DbSession public void save(CoinData coinData, Transaction tx) throws NulsException { UtxoData utxoData = (UtxoData) coinData; List<UtxoInputPo> inputPoList = new ArrayList<>(); List<UtxoOutput> spends = new ArrayList<>(); List<UtxoOutputPo> spendPoList = new ArrayList<>(); List<TxAccountRelationPo> txRelations = new ArrayList<>(); Set<String> addressSet = new HashSet<>(); try { processDataInput(utxoData, inputPoList, spends, spendPoList, addressSet); List<UtxoOutputPo> outputPoList = new ArrayList<>(); for (int i = 0; i < utxoData.getOutputs().size(); i++) { UtxoOutput output = utxoData.getOutputs().get(i); output = ledgerCacheService.getUtxo(output.getKey()); if (output == null) { throw new NulsRuntimeException(ErrorCode.DATA_NOT_FOUND); } if (output.isConfirm() || OutPutStatusEnum.UTXO_SPENT == output.getStatus()) { Log.error("-----------------------------------save() output status is" + output.getStatus().name()); throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "use a not legal utxo"); } if (OutPutStatusEnum.UTXO_UNCONFIRM_CONSENSUS_LOCK == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_CONSENSUS_LOCK); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_TIME_LOCK == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_TIME_LOCK); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_UNSPEND); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND); } UtxoOutputPo outputPo = UtxoTransferTool.toOutputPojo(output); outputPoList.add(outputPo); addressSet.add(Address.fromHashs(output.getAddress()).getBase58()); } for (String address : addressSet) { TxAccountRelationPo relationPo = new TxAccountRelationPo(tx.getHash().getDigestHex(), address); txRelations.add(relationPo); } outputDataService.updateStatus(spendPoList); inputDataService.save(inputPoList); outputDataService.save(outputPoList); relationDataService.save(txRelations); afterSaveDatabase(spends, utxoData, tx); for (String address : addressSet) { UtxoTransactionTool.getInstance().calcBalance(address, true); } } catch (Exception e) { //rollback // Log.warn(e.getMessage(), e); // for (UtxoOutput output : utxoData.getOutputs()) { // ledgerCacheService.removeUtxo(output.getKey()); // } // for (UtxoOutput spend : spends) { // ledgerCacheService.updateUtxoStatus(spend.getKey(), UtxoOutput.UTXO_CONFIRM_LOCK, UtxoOutput.UTXO_SPENT); // } throw e; } } #location 37 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override @DbSession public void save(CoinData coinData, Transaction tx) throws NulsException { UtxoData utxoData = (UtxoData) coinData; List<UtxoInputPo> inputPoList = new ArrayList<>(); List<UtxoOutput> spends = new ArrayList<>(); List<UtxoOutputPo> spendPoList = new ArrayList<>(); List<TxAccountRelationPo> txRelations = new ArrayList<>(); Set<String> addressSet = new HashSet<>(); lock.lock(); try { processDataInput(utxoData, inputPoList, spends, spendPoList, addressSet); List<UtxoOutputPo> outputPoList = new ArrayList<>(); for (int i = 0; i < utxoData.getOutputs().size(); i++) { UtxoOutput output = utxoData.getOutputs().get(i); output = ledgerCacheService.getUtxo(output.getKey()); if (output == null) { throw new NulsRuntimeException(ErrorCode.DATA_NOT_FOUND); } if (output.isConfirm() || OutPutStatusEnum.UTXO_SPENT == output.getStatus()) { Log.error("-----------------------------------save() output status is" + output.getStatus().name()); throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "use a not legal utxo"); } if (OutPutStatusEnum.UTXO_UNCONFIRM_CONSENSUS_LOCK == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_CONSENSUS_LOCK); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_TIME_LOCK == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_TIME_LOCK); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_UNSPEND); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND); } UtxoOutputPo outputPo = UtxoTransferTool.toOutputPojo(output); outputPoList.add(outputPo); addressSet.add(Address.fromHashs(output.getAddress()).getBase58()); } for (String address : addressSet) { TxAccountRelationPo relationPo = new TxAccountRelationPo(tx.getHash().getDigestHex(), address); txRelations.add(relationPo); } outputDataService.updateStatus(spendPoList); inputDataService.save(inputPoList); outputDataService.save(outputPoList); relationDataService.save(txRelations); afterSaveDatabase(spends, utxoData, tx); for (String address : addressSet) { UtxoTransactionTool.getInstance().calcBalance(address, true); } } catch (Exception e) { //rollback // Log.warn(e.getMessage(), e); // for (UtxoOutput output : utxoData.getOutputs()) { // ledgerCacheService.removeUtxo(output.getKey()); // } // for (UtxoOutput spend : spends) { // ledgerCacheService.updateUtxoStatus(spend.getKey(), UtxoOutput.UTXO_CONFIRM_LOCK, UtxoOutput.UTXO_SPENT); // } throw e; } finally { lock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean addBlockHashResponse(String nodeId, BlockHashResponse response) { if (this.nodeIdList == null || !this.nodeIdList.contains(nodeId)) { return false; } if (!requesting) { return false; } if (response.getBestHeight() == 0 && NulsContext.getInstance().getBestHeight() > 0) { hashesMap.remove(nodeId); nodeIdList.remove(nodeId); return false; } if (hashesMap.get(nodeId) == null) { hashesMap.put(nodeId, response); } else { BlockHashResponse instance = hashesMap.get(nodeId); instance.merge(response); hashesMap.put(nodeId, instance); } if (response.getHeightList().get(response.getHeightList().size() - 1) < end) { return true; } String key = response.getBestHash().getDigestHex(); List<String> nodes = calcMap.get(key); if (null == nodes) { nodes = new ArrayList<>(); } if (!nodes.contains(nodeId)) { nodes.add(nodeId); } calcMap.put(key, nodes); calc(); return true; } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean addBlockHashResponse(String nodeId, BlockHashResponse response) { if (this.nodeIdList == null || !this.nodeIdList.contains(nodeId)) { return false; } if (!requesting) { return false; } if (response.getBestHeight() == 0 && NulsContext.getInstance().getBestHeight() > 0) { hashesMap.remove(nodeId); nodeIdList.remove(nodeId); return false; } if (hashesMap.get(nodeId) == null) { hashesMap.put(nodeId, response); } else { BlockHashResponse instance = hashesMap.get(nodeId); instance.merge(response); hashesMap.put(nodeId, instance); } // if (response.getHeightList().get(response.getHeightList().size() - 1) < end) { // return true; // } String key = response.getBestHash().getDigestHex(); List<String> nodes = calcMap.get(key); if (null == nodes) { nodes = new ArrayList<>(); } if (!nodes.contains(nodeId)) { nodes.add(nodeId); } calcMap.put(key, nodes); calc(); return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @DbSession public boolean saveBlock(Block block) throws IOException { BlockLog.debug("save block height:" + block.getHeader().getHeight() + ", preHash:" + block.getHeader().getPreHash() + " , hash:" + block.getHeader().getHash() + ", address:" + Address.fromHashs(block.getHeader().getPackingAddress())); BlockHeader bestBlockHeader = getLocalBestBlockHeader(); if(!bestBlockHeader.getHash().equals(block.getHeader().getPreHash())) { throw new NulsRuntimeException(ErrorCode.FAILED, "save blcok error , prehash is error , height: " + block.getHeader().getHeight() + " , hash: " + block.getHeader().getHash()); } List<Transaction> commitedList = new ArrayList<>(); for (int x = 0; x < block.getHeader().getTxCount(); x++) { Transaction tx = block.getTxs().get(x); tx.setIndex(x); tx.setBlockHeight(block.getHeader().getHeight()); try { tx.verifyWithException(); commitedList.add(tx); ledgerService.commitTx(tx, block); } catch (Exception e) { Log.error(e); this.rollback(commitedList); throw new NulsRuntimeException(e); } } ledgerService.saveTxList(block.getTxs()); blockStorageService.save(block); List<Transaction> localTxList = null; try { localTxList = this.ledgerService.getWaitingTxList(); } catch (Exception e) { Log.error(e); } if (null != localTxList && !localTxList.isEmpty()) { for (Transaction tx : localTxList) { try { ValidateResult result = ledgerService.conflictDetectTx(tx, block.getTxs()); if (result.isFailed()) { ledgerService.deleteLocalTx(tx.getHash().getDigestHex()); } } catch (NulsException e) { Log.error(e); } } } return true; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Override @DbSession public boolean saveBlock(Block block) throws IOException { BlockLog.debug("save block height:" + block.getHeader().getHeight() + ", preHash:" + block.getHeader().getPreHash() + " , hash:" + block.getHeader().getHash() + ", address:" + Address.fromHashs(block.getHeader().getPackingAddress())); BlockHeader bestBlockHeader = getLocalBestBlockHeader(); if((bestBlockHeader == null && block.getHeader().getHeight() != 0L) || (bestBlockHeader != null && !bestBlockHeader.getHash().equals(block.getHeader().getPreHash()))) { throw new NulsRuntimeException(ErrorCode.FAILED, "save blcok error , prehash is error , height: " + block.getHeader().getHeight() + " , hash: " + block.getHeader().getHash()); } List<Transaction> commitedList = new ArrayList<>(); for (int x = 0; x < block.getHeader().getTxCount(); x++) { Transaction tx = block.getTxs().get(x); tx.setIndex(x); tx.setBlockHeight(block.getHeader().getHeight()); try { tx.verifyWithException(); commitedList.add(tx); ledgerService.commitTx(tx, block); } catch (Exception e) { Log.error(e); this.rollback(commitedList); throw new NulsRuntimeException(e); } } ledgerService.saveTxList(block.getTxs()); blockStorageService.save(block); List<Transaction> localTxList = null; try { localTxList = this.ledgerService.getWaitingTxList(); } catch (Exception e) { Log.error(e); } if (null != localTxList && !localTxList.isEmpty()) { for (Transaction tx : localTxList) { try { ValidateResult result = ledgerService.conflictDetectTx(tx, block.getTxs()); if (result.isFailed()) { ledgerService.deleteLocalTx(tx.getHash().getDigestHex()); } } catch (NulsException e) { Log.error(e); } } } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void parse(NulsByteBuffer byteBuffer) throws NulsException { this.setHeader(byteBuffer.readNulsData(new EventHeader())); // version = new NulsVersion(byteBuffer.readShort()); bestBlockHeight = byteBuffer.readVarInt(); bestBlockHash = new String(byteBuffer.readByLengthByte()); nulsVersion = new String(byteBuffer.readByLengthByte()); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected void parse(NulsByteBuffer byteBuffer) throws NulsException { this.setHeader(byteBuffer.readNulsData(new EventHeader())); // version = new NulsVersion(byteBuffer.readShort()); bestBlockHeight = byteBuffer.readVarInt(); bestBlockHash = byteBuffer.readString(); nulsVersion = byteBuffer.readString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void requestTxGroup(NulsDigestData blockHash, String nodeId) { GetTxGroupRequest request = new GetTxGroupRequest(); GetTxGroupParam data = new GetTxGroupParam(); data.setBlockHash(blockHash); List<NulsDigestData> txHashList = new ArrayList<>(); SmallBlock smb = temporaryCacheManager.getSmallBlock(blockHash.getDigestHex()); for (NulsDigestData txHash : smb.getTxHashList()) { boolean exist = txCacheManager.txExist(txHash); if (!exist) { txHashList.add(txHash); } } if (txHashList.isEmpty()) { BlockHeader header = temporaryCacheManager.getBlockHeader(smb.getBlockHash().getDigestHex()); if (null == header) { return; } Block block = new Block(); block.setHeader(header); List<Transaction> txs = new ArrayList<>(); for (NulsDigestData txHash : smb.getTxHashList()) { Transaction tx = txCacheManager.getTx(txHash); if (null == tx) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR); } txs.add(tx); } block.setTxs(txs); ValidateResult<RedPunishData> vResult = block.verify(); if (null == vResult || vResult.isFailed()) { if (vResult.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) { RedPunishData redPunishData = vResult.getObject(); ConsensusMeetingRunner.putPunishData(redPunishData); } return; } blockManager.addBlock(block, false,nodeId); AssembledBlockNotice notice = new AssembledBlockNotice(); notice.setEventBody(header); eventBroadcaster.publishToLocal(notice); return; } data.setTxHashList(txHashList); request.setEventBody(data); tgRequest.put(blockHash.getDigestHex(), System.currentTimeMillis()); Integer value = tgRequestCount.get(blockHash.getDigestHex()); if (null == value) { value = 0; } tgRequestCount.put(blockHash.getDigestHex(), 1 + value); if (StringUtils.isBlank(nodeId)) { eventBroadcaster.broadcastAndCache(request, false); } else { eventBroadcaster.sendToNode(request, nodeId); } } #location 32 #vulnerability type NULL_DEREFERENCE
#fixed code public void requestTxGroup(NulsDigestData blockHash, String nodeId) { GetTxGroupRequest request = new GetTxGroupRequest(); GetTxGroupParam data = new GetTxGroupParam(); data.setBlockHash(blockHash); List<NulsDigestData> txHashList = new ArrayList<>(); SmallBlock smb = temporaryCacheManager.getSmallBlock(blockHash.getDigestHex()); for (NulsDigestData txHash : smb.getTxHashList()) { boolean exist = txCacheManager.txExist(txHash); if (!exist) { txHashList.add(txHash); } } if (txHashList.isEmpty()) { BlockHeader header = temporaryCacheManager.getBlockHeader(smb.getBlockHash().getDigestHex()); if (null == header) { return; } Block block = new Block(); block.setHeader(header); List<Transaction> txs = new ArrayList<>(); for (NulsDigestData txHash : smb.getTxHashList()) { Transaction tx = txCacheManager.getTx(txHash); if (null == tx) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR); } txs.add(tx); } block.setTxs(txs); ValidateResult vResult = block.verify(); if (vResult.isFailed()&&vResult.getErrorCode()!=ErrorCode.ORPHAN_BLOCK&&vResult.getErrorCode()!=ErrorCode.ORPHAN_TX) { return; } blockManager.addBlock(block, false,nodeId); AssembledBlockNotice notice = new AssembledBlockNotice(); notice.setEventBody(header); eventBroadcaster.publishToLocal(notice); return; } data.setTxHashList(txHashList); request.setEventBody(data); tgRequest.put(blockHash.getDigestHex(), System.currentTimeMillis()); Integer value = tgRequestCount.get(blockHash.getDigestHex()); if (null == value) { value = 0; } tgRequestCount.put(blockHash.getDigestHex(), 1 + value); if (StringUtils.isBlank(nodeId)) { eventBroadcaster.broadcastAndCache(request, false); } else { eventBroadcaster.sendToNode(request, nodeId); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public PocMeetingRound getRound(long preRoundIndex, long roundIndex, boolean needPreRound) { PocMeetingRound round = ROUND_MAP.get(roundIndex); Block preRoundFirstBlock = null; BlockRoundData preRoundData = null; if (null == round) { Block bestBlock = getBestBlock(); BlockRoundData nowRoundData = new BlockRoundData(bestBlock.getHeader().getExtend()); if (nowRoundData.getRoundIndex() >= preRoundIndex) { preRoundFirstBlock = getBlockService().getPreRoundFirstBlock(preRoundIndex); if (null == preRoundFirstBlock) { return null; } preRoundData = new BlockRoundData(preRoundFirstBlock.getHeader().getExtend()); round = calcRound(preRoundFirstBlock.getHeader().getHeight(), roundIndex, preRoundData.getRoundEndTime(), false); if (roundIndex > (preRoundData.getRoundIndex() + 1)) { long roundTime = PocConsensusConstant.BLOCK_TIME_INTERVAL_SECOND * 1000L * round.getMemberCount(); long startTime = round.getStartTime() + (roundIndex - (preRoundData.getRoundIndex() + 1)) * roundTime; round.setStartTime(startTime); List<PocMeetingMember> memberList = round.getMemberList(); for (PocMeetingMember member : memberList) { member.setRoundStartTime(round.getStartTime()); } Collections.sort(memberList); round.setMemberList(memberList); } ROUND_MAP.put(round.getIndex(), round); } else { return null; } } if (needPreRound && round.getPreRound() == null) { if (null == preRoundFirstBlock) { Block firstBlock = getBlockService().getPreRoundFirstBlock(preRoundIndex); if (null == firstBlock) { return null; } preRoundFirstBlock = firstBlock; preRoundData = new BlockRoundData(preRoundFirstBlock.getHeader().getExtend()); } if (preRoundFirstBlock.getHeader().getHeight() == 0) { round.setPreRound(calcRound(0, 1, preRoundData.getRoundStartTime(), false)); return round; } Block preblock = getBlockService().getBlock(preRoundFirstBlock.getHeader().getPreHash().getDigestHex()); if (null == preblock) { return null; } BlockRoundData preBlockRoundData = new BlockRoundData(preblock.getHeader().getExtend()); round.setPreRound(getRound(preBlockRoundData.getRoundIndex(), preRoundIndex, false)); } StringBuilder str = new StringBuilder(); for (PocMeetingMember member : round.getMemberList()) { str.append(member.getPackingAddress()); str.append(" ,order:" + member.getPackingIndexOfRound()); str.append(",packEndTime:" + new Date(member.getPackEndTime())); str.append("\n"); } if(null==round.getPreRound()){ BlockLog.info("calc new round:index:" + round.getIndex() + " , start:" + new Date(round.getStartTime()) + ", netTime:(" + new Date(TimeService.currentTimeMillis()).toString() + ") , members:\n :" + str); }else { BlockLog.info("calc new round:index:" + round.getIndex() + " ,preIndex:" + round.getPreRound().getIndex() + " , start:" + new Date(round.getStartTime()) + ", netTime:(" + new Date(TimeService.currentTimeMillis()).toString() + ") , members:\n :" + str); } return round; } #location 33 #vulnerability type NULL_DEREFERENCE
#fixed code public PocMeetingRound getRound(long preRoundIndex, long roundIndex, boolean needPreRound) { PocMeetingRound round = ROUND_MAP.get(roundIndex); Block preRoundFirstBlock = null; BlockRoundData preRoundData = null; if (null == round) { Block bestBlock = getBestBlock(); BlockRoundData nowRoundData = new BlockRoundData(bestBlock.getHeader().getExtend()); if (nowRoundData.getRoundIndex() >= preRoundIndex) { preRoundFirstBlock = getBlockService().getPreRoundFirstBlock(preRoundIndex); if (null == preRoundFirstBlock) { return null; } preRoundData = new BlockRoundData(preRoundFirstBlock.getHeader().getExtend()); round = calcRound(preRoundFirstBlock.getHeader().getHeight(), roundIndex, preRoundData.getRoundEndTime(), false); if (roundIndex > (preRoundData.getRoundIndex() + 1)) { long roundTime = PocConsensusConstant.BLOCK_TIME_INTERVAL_SECOND * 1000L * round.getMemberCount(); long startTime = round.getStartTime() + (roundIndex - (preRoundData.getRoundIndex() + 1)) * roundTime; round.setStartTime(startTime); List<PocMeetingMember> memberList = round.getMemberList(); for (PocMeetingMember member : memberList) { member.setRoundStartTime(round.getStartTime()); } Collections.sort(memberList); round.setMemberList(memberList); } ROUND_MAP.put(round.getIndex(), round); } else { return null; } } if (needPreRound && round.getPreRound() == null) { if (null == preRoundFirstBlock) { Block firstBlock = getBlockService().getPreRoundFirstBlock(preRoundIndex); if (null == firstBlock) { return null; } preRoundFirstBlock = firstBlock; preRoundData = new BlockRoundData(preRoundFirstBlock.getHeader().getExtend()); } if (preRoundFirstBlock.getHeader().getHeight() == 0) { round.setPreRound(calcRound(0, 1, preRoundData.getRoundStartTime(), false)); return round; } Block preblock = getBlockService().getBlock(preRoundFirstBlock.getHeader().getPreHash().getDigestHex()); if (null == preblock) { return null; } BlockRoundData preBlockRoundData = new BlockRoundData(preblock.getHeader().getExtend()); round.setPreRound(getRound(preBlockRoundData.getRoundIndex(), preRoundIndex, false)); } StringBuilder str = new StringBuilder(); for (PocMeetingMember member : round.getMemberList()) { str.append(member.getPackingAddress()); str.append(" ,order:" + member.getPackingIndexOfRound()); str.append(",packEndTime:" + new Date(member.getPackEndTime())); str.append("\n"); } if(null==round.getPreRound()){ BlockLog.debug("calc new round:index:" + round.getIndex() + " , start:" + new Date(round.getStartTime()) + ", netTime:(" + new Date(TimeService.currentTimeMillis()).toString() + ") , members:\n :" + str); }else { BlockLog.debug("calc new round:index:" + round.getIndex() + " ,preIndex:" + round.getPreRound().getIndex() + " , start:" + new Date(round.getStartTime()) + ", netTime:(" + new Date(TimeService.currentTimeMillis()).toString() + ") , members:\n :" + str); } return round; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public PocMeetingRound getCurrentRound() { Block currentBlock = NulsContext.getInstance().getBestBlock(); BlockRoundData currentRoundData = new BlockRoundData(currentBlock.getHeader().getExtend()); PocMeetingRound round = ROUND_MAP.get(currentRoundData.getRoundIndex()); if (null == round) { round = resetCurrentMeetingRound(); } return round; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public PocMeetingRound getCurrentRound() { return currentRound; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public BlockInfo request(long start, long end, long split) { lock.lock(); this.startTime = TimeService.currentTimeMillis(); requesting = true; hashesMap.clear(); calcMap.clear(); this.start = start; this.end = end; this.split = split; GetBlocksHashRequest event = new GetBlocksHashRequest(start, end, split); nodeIdList = this.eventBroadcaster.broadcastAndCache(event, false); if (nodeIdList.isEmpty()) { Log.error("get best height from net faild!"); lock.unlock(); throw new NulsRuntimeException(ErrorCode.NET_MESSAGE_ERROR, "broadcast faild!"); } return this.getBlockInfo(); } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public BlockInfo request(long start, long end, long split) { lock.lock(); this.startTime = TimeService.currentTimeMillis(); requesting = true; hashesMap.clear(); calcMap.clear(); this.start = start; this.end = end; this.split = split; GetBlocksHashRequest event = new GetBlocksHashRequest(start, end, split); nodeIdList = this.eventBroadcaster.broadcastAndCache(event, false); if (nodeIdList.isEmpty()) { Log.error("get best height from net faild!"); lock.unlock(); return null; } return this.getBlockInfo(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Transaction getTx(NulsDigestData hash) { TransactionLocalPo localPo = localTxDao.get(hash.getDigestHex()); if (localPo != null) { try { Transaction tx = UtxoTransferTool.toTransaction(localPo); return tx; } catch (Exception e) { Log.error(e); } } TransactionPo po = txDao.get(hash.getDigestHex()); if (null == po) { return null; } try { Transaction tx = UtxoTransferTool.toTransaction(po); return tx; } catch (Exception e) { Log.error(e); } return null; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public Transaction getTx(NulsDigestData hash) { TransactionPo po = txDao.get(hash.getDigestHex()); if (null != po) { try { Transaction tx = UtxoTransferTool.toTransaction(po); return tx; } catch (Exception e) { Log.error(e); } } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public NetworkEventResult process(BaseEvent networkEvent, Node node) { VersionEvent event = (VersionEvent) networkEvent; String key = event.getHeader().getEventType() + "-" + node.getId(); if (cacheService.existEvent(key)) { Log.info("----------VersionEventHandler cacheService existEvent--------"); getNetworkService().removeNode(node.getId()); return null; } cacheService.putEvent(key, event, true); if (event.getBestBlockHeight() < 0) { throw new NetworkMessageException(ErrorCode.NET_MESSAGE_ERROR); } node.setVersionMessage(event); if (!node.isHandShake()) { node.setStatus(Node.HANDSHAKE); node.setPort(event.getExternalPort()); node.setLastTime(TimeService.currentTimeMillis()); getNodeDao().saveChange(NodeTransferTool.toPojo(node)); } return null; } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public NetworkEventResult process(BaseEvent networkEvent, Node node) { VersionEvent event = (VersionEvent) networkEvent; // String key = event.getHeader().getEventType() + "-" + node.getId(); // if (cacheService.existEvent(key)) { // Log.info("----------VersionEventHandler cacheService existEvent--------"); // getNetworkService().removeNode(node.getId()); // return null; // } // cacheService.putEvent(key, event, true); if (event.getBestBlockHeight() < 0) { throw new NetworkMessageException(ErrorCode.NET_MESSAGE_ERROR); } node.setVersionMessage(event); if (!node.isHandShake()) { node.setStatus(Node.HANDSHAKE); node.setPort(event.getExternalPort()); node.setLastTime(TimeService.currentTimeMillis()); getNodeDao().saveChange(NodeTransferTool.toPojo(node)); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean saveLocalTx(Transaction tx) throws IOException { try { ValidateResult validateResult = this.conflictDetectTx(tx, this.getWaitingTxList()); if (validateResult.isFailed()) { throw new NulsRuntimeException(validateResult.getErrorCode(), validateResult.getMessage()); } } catch (Exception e) { Log.error(e); throw new NulsRuntimeException(e); } TransactionLocalPo localPo = UtxoTransferTool.toLocalTransactionPojo(tx); localPo.setTxStatus(TransactionLocalPo.UNCONFIRM); localTxDao.save(localPo); // save relation if (tx instanceof AbstractCoinTransaction) { AbstractCoinTransaction abstractTx = (AbstractCoinTransaction) tx; UtxoData utxoData = (UtxoData) abstractTx.getCoinData(); if (utxoData.getInputs() != null && !utxoData.getInputs().isEmpty()) { UtxoInput input = utxoData.getInputs().get(0); UtxoOutput output = input.getFrom(); TxAccountRelationPo relationPo = new TxAccountRelationPo(); relationPo.setTxHash(tx.getHash().getDigestHex()); relationPo.setAddress(output.getAddress()); relationDataService.save(relationPo); } } // if (tx instanceof AbstractCoinTransaction) { // AbstractCoinTransaction abstractTx = (AbstractCoinTransaction) tx; // UtxoData utxoData = (UtxoData) abstractTx.getCoinData(); // // for (UtxoOutput output : utxoData.getOutputs()) { // if (output.isUsable() && NulsContext.LOCAL_ADDRESS_LIST.contains(output.getAddress())) { // output.setTxHash(tx.getHash()); // ledgerCacheService.putUtxo(output.getKey(), output, false); // } // } // } return true; } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean saveLocalTx(Transaction tx) throws IOException { try { ValidateResult validateResult = this.conflictDetectTx(tx, this.getWaitingTxList()); if (validateResult.isFailed()) { throw new NulsRuntimeException(validateResult.getErrorCode(), validateResult.getMessage()); } } catch (Exception e) { Log.error(e); throw new NulsRuntimeException(e); } TransactionLocalPo localPo = UtxoTransferTool.toLocalTransactionPojo(tx); localPo.setTxStatus(TransactionLocalPo.UNCONFIRM); localTxDao.save(localPo); ledgerCacheService.putLocalTx(tx); // save relation if (tx instanceof AbstractCoinTransaction) { AbstractCoinTransaction abstractTx = (AbstractCoinTransaction) tx; UtxoData utxoData = (UtxoData) abstractTx.getCoinData(); if (utxoData.getInputs() != null && !utxoData.getInputs().isEmpty()) { UtxoInput input = utxoData.getInputs().get(0); UtxoOutput output = input.getFrom(); TxAccountRelationPo relationPo = new TxAccountRelationPo(); relationPo.setTxHash(tx.getHash().getDigestHex()); relationPo.setAddress(output.getAddress()); relationDataService.save(relationPo); } } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Result transfer(byte[] from, byte[] to, Na values, String password, String remark) { try { AssertUtil.canNotEmpty(from, "the from address can not be empty"); AssertUtil.canNotEmpty(to, "the to address can not be empty"); AssertUtil.canNotEmpty(values, "the amount can not be empty"); if (values.isZero() || values.isLessThan(Na.ZERO)) { return Result.getFailed("amount error"); } Result<Account> accountResult = accountService.getAccount(from); if (accountResult.isFailed()) { return accountResult; } Account account = accountResult.getData(); if (accountService.isEncrypted(account).isSuccess()) { AssertUtil.canNotEmpty(password, "the password can not be empty"); Result passwordResult = accountService.validPassword(account, password); if (passwordResult.isFailed()) { return passwordResult; } } TransferTransaction tx = new TransferTransaction(); if (StringUtils.isNotBlank(remark)) { try { tx.setRemark(remark.getBytes(NulsConfig.DEFAULT_ENCODING)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } tx.setTime(TimeService.currentTimeMillis()); CoinData coinData = new CoinData(); Coin toCoin = new Coin(to, values); coinData.getTo().add(toCoin); CoinDataResult coinDataResult = getCoinData(from, values, tx.size() + P2PKHScriptSig.DEFAULT_SERIALIZE_LENGTH); if (!coinDataResult.isEnough()) { return Result.getFailed(LedgerErrorCode.BALANCE_NOT_ENOUGH); } coinData.setFrom(coinDataResult.getCoinList()); if (coinDataResult.getChange() != null) { coinData.getTo().add(coinDataResult.getChange()); } tx.setCoinData(coinData); tx.setHash(NulsDigestData.calcDigestData(tx.serialize())); P2PKHScriptSig sig = new P2PKHScriptSig(); sig.setPublicKey(account.getPubKey()); sig.setSignData(accountService.signData(tx.getHash().serialize(), account, password)); tx.setScriptSig(sig.serialize()); ValidateResult result1 = tx.verify(); if (result1.isFailed()) { return result1; } result1 = this.ledgerService.verifyCoinData(tx, this.getAllUnconfirmedTransaction().getData()); if (result1.isFailed()) { return result1; } Result saveResult = saveUnconfirmedTransaction(tx); if (saveResult.isFailed()) { return saveResult; } Result sendResult = this.transactionService.broadcastTx(tx); if (sendResult.isFailed()) { return sendResult; } return Result.getSuccess().setData(tx.getHash().getDigestHex()); } catch (IOException e) { Log.error(e); return Result.getFailed(e.getMessage()); } catch (NulsException e) { Log.error(e); return Result.getFailed(e.getErrorCode()); } } #location 53 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public Result transfer(byte[] from, byte[] to, Na values, String password, String remark) { try { AssertUtil.canNotEmpty(from, "the from address can not be empty"); AssertUtil.canNotEmpty(to, "the to address can not be empty"); AssertUtil.canNotEmpty(values, "the amount can not be empty"); if (values.isZero() || values.isLessThan(Na.ZERO)) { return Result.getFailed("amount error"); } Result<Account> accountResult = accountService.getAccount(from); if (accountResult.isFailed()) { return accountResult; } Account account = accountResult.getData(); if (accountService.isEncrypted(account).isSuccess()) { AssertUtil.canNotEmpty(password, "the password can not be empty"); Result passwordResult = accountService.validPassword(account, password); if (passwordResult.isFailed()) { return passwordResult; } } TransferTransaction tx = new TransferTransaction(); if (StringUtils.isNotBlank(remark)) { try { tx.setRemark(remark.getBytes(NulsConfig.DEFAULT_ENCODING)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } tx.setTime(TimeService.currentTimeMillis()); CoinData coinData = new CoinData(); Coin toCoin = new Coin(to, values); coinData.getTo().add(toCoin); CoinDataResult coinDataResult = getCoinData(from, values, tx.size() + P2PKHScriptSig.DEFAULT_SERIALIZE_LENGTH); if (!coinDataResult.isEnough()) { return Result.getFailed(LedgerErrorCode.BALANCE_NOT_ENOUGH); } coinData.setFrom(coinDataResult.getCoinList()); if (coinDataResult.getChange() != null) { coinData.getTo().add(coinDataResult.getChange()); } tx.setCoinData(coinData); tx.setHash(NulsDigestData.calcDigestData(tx.serialize())); P2PKHScriptSig sig = new P2PKHScriptSig(); sig.setPublicKey(account.getPubKey()); sig.setSignData(accountService.signData(tx.getHash().serialize(), account, password)); tx.setScriptSig(sig.serialize()); Result saveResult = saveUnconfirmedTransaction(tx); if (saveResult.isFailed()) { return saveResult; } Result sendResult = this.transactionService.broadcastTx(tx); if (sendResult.isFailed()) { return sendResult; } return Result.getSuccess().setData(tx.getHash().getDigestHex()); } catch (IOException e) { Log.error(e); return Result.getFailed(e.getMessage()); } catch (NulsException e) { Log.error(e); return Result.getFailed(e.getErrorCode()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean processing(long height) { if (chainList.isEmpty()) { return false; } lock.lock(); try { List<String> hashList = this.getHashList(height); if (hashList.size() == 1) { return true; } if (hashList.isEmpty()) { Log.warn("lost a block:" + height); return false; } List<BlockHeaderChain> longestChainList = new ArrayList<>(); int size = 0; for (BlockHeaderChain chain : chainList) { if (chain.size() == size) { longestChainList.add(chain); } else if (chain.size() > size && size == 0) { longestChainList.add(chain); } else if (chain.size() > size && size != 0) { longestChainList.clear(); longestChainList.add(chain); } } if (longestChainList.size() != 1) { return false; } chainList = longestChainList; return true; } finally { lock.unlock(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean processing(long height) { if (chainList.isEmpty()) { return false; } List<String> hashList = this.getHashList(height); if (hashList.size() == 1) { return true; } if (hashList.isEmpty()) { Log.warn("lost a block:" + height); return false; } int maxSize = 0; int secondMaxSize = 0; for (BlockHeaderChain chain : chainList) { int size = chain.size(); if (size > maxSize) { secondMaxSize = maxSize; maxSize = size; } else if (size > secondMaxSize) { secondMaxSize = size; } else if (size == maxSize) { secondMaxSize = size; } } if (maxSize <= (secondMaxSize + 6)) { return false; } for (int i = chainList.size() - 1; i >= 0; i--) { if (chainList.size() < maxSize) { chainList.remove(i); } } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void reset() { this.needReSet = true; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void reset() { lock.lock();try{ this.needReSet = true; ROUND_MAP.clear(); this.init();}finally { lock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<Transaction> getTxList(Block block, List<NulsDigestData> txHashList) { List<Transaction> txList = new ArrayList<>(); Map<String, Integer> allTxMap = new HashMap<>(); for (int i = 0; i < block.getHeader().getTxCount(); i++) { Transaction tx = block.getTxs().get(i); allTxMap.put(tx.getHash().getDigestHex(), i); } for (NulsDigestData hash : txHashList) { txList.add(block.getTxs().get(allTxMap.get(hash.getDigestHex()))); } if (txList.size() != txHashList.size()) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR); } return txList; } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code private List<Transaction> getTxList(Block block, List<NulsDigestData> txHashList) { List<Transaction> txList = new ArrayList<>(); for (Transaction tx : block.getTxs()) { if (txHashList.contains(tx.getHash())) { txList.add(tx); } } if (txList.size() != txHashList.size()) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR); } return txList; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onMessage(GetBlockRequest message, Node fromNode) throws NulsException { GetBlockDataParam param = message.getMsgBody(); if (param.getSize() > MAX_SIZE) { return; } if (param.getSize() == 1) { Block block = null; Result<Block> result = this.blockService.getBlock(param.getStartHash()); if (result.isFailed()) { sendNotFound(param.getStartHash(), fromNode); return; } block = result.getData(); sendBlock(block, fromNode); return; } Block chainStartBlock = null; Result<Block> blockResult = this.blockService.getBlock(param.getStartHash()); if (blockResult.isFailed()) { sendNotFound(param.getStartHash(), fromNode); return; } else { chainStartBlock = blockResult.getData(); } Block chainEndBlock = null; blockResult = this.blockService.getBlock(param.getEndHash()); if (blockResult.isFailed()) { sendNotFound(param.getEndHash(), fromNode); return; } else { chainEndBlock = blockResult.getData(); } if (chainEndBlock.getHeader().getHeight() < chainStartBlock.getHeader().getHeight()) { return; } long end = param.getStart() + param.getSize() - 1; if (chainStartBlock.getHeader().getHeight() > param.getStart() || chainEndBlock.getHeader().getHeight() < end) { sendNotFound(param.getStartHash(), fromNode); return; } Block block = chainEndBlock; while (true) { this.sendBlock(block, fromNode); if (block.getHeader().getHash().equals(chainStartBlock.getHeader().getHash())) { break; } if (block.getHeader().getPreHash().equals(chainStartBlock.getHeader().getHash())) { block = chainStartBlock; continue; } block = blockService.getBlock(block.getHeader().getPreHash()).getData(); } } #location 46 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void onMessage(GetBlockRequest message, Node fromNode) { BlockSendThread.offer(message, fromNode); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void init() { //load five(CACHE_COUNT) round from db on the start time ; Block bestBlock = getBestBlock(); BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend()); for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) { Block firstBlock = getBlockService().getPreRoundFirstBlock(i - 1); BlockRoundData thisRoundData = new BlockRoundData(firstBlock.getHeader().getExtend()); PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, thisRoundData.getRoundStartTime()); ROUND_MAP.put(round.getIndex(), round); Log.debug("load the round data index:{}", round.getIndex()); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void init() { //load five(CACHE_COUNT) round from db on the start time ; Block bestBlock = getBestBlock(); BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend()); for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) { Block firstBlock = getBlockService().getPreRoundFirstBlock(i - 1); BlockRoundData preRoundData = new BlockRoundData(firstBlock.getHeader().getExtend()); PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, preRoundData.getRoundEndTime()); ROUND_MAP.put(round.getIndex(), round); Log.debug("load the round data index:{}", round.getIndex()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void requestTxGroup(NulsDigestData blockHash, String nodeId) { GetTxGroupRequest request = new GetTxGroupRequest(); GetTxGroupParam data = new GetTxGroupParam(); data.setBlockHash(blockHash); List<NulsDigestData> txHashList = new ArrayList<>(); SmallBlock smb = temporaryCacheManager.getSmallBlock(blockHash.getDigestHex()); for (NulsDigestData txHash : smb.getTxHashList()) { boolean exist = txCacheManager.txExist(txHash); if (!exist) { txHashList.add(txHash); } } if (txHashList.isEmpty()) { BlockHeader header = temporaryCacheManager.getBlockHeader(smb.getBlockHash().getDigestHex()); if (null == header) { return; } Block block = new Block(); block.setHeader(header); List<Transaction> txs = new ArrayList<>(); for (NulsDigestData txHash : smb.getTxHashList()) { Transaction tx = txCacheManager.getTx(txHash); if (null == tx) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR); } txs.add(tx); } block.setTxs(txs); ValidateResult<RedPunishData> vResult = block.verify(); if (null == vResult || vResult.isFailed()) { if (vResult.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) { RedPunishData redPunishData = vResult.getObject(); ConsensusMeetingRunner.putPunishData(redPunishData); } return; } blockManager.addBlock(block, false,nodeId); AssembledBlockNotice notice = new AssembledBlockNotice(); notice.setEventBody(header); eventBroadcaster.publishToLocal(notice); return; } data.setTxHashList(txHashList); request.setEventBody(data); tgRequest.put(blockHash.getDigestHex(), System.currentTimeMillis()); Integer value = tgRequestCount.get(blockHash.getDigestHex()); if (null == value) { value = 0; } tgRequestCount.put(blockHash.getDigestHex(), 1 + value); if (StringUtils.isBlank(nodeId)) { eventBroadcaster.broadcastAndCache(request, false); } else { eventBroadcaster.sendToNode(request, nodeId); } } #location 34 #vulnerability type NULL_DEREFERENCE
#fixed code public void requestTxGroup(NulsDigestData blockHash, String nodeId) { GetTxGroupRequest request = new GetTxGroupRequest(); GetTxGroupParam data = new GetTxGroupParam(); data.setBlockHash(blockHash); List<NulsDigestData> txHashList = new ArrayList<>(); SmallBlock smb = temporaryCacheManager.getSmallBlock(blockHash.getDigestHex()); for (NulsDigestData txHash : smb.getTxHashList()) { boolean exist = txCacheManager.txExist(txHash); if (!exist) { txHashList.add(txHash); } } if (txHashList.isEmpty()) { BlockHeader header = temporaryCacheManager.getBlockHeader(smb.getBlockHash().getDigestHex()); if (null == header) { return; } Block block = new Block(); block.setHeader(header); List<Transaction> txs = new ArrayList<>(); for (NulsDigestData txHash : smb.getTxHashList()) { Transaction tx = txCacheManager.getTx(txHash); if (null == tx) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR); } txs.add(tx); } block.setTxs(txs); ValidateResult vResult = block.verify(); if (vResult.isFailed()&&vResult.getErrorCode()!=ErrorCode.ORPHAN_BLOCK&&vResult.getErrorCode()!=ErrorCode.ORPHAN_TX) { return; } blockManager.addBlock(block, false,nodeId); AssembledBlockNotice notice = new AssembledBlockNotice(); notice.setEventBody(header); eventBroadcaster.publishToLocal(notice); return; } data.setTxHashList(txHashList); request.setEventBody(data); tgRequest.put(blockHash.getDigestHex(), System.currentTimeMillis()); Integer value = tgRequestCount.get(blockHash.getDigestHex()); if (null == value) { value = 0; } tgRequestCount.put(blockHash.getDigestHex(), 1 + value); if (StringUtils.isBlank(nodeId)) { eventBroadcaster.broadcastAndCache(request, false); } else { eventBroadcaster.sendToNode(request, nodeId); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @DbSession public void save(CoinData coinData, Transaction tx) throws NulsException { UtxoData utxoData = (UtxoData) coinData; List<UtxoInputPo> inputPoList = new ArrayList<>(); List<UtxoOutput> spends = new ArrayList<>(); List<UtxoOutputPo> spendPoList = new ArrayList<>(); List<TxAccountRelationPo> txRelations = new ArrayList<>(); Set<String> addressSet = new HashSet<>(); try { processDataInput(utxoData, inputPoList, spends, spendPoList, addressSet); List<UtxoOutputPo> outputPoList = new ArrayList<>(); for (int i = 0; i < utxoData.getOutputs().size(); i++) { UtxoOutput output = utxoData.getOutputs().get(i); output = ledgerCacheService.getUtxo(output.getKey()); if (output == null) { throw new NulsRuntimeException(ErrorCode.DATA_NOT_FOUND); } if (output.isConfirm() || OutPutStatusEnum.UTXO_SPENT == output.getStatus()) { Log.error("-----------------------------------save() output status is" + output.getStatus().name()); throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "use a not legal utxo"); } if (OutPutStatusEnum.UTXO_UNCONFIRM_CONSENSUS_LOCK == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_CONSENSUS_LOCK); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_TIME_LOCK == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_TIME_LOCK); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_UNSPEND); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND); } UtxoOutputPo outputPo = UtxoTransferTool.toOutputPojo(output); outputPoList.add(outputPo); addressSet.add(Address.fromHashs(output.getAddress()).getBase58()); } for (String address : addressSet) { TxAccountRelationPo relationPo = new TxAccountRelationPo(tx.getHash().getDigestHex(), address); txRelations.add(relationPo); } outputDataService.updateStatus(spendPoList); inputDataService.save(inputPoList); outputDataService.save(outputPoList); relationDataService.save(txRelations); afterSaveDatabase(spends, utxoData, tx); for (String address : addressSet) { UtxoTransactionTool.getInstance().calcBalance(address, true); } } catch (Exception e) { //rollback // Log.warn(e.getMessage(), e); // for (UtxoOutput output : utxoData.getOutputs()) { // ledgerCacheService.removeUtxo(output.getKey()); // } // for (UtxoOutput spend : spends) { // ledgerCacheService.updateUtxoStatus(spend.getKey(), UtxoOutput.UTXO_CONFIRM_LOCK, UtxoOutput.UTXO_SPENT); // } throw e; } } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override @DbSession public void save(CoinData coinData, Transaction tx) throws NulsException { UtxoData utxoData = (UtxoData) coinData; List<UtxoInputPo> inputPoList = new ArrayList<>(); List<UtxoOutput> spends = new ArrayList<>(); List<UtxoOutputPo> spendPoList = new ArrayList<>(); List<TxAccountRelationPo> txRelations = new ArrayList<>(); Set<String> addressSet = new HashSet<>(); lock.lock(); try { processDataInput(utxoData, inputPoList, spends, spendPoList, addressSet); List<UtxoOutputPo> outputPoList = new ArrayList<>(); for (int i = 0; i < utxoData.getOutputs().size(); i++) { UtxoOutput output = utxoData.getOutputs().get(i); output = ledgerCacheService.getUtxo(output.getKey()); if (output == null) { throw new NulsRuntimeException(ErrorCode.DATA_NOT_FOUND); } if (output.isConfirm() || OutPutStatusEnum.UTXO_SPENT == output.getStatus()) { Log.error("-----------------------------------save() output status is" + output.getStatus().name()); throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "use a not legal utxo"); } if (OutPutStatusEnum.UTXO_UNCONFIRM_CONSENSUS_LOCK == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_CONSENSUS_LOCK); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_TIME_LOCK == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_TIME_LOCK); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_UNSPEND); } else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND == output.getStatus()) { output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND); } UtxoOutputPo outputPo = UtxoTransferTool.toOutputPojo(output); outputPoList.add(outputPo); addressSet.add(Address.fromHashs(output.getAddress()).getBase58()); } for (String address : addressSet) { TxAccountRelationPo relationPo = new TxAccountRelationPo(tx.getHash().getDigestHex(), address); txRelations.add(relationPo); } outputDataService.updateStatus(spendPoList); inputDataService.save(inputPoList); outputDataService.save(outputPoList); relationDataService.save(txRelations); afterSaveDatabase(spends, utxoData, tx); for (String address : addressSet) { UtxoTransactionTool.getInstance().calcBalance(address, true); } } catch (Exception e) { //rollback // Log.warn(e.getMessage(), e); // for (UtxoOutput output : utxoData.getOutputs()) { // ledgerCacheService.removeUtxo(output.getKey()); // } // for (UtxoOutput spend : spends) { // ledgerCacheService.updateUtxoStatus(spend.getKey(), UtxoOutput.UTXO_CONFIRM_LOCK, UtxoOutput.UTXO_SPENT); // } throw e; } finally { lock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onEvent(SmallBlockEvent event, String fromId) { ValidateResult result = event.getEventBody().verify(); if (result.isFailed()) { return; } temporaryCacheManager.cacheSmallBlock(event.getEventBody()); downloadDataUtils.removeSmallBlock(event.getEventBody().getBlockHash().getDigestHex()); GetTxGroupRequest request = new GetTxGroupRequest(); GetTxGroupParam param = new GetTxGroupParam(); param.setBlockHash(event.getEventBody().getBlockHash()); for (NulsDigestData hash : event.getEventBody().getTxHashList()) { if (!receivedTxCacheManager.txExist(hash) && !orphanTxCacheManager.txExist(hash)) { param.addHash(hash); } } if (param.getTxHashList().isEmpty()) { BlockHeader header = temporaryCacheManager.getBlockHeader(event.getEventBody().getBlockHash().getDigestHex()); if (null == header) { return; } Block block = new Block(); block.setHeader(header); List<Transaction> txs = new ArrayList<>(); for (NulsDigestData txHash : event.getEventBody().getTxHashList()) { Transaction tx = receivedTxCacheManager.getTx(txHash); if (null == tx) { tx = orphanTxCacheManager.getTx(txHash); } if (null == tx) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR); } txs.add(tx); } block.setTxs(txs); ValidateResult<RedPunishData> vResult = block.verify(); if (null == vResult || (vResult.isFailed() && vResult.getErrorCode() != ErrorCode.ORPHAN_TX)) { if (vResult.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) { RedPunishData data = vResult.getObject(); ConsensusMeetingRunner.putPunishData(data); networkService.blackNode(fromId, NodePo.BLACK); } else { networkService.removeNode(fromId, NodePo.YELLOW); } return; } blockManager.addBlock(block, false, fromId); downloadDataUtils.removeTxGroup(block.getHeader().getHash().getDigestHex()); BlockHeaderEvent headerEvent = new BlockHeaderEvent(); headerEvent.setEventBody(header); eventBroadcaster.broadcastHashAndCacheAysn(headerEvent, false, fromId); return; } request.setEventBody(param); this.eventBroadcaster.sendToNode(request, fromId); } #location 39 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void onEvent(SmallBlockEvent event, String fromId) { ValidateResult result = event.getEventBody().verify(); if (result.isFailed()) { return; } temporaryCacheManager.cacheSmallBlock(event.getEventBody()); downloadDataUtils.removeSmallBlock(event.getEventBody().getBlockHash().getDigestHex()); GetTxGroupRequest request = new GetTxGroupRequest(); GetTxGroupParam param = new GetTxGroupParam(); param.setBlockHash(event.getEventBody().getBlockHash()); for (NulsDigestData hash : event.getEventBody().getTxHashList()) { if (!receivedTxCacheManager.txExist(hash) && !orphanTxCacheManager.txExist(hash)) { param.addHash(hash); } } if (param.getTxHashList().isEmpty()) { BlockHeader header = temporaryCacheManager.getBlockHeader(event.getEventBody().getBlockHash().getDigestHex()); if (null == header) { return; } Block block = new Block(); block.setHeader(header); List<Transaction> txs = new ArrayList<>(); for (NulsDigestData txHash : event.getEventBody().getTxHashList()) { Transaction tx = receivedTxCacheManager.getTx(txHash); if (null == tx) { tx = orphanTxCacheManager.getTx(txHash); } if (null == tx) { throw new NulsRuntimeException(ErrorCode.DATA_ERROR); } txs.add(tx); } block.setTxs(txs); ValidateResult<RedPunishData> vResult = block.verify(); if (null == vResult || (vResult.isFailed() && vResult.getErrorCode() != ErrorCode.ORPHAN_TX)) { if (vResult.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) { RedPunishData data = vResult.getObject(); ConsensusMeetingRunner.putPunishData(data); networkService.blackNode(fromId, NodePo.BLACK); } else { networkService.removeNode(fromId, NodePo.YELLOW); } return; } blockManager.addBlock(block, false, fromId); downloadDataUtils.removeTxGroup(block.getHeader().getHash().getDigestHex()); BlockHeaderEvent headerEvent = new BlockHeaderEvent(); headerEvent.setEventBody(header); eventBroadcaster.broadcastHashAndCacheAysn(headerEvent, false, fromId); return; } request.setEventBody(param); this.eventBroadcaster.sendToNode(request, fromId); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onEvent(BlockEvent event, String fromId) { Block block = event.getEventBody(); ValidateResult result = block.verify(); if (result.isFailed()) { if (result.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) { networkService.removeNode(fromId); } return; } if (BlockBatchDownloadUtils.getInstance().downloadedBlock(fromId, block)) { return; } blockCacheManager.cacheBlock(block); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void onEvent(BlockEvent event, String fromId) { Block block = event.getEventBody(); ValidateResult result = block.verify(); if (result.isFailed()) { if (result.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) { networkService.blackNode(fromId, NodePo.YELLOW); } return; } if (BlockBatchDownloadUtils.getInstance().downloadedBlock(fromId, block)) { return; } blockCacheManager.cacheBlock(block); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Result saveLocalTx(Transaction tx) { if (tx == null) { return Result.getFailed(KernelErrorCode.NULL_PARAMETER); } byte[] txHashBytes = new byte[0]; try { txHashBytes = tx.getHash().serialize(); } catch (IOException e) { throw new NulsRuntimeException(e); } CoinData coinData = tx.getCoinData(); if (coinData != null) { // delete - from List<Coin> froms = coinData.getFrom(); Set<byte[]> fromsSet = new HashSet<>(); for (Coin from : froms) { byte[] fromSource = from.getOwner(); byte[] utxoFromSource = new byte[tx.getHash().size()]; byte[] fromIndex = new byte[fromSource.length - utxoFromSource.length]; System.arraycopy(fromSource, 0, utxoFromSource, 0, tx.getHash().size()); System.arraycopy(fromSource, tx.getHash().size(), fromIndex, 0, fromIndex.length); Transaction sourceTx = null; try { sourceTx = ledgerService.getTx(NulsDigestData.fromDigestHex(Hex.encode(fromSource))); if (sourceTx == null) { sourceTx = getUnconfirmedTransaction(NulsDigestData.fromDigestHex(Hex.encode(fromSource))).getData(); } } catch (Exception e) { throw new NulsRuntimeException(e); } if(sourceTx == null){ return Result.getFailed(); } byte[] address = sourceTx.getCoinData().getTo().get((int) new VarInt(fromIndex, 0).value).getOwner(); fromsSet.add(org.spongycastle.util.Arrays.concatenate(address, from.getOwner())); } storageService.batchDeleteUTXO(fromsSet); // save utxo - to List<Coin> tos = coinData.getTo(); byte[] indexBytes; Map<byte[], byte[]> toMap = new HashMap<>(); for (int i = 0, length = tos.size(); i < length; i++) { try { byte[] outKey = org.spongycastle.util.Arrays.concatenate(tos.get(i).getOwner(), tx.getHash().serialize(), new VarInt(i).encode()); toMap.put(outKey, tos.get(i).serialize()); } catch (IOException e) { throw new NulsRuntimeException(e); } } storageService.batchSaveUTXO(toMap); } return Result.getSuccess(); } #location 46 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public Result saveLocalTx(Transaction tx) { if (tx == null) { return Result.getFailed(KernelErrorCode.NULL_PARAMETER); } byte[] txHashBytes = new byte[0]; try { txHashBytes = tx.getHash().serialize(); } catch (IOException e) { throw new NulsRuntimeException(e); } CoinData coinData = tx.getCoinData(); if (coinData != null) { // delete - from List<Coin> froms = coinData.getFrom(); Set<byte[]> fromsSet = new HashSet<>(); for (Coin from : froms) { byte[] fromSource = from.getOwner(); byte[] utxoFromSource = new byte[tx.getHash().size()]; byte[] fromIndex = new byte[fromSource.length - utxoFromSource.length]; System.arraycopy(fromSource, 0, utxoFromSource, 0, tx.getHash().size()); System.arraycopy(fromSource, tx.getHash().size(), fromIndex, 0, fromIndex.length); Transaction sourceTx = null; try { sourceTx = ledgerService.getTx(NulsDigestData.fromDigestHex(Hex.encode(fromSource))); } catch (Exception e) { throw new NulsRuntimeException(e); } if (sourceTx == null) { return Result.getFailed(AccountLedgerErrorCode.SOURCE_TX_NOT_EXSITS); } byte[] address = sourceTx.getCoinData().getTo().get((int) new VarInt(fromIndex, 0).value).getOwner(); fromsSet.add(org.spongycastle.util.Arrays.concatenate(address, from.getOwner())); } storageService.batchDeleteUTXO(fromsSet); // save utxo - to List<Coin> tos = coinData.getTo(); byte[] indexBytes; Map<byte[], byte[]> toMap = new HashMap<>(); for (int i = 0, length = tos.size(); i < length; i++) { try { byte[] outKey = org.spongycastle.util.Arrays.concatenate(tos.get(i).getOwner(), tx.getHash().serialize(), new VarInt(i).encode()); toMap.put(outKey, tos.get(i).serialize()); } catch (IOException e) { throw new NulsRuntimeException(e); } } storageService.batchSaveUTXO(toMap); } return Result.getSuccess(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void start() { List<Peer> peers = discovery.getLocalPeers(10); if (peers.isEmpty()) { peers = getSeedPeers(); } for (Peer peer : peers) { peer.setType(Peer.OUT); addPeerToGroup(NetworkConstant.NETWORK_PEER_OUT_GROUP, peer); } boolean isConsensus = ConfigLoader.getCfgValue(PocConsensusConstant.CFG_CONSENSUS_SECTION, PocConsensusConstant.PROPERTY_DELEGATE_PEER, false); if (isConsensus) { network.maxOutCount(network.maxOutCount() * 5); network.maxInCount(network.maxInCount() * 5); } System.out.println("-----------peerManager start"); //start heart beat thread ThreadManager.createSingleThreadAndRun(NulsConstant.MODULE_ID_NETWORK, "peerDiscovery", this.discovery); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void start() { List<Peer> peers = discovery.getLocalPeers(10); if (peers.isEmpty()) { peers = getSeedPeers(); } for (Peer peer : peers) { peer.setType(Peer.OUT); addPeerToGroup(NetworkConstant.NETWORK_PEER_OUT_GROUP, peer); } boolean isConsensus = NulsContext.MODULES_CONFIG.getCfgValue(PocConsensusConstant.CFG_CONSENSUS_SECTION, PocConsensusConstant.PROPERTY_DELEGATE_PEER, false); if (isConsensus) { network.maxOutCount(network.maxOutCount() * 5); network.maxInCount(network.maxInCount() * 5); } System.out.println("-----------peerManager start"); //start heart beat thread ThreadManager.createSingleThreadAndRun(NulsConstant.MODULE_ID_NETWORK, "peerDiscovery", this.discovery); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void start() { getNetworkStorage().init(); List<Node> nodeList = getNetworkStorage().getLocalNodeList(20); nodeList.addAll(getSeedNodes()); for (Node node : nodeList) { addNode(node); } running = true; TaskManager.createAndRunThread(NetworkConstant.NETWORK_MODULE_ID, "NetworkNodeManager", this); nodeDiscoverHandler.start(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void start() { List<Node> nodeList = getNetworkStorage().getLocalNodeList(20); nodeList.addAll(getSeedNodes()); for (Node node : nodeList) { addNode(node); } running = true; TaskManager.createAndRunThread(NetworkConstant.NETWORK_MODULE_ID, "NetworkNodeManager", this); nodeDiscoverHandler.start(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected Block createBlock() { // new a block header BlockHeader blockHeader = new BlockHeader(); blockHeader.setHeight(0); blockHeader.setPreHash(NulsDigestData.calcDigestData("00000000000".getBytes())); blockHeader.setTime(1L); blockHeader.setTxCount(1); blockHeader.setMerkleHash(NulsDigestData.calcDigestData(new byte[20])); // add a round data BlockRoundData roundData = new BlockRoundData(); roundData.setConsensusMemberCount(1); roundData.setPackingIndexOfRound(1); roundData.setRoundIndex(1); roundData.setRoundStartTime(1L); try { blockHeader.setExtend(roundData.serialize()); } catch (IOException e) { throw new NulsRuntimeException(e); } // new a block of height 0 Block block = new Block(); block.setHeader(blockHeader); List<Transaction> txs = new ArrayList<>(); block.setTxs(txs); Transaction tx = new TestTransaction(); txs.add(tx); List<NulsDigestData> txHashList = block.getTxHashList(); blockHeader.setMerkleHash(NulsDigestData.calcMerkleDigestData(txHashList)); NulsSignData signData = null; try { signData = accountService.signData(blockHeader.getHash().getDigestBytes(), ecKey); } catch (NulsException e) { e.printStackTrace(); } P2PKHScriptSig sig = new P2PKHScriptSig(); sig.setSignData(signData); sig.setPublicKey(ecKey.getPubKey()); blockHeader.setScriptSig(sig); return block; } #location 38 #vulnerability type NULL_DEREFERENCE
#fixed code protected Block createBlock() { // new a block header BlockHeader blockHeader = new BlockHeader(); blockHeader.setHeight(0); blockHeader.setPreHash(NulsDigestData.calcDigestData("00000000000".getBytes())); blockHeader.setTime(1L); blockHeader.setTxCount(1); blockHeader.setMerkleHash(NulsDigestData.calcDigestData(new byte[20])); // add a round data BlockRoundData roundData = new BlockRoundData(); roundData.setConsensusMemberCount(1); roundData.setPackingIndexOfRound(1); roundData.setRoundIndex(1); roundData.setRoundStartTime(1L); try { blockHeader.setExtend(roundData.serialize()); } catch (IOException e) { throw new NulsRuntimeException(e); } // new a block of height 0 Block block = new Block(); block.setHeader(blockHeader); List<Transaction> txs = new ArrayList<>(); block.setTxs(txs); Transaction tx = new TestTransaction(); txs.add(tx); List<NulsDigestData> txHashList = block.getTxHashList(); blockHeader.setMerkleHash(NulsDigestData.calcMerkleDigestData(txHashList)); NulsSignData signData = signDigest(blockHeader.getHash().getDigestBytes(), ecKey); P2PKHScriptSig sig = new P2PKHScriptSig(); sig.setSignData(signData); sig.setPublicKey(ecKey.getPubKey()); blockHeader.setScriptSig(sig); return block; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void checkIt() { int maxSize = 0; BlockHeaderChain longestChain = null; StringBuilder str = new StringBuilder("++++++++++++++++++++++++chain info:"); for (BlockHeaderChain chain : chainList) { str.append("+++++++++++\nchain:start-" + chain.getHeaderDigestList().get(0).getHeight() + ", end-" + chain.getHeaderDigestList().get(chain.size() - 1).getHeight()); int listSize = chain.size(); if (maxSize < listSize) { maxSize = listSize; longestChain = chain; } else if (maxSize == listSize) { HeaderDigest hd = chain.getLastHd(); HeaderDigest hd_long = longestChain.getLastHd(); if (hd.getTime() < hd_long.getTime()) { longestChain = chain; } } } if (tempIndex % 10 == 0) { BlockLog.info(str.toString()); tempIndex++; } if (this.approvingChain != null || !this.approvingChain.getId().equals(longestChain.getId())) { BlockService blockService = NulsContext.getServiceBean(BlockService.class); for (int i=approvingChain.size()-1;i>=0;i--) { HeaderDigest hd = approvingChain.getHeaderDigestList().get(i); try { blockService.rollbackBlock(hd.getHash()); } catch (NulsException e) { Log.error(e); } } for(int i=0;i<longestChain.getHeaderDigestList().size();i++){ HeaderDigest hd = longestChain.getHeaderDigestList().get(i); blockService.approvalBlock(hd.getHash()); } } this.approvingChain = longestChain; Set<String> rightHashSet = new HashSet<>(); Set<String> removeHashSet = new HashSet<>(); for (int i = chainList.size() - 1; i >= 0; i--) { BlockHeaderChain chain = chainList.get(i); if (chain.size() < (maxSize - 6)) { removeHashSet.addAll(chain.getHashSet()); this.chainList.remove(chain); } else { rightHashSet.addAll(chain.getHashSet()); } } for (String hash : removeHashSet) { if (!rightHashSet.contains(hash)) { confirmingBlockCacheManager.removeBlock(hash); } } } #location 28 #vulnerability type NULL_DEREFERENCE
#fixed code private void checkIt() { int maxSize = 0; BlockHeaderChain longestChain = null; StringBuilder str = new StringBuilder("++++++++++++++++++++++++chain info:"); for (BlockHeaderChain chain : chainList) { str.append("+++++++++++\nchain:start-" + chain.getHeaderDigestList().get(0).getHeight() + ", end-" + chain.getHeaderDigestList().get(chain.size() - 1).getHeight()); int listSize = chain.size(); if (maxSize < listSize) { maxSize = listSize; longestChain = chain; } else if (maxSize == listSize) { HeaderDigest hd = chain.getLastHd(); HeaderDigest hd_long = longestChain.getLastHd(); if (hd.getTime() < hd_long.getTime()) { longestChain = chain; } } } if (tempIndex % 10 == 0) { BlockLog.info(str.toString()); tempIndex++; } if (this.approvingChain != null && !this.approvingChain.getId().equals(longestChain.getId())) { BlockService blockService = NulsContext.getServiceBean(BlockService.class); for (int i=approvingChain.size()-1;i>=0;i--) { HeaderDigest hd = approvingChain.getHeaderDigestList().get(i); try { blockService.rollbackBlock(hd.getHash()); } catch (NulsException e) { Log.error(e); } } for(int i=0;i<longestChain.getHeaderDigestList().size();i++){ HeaderDigest hd = longestChain.getHeaderDigestList().get(i); blockService.approvalBlock(hd.getHash()); } } this.approvingChain = longestChain; Set<String> rightHashSet = new HashSet<>(); Set<String> removeHashSet = new HashSet<>(); for (int i = chainList.size() - 1; i >= 0; i--) { BlockHeaderChain chain = chainList.get(i); if (chain.size() < (maxSize - 6)) { removeHashSet.addAll(chain.getHashSet()); this.chainList.remove(chain); } else { rightHashSet.addAll(chain.getHashSet()); } } for (String hash : removeHashSet) { if (!rightHashSet.contains(hash)) { confirmingBlockCacheManager.removeBlock(hash); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public NetworkEventResult process(BaseEvent networkEvent, Node node) { VersionEvent event = (VersionEvent) networkEvent; // String key = event.getHeader().getEventType() + "-" + node.getId(); // if (cacheService.existEvent(key)) { // Log.info("----------VersionEventHandler cacheService existEvent--------"); // getNetworkService().removeNode(node.getId()); // return null; // } // cacheService.putEvent(key, event, true); if (event.getBestBlockHeight() < 0) { throw new NetworkMessageException(ErrorCode.NET_MESSAGE_ERROR); } node.setVersionMessage(event); checkVersion(event.getNulsVersion()); if (!node.isHandShake()) { node.setStatus(Node.HANDSHAKE); node.setPort(event.getExternalPort()); node.setLastTime(TimeService.currentTimeMillis()); getNodeDao().saveChange(NodeTransferTool.toPojo(node)); } return null; } #location 23 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public NetworkEventResult process(BaseEvent networkEvent, Node node) { VersionEvent event = (VersionEvent) networkEvent; // String key = event.getHeader().getEventType() + "-" + node.getId(); // if (cacheService.existEvent(key)) { // Log.info("----------VersionEventHandler cacheService existEvent--------"); // getNetworkService().removeNode(node.getId()); // return null; // } // cacheService.putEvent(key, event, true); if (event.getBestBlockHeight() < 0) { throw new NetworkMessageException(ErrorCode.NET_MESSAGE_ERROR); } node.setVersionMessage(event); checkVersion(event.getNulsVersion()); if (!node.isHandShake()) { node.setStatus(Node.HANDSHAKE); String oldId = node.getId(); node.setId(null); node.setPort(event.getExternalPort()); getNetworkService().changeNodeFromMap(oldId, node); node.setLastTime(TimeService.currentTimeMillis()); getNodeDao().saveChange(NodeTransferTool.toPojo(node)); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { SocketChannel channel = (SocketChannel) ctx.channel(); Attribute<Node> nodeAttribute = channel.attr(key); Node node = nodeAttribute.get(); String nodeId = node == null ? null : node.getId(); Log.debug("---------------------- client channelRegistered -----------" + nodeId); Map<String, Node> nodes = null; //Map<String, Node> nodes = getNetworkService().getNodes(); // If a node with the same IP already in nodes, as a out node, can not add anymore for (Node n : nodes.values()) { //both ip and port equals , it means the node is myself if (n.getIp().equals(node.getIp()) && !n.getPort().equals(node.getSeverPort())) { Log.debug("----------------------client: it already had a connection: " + n.getId() + " type:" + n.getType() + ", this connection: " + nodeId + "---------------------- "); ctx.channel().close(); return; } } } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { SocketChannel channel = (SocketChannel) ctx.channel(); Attribute<Node> nodeAttribute = channel.attr(key); Node node = nodeAttribute.get(); String nodeId = node == null ? null : node.getId(); Log.debug("---------------------- client channelRegistered -----------" + nodeId); Map<String, Node> nodes = nodeManager.getNodes(); //Map<String, Node> nodes = getNetworkService().getNodes(); // If a node with the same IP already in nodes, as a out node, can not add anymore for (Node n : nodes.values()) { //both ip and port equals , it means the node is myself if (n.getIp().equals(node.getIp()) && !n.getPort().equals(node.getSeverPort())) { Log.debug("----------------------client: it already had a connection: " + n.getId() + " type:" + n.getType() + ", this connection: " + nodeId + "---------------------- "); ctx.channel().close(); return; } } }
Below is the vulnerable code, please generate the patch based on the following information.