ECKey: Simplify comparators using JDK 8 methods

This commit is contained in:
Sean Gilligan 2021-12-30 19:17:09 -08:00 committed by Andreas Schildbach
parent 9641fde9e8
commit 25454bd624

View File

@ -92,28 +92,14 @@ import static com.google.common.base.Preconditions.*;
*/ */
public class ECKey implements EncryptableItem { public class ECKey implements EncryptableItem {
private static final Logger log = LoggerFactory.getLogger(ECKey.class); private static final Logger log = LoggerFactory.getLogger(ECKey.class);
// Note: this can be replaced with Arrays.compare(a, b) once we require Java 9
private static final Comparator<byte[]> LEXICOGRAPHICAL_COMPARATOR = UnsignedBytes.lexicographicalComparator();
/** Sorts oldest keys first, newest last. */ /** Sorts oldest keys first, newest last. */
public static final Comparator<ECKey> AGE_COMPARATOR = new Comparator<ECKey>() { public static final Comparator<ECKey> AGE_COMPARATOR = Comparator.comparingLong(k -> k.creationTimeSeconds);
@Override /** Compares by extracting pub key as a {@code byte[]} and using a lexicographic comparator */
public int compare(ECKey k1, ECKey k2) { public static final Comparator<ECKey> PUBKEY_COMPARATOR = Comparator.comparing(ECKey::getPubKey, LEXICOGRAPHICAL_COMPARATOR);
if (k1.creationTimeSeconds == k2.creationTimeSeconds)
return 0;
else
return k1.creationTimeSeconds > k2.creationTimeSeconds ? 1 : -1;
}
};
/** Compares pub key bytes using {@link com.google.common.primitives.UnsignedBytes#lexicographicalComparator()} */
public static final Comparator<ECKey> PUBKEY_COMPARATOR = new Comparator<ECKey>() {
private Comparator<byte[]> comparator = UnsignedBytes.lexicographicalComparator();
@Override
public int compare(ECKey k1, ECKey k2) {
return comparator.compare(k1.getPubKey(), k2.getPubKey());
}
};
// The parameters of the secp256k1 curve that Bitcoin uses. // The parameters of the secp256k1 curve that Bitcoin uses.
private static final X9ECParameters CURVE_PARAMS = CustomNamedCurves.getByName("secp256k1"); private static final X9ECParameters CURVE_PARAMS = CustomNamedCurves.getByName("secp256k1");