Skip to content

Commit

Permalink
Refactor: RA-79: Fix for SonarQube and Spotbugs issues
Browse files Browse the repository at this point in the history
  • Loading branch information
BerezinD committed Apr 29, 2024
1 parent 8d8bf1c commit c82012f
Show file tree
Hide file tree
Showing 11 changed files with 80 additions and 53 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

import org.cardanofoundation.rosetta.api.block.model.entity.BlockAwareEntity;
import org.hibernate.annotations.DynamicUpdate;

@EqualsAndHashCode(callSuper = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
Expand Down Expand Up @@ -45,3 +47,4 @@ public class StakeAddressBalanceEntity extends BlockAwareEntity {
@Column(name = "epoch")
private Integer epoch;
}

Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public enum CatalystDataIndexes {

public static CatalystDataIndexes findByValue(Long value) {
for (CatalystDataIndexes a : CatalystDataIndexes.values()) {
if (a.getValue() == value) {
if (a.getValue().equals(value)) {
return a;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public enum CatalystLabels {

public static CatalystLabels findByValue(String label) {
for (CatalystLabels a : CatalystLabels.values()) {
if (a.getLabel() == label) {
if (a.getLabel().equals(label)) {
return a;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,7 @@ public static CoinChange getCoinChange(int index, String hash, CoinAction coinAc
CoinIdentifier coinIdentifier = new CoinIdentifier();
coinIdentifier.setIdentifier(hash + ":" + index);

return CoinChange.builder().coinIdentifier(CoinIdentifier.builder().identifier(hash + ":" + index).build())
.coinAction(coinAction).build();
return CoinChange.builder().coinIdentifier(coinIdentifier).coinAction(coinAction).build();
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ private static void fillOutputOperations(TransactionBody transactionBody, List<O
operations);
log.info("[parseOperationsFromTransactionBody] About to parse {} outputs", outputs.size());
for (TransactionOutput output : outputs) {
Operation outputParsed = ParseConstructionUtil.TransActionOutputToOperation(output, (long) operations.size(),
Operation outputParsed = ParseConstructionUtil.transActionOutputToOperation(output, (long) operations.size(),
relatedOperations);
operations.add(outputParsed);
}
Expand All @@ -117,7 +117,7 @@ private static void fillInputOperations(TransactionBody transactionBody, Transac
operations.add(inputOperations.get(i));
} else {
TransactionInput input = inputs.get(i);
Operation inputParsed = ParseConstructionUtil.TransactionInputToOperation(input, (long) operations.size());
Operation inputParsed = ParseConstructionUtil.transactionInputToOperation(input, (long) operations.size());
operations.add(inputParsed);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public String getCardanoAddress(AddressType addressType, PublicKey stakingCreden

public HdPublicKey getHdPublicKeyFromRosettaKey(PublicKey publicKey) {
byte[] pubKeyBytes = HexUtil.decodeHexString(publicKey.getHexBytes());
HdPublicKey pubKey = new HdPublicKey();
HdPublicKey pubKey;
if(pubKeyBytes.length == 32) {
pubKey = new HdPublicKey();
pubKey.setKeyData(pubKeyBytes);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import okhttp3.Request.Builder;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.apache.commons.lang3.ObjectUtils;
import org.jetbrains.annotations.NotNull;
import org.openapitools.client.model.AccountIdentifier;
Expand Down Expand Up @@ -367,7 +368,7 @@ public UnsignedTransaction createUnsignedTransaction(NetworkIdentifierType netwo
String transactionBytes = HexUtil.encodeHexString(
com.bloxbean.cardano.yaci.core.util.CborSerializationUtil.serialize(mapCbor));
log.info("[createUnsignedTransaction] Hashing transaction body");
String bodyHash = com.bloxbean.cardano.client.util.HexUtil.encodeHexString(
String bodyHash = HexUtil.encodeHexString(
Blake2bUtil.blake2bHash256(CborSerializationUtil.serialize(mapCbor)));
UnsignedTransaction toReturn = new UnsignedTransaction(
HexUtil.encodeHexString(HexUtil.decodeHexString(bodyHash)), transactionBytes,
Expand Down Expand Up @@ -509,27 +510,25 @@ public String submitTransaction(String signedTransaction) throws ApiException {
.build();
OkHttpClient client = new OkHttpClient();
Call call = client.newCall(request);
Response response = null;
try {
response = call.execute();
try (Response response = call.execute()) {
ResponseBody body = response.body();

if (response.code() == Constants.SUCCESS_SUBMIT_TX_HTTP_CODE) {
String txHash = response.body().string();
if (body == null) {
throw ExceptionFactory.sendTransactionError("Empty response body");
}
String txHash = body.string();
// removing leading and trailing quotes returned from node API
if (txHash.length() == Constants.TX_HASH_LENGTH + 2) {
txHash = txHash.substring(1, txHash.length() - 1);
}
return txHash;
} else {
throw ExceptionFactory.sendTransactionError(response.body().string());
throw ExceptionFactory.sendTransactionError(body == null ? null : body.string());
}
} catch (IOException e) {
log.error("{}[submitTransaction] There was an error submitting transaction", e.getMessage());
throw ExceptionFactory.sendTransactionError(e.getMessage());
} finally {
if (response != null) {
response.close();
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import org.cardanofoundation.rosetta.common.enumeration.OperationType;

import java.util.ArrayList;
import java.util.List;
import org.openapitools.client.model.CurveType;

Expand Down Expand Up @@ -89,24 +88,24 @@ private Constants() {
public static final String CHAIN_CODE_DUMMY = new String(new char[CHAIN_CODE_LENGTH]).replace(
"\0", "0");

public static final List<String> STAKING_OPERATIONS = new ArrayList<>(
public static final List<String> STAKING_OPERATIONS =
List.of(OperationType.STAKE_DELEGATION.getValue(),
OperationType.STAKE_KEY_REGISTRATION.getValue(),
OperationType.STAKE_KEY_DEREGISTRATION.getValue(),
OperationType.WITHDRAWAL.getValue()));
public static final List<String> POOL_OPERATIONS = new ArrayList<>(
OperationType.WITHDRAWAL.getValue());
public static final List<String> POOL_OPERATIONS =
List.of(OperationType.POOL_RETIREMENT.getValue(),
OperationType.POOL_REGISTRATION.getValue(),
OperationType.POOL_REGISTRATION_WITH_CERT.getValue()));
public static final List<String> STAKE_POOL_OPERATIONS = new ArrayList<>(
OperationType.POOL_REGISTRATION_WITH_CERT.getValue());
public static final List<String> STAKE_POOL_OPERATIONS =
List.of(OperationType.STAKE_DELEGATION.getValue(),
OperationType.STAKE_KEY_REGISTRATION.getValue(),
OperationType.STAKE_KEY_DEREGISTRATION.getValue(),
OperationType.POOL_RETIREMENT.getValue(),
OperationType.POOL_REGISTRATION.getValue(),
OperationType.POOL_REGISTRATION_WITH_CERT.getValue()));
public static final List<String> VOTE_OPERATIONS = new ArrayList<>(
List.of(OperationType.VOTE_REGISTRATION.getValue()));
OperationType.POOL_REGISTRATION_WITH_CERT.getValue());
public static final List<String> VOTE_OPERATIONS =
List.of(OperationType.VOTE_REGISTRATION.getValue());

public static final Integer ED_25519_KEY_SIGNATURE_BYTE_LENGTH = 64;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@

public class OperationParseUtil {

private OperationParseUtil() {
}

public static ProcessOperations parseOperation(
Operation operation, NetworkIdentifierType networkIdentifierType, ProcessOperations resultAccumulator, String type) {
return switch (OperationType.fromValue(type)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,16 @@
import com.bloxbean.cardano.client.transaction.spec.cert.SingleHostName;
import com.bloxbean.cardano.client.transaction.spec.cert.StakeDelegation;
import com.bloxbean.cardano.client.util.HexUtil;

import java.math.BigInteger;
import java.util.Comparator;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.ObjectUtils;

import org.cardanofoundation.rosetta.common.enumeration.CatalystDataIndexes;
import org.cardanofoundation.rosetta.common.enumeration.CatalystLabels;
import org.cardanofoundation.rosetta.common.enumeration.CatalystSigIndexes;
Expand All @@ -45,10 +48,12 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.cardanofoundation.rosetta.common.enumeration.OperationType;
import org.cardanofoundation.rosetta.common.exception.ExceptionFactory;
import org.cardanofoundation.rosetta.common.mapper.DataMapper;
import org.cardanofoundation.rosetta.common.model.cardano.network.RelayType;

import org.openapitools.client.model.AccountIdentifier;
import org.openapitools.client.model.Amount;
import org.openapitools.client.model.CoinAction;
Expand All @@ -70,6 +75,9 @@
@Slf4j
public class ParseConstructionUtil {

private ParseConstructionUtil() {
}

public static Inet4Address parseIpv4(String ip) throws UnknownHostException {
if (!ObjectUtils.isEmpty(ip)) {
String[] ipNew = ip.split("\\.");
Expand All @@ -92,10 +100,11 @@ public static Inet6Address parseIpv6(String ip) throws UnknownHostException {
}


public static List<String> getOwnerAddressesFromPoolRegistrations(String networkId, PoolRegistration poolRegistration) {
public static List<String> getOwnerAddressesFromPoolRegistrations(String networkId,
PoolRegistration poolRegistration) {
List<String> poolOwners = new ArrayList<>();
Set<String> owners = poolRegistration.getPoolOwners();
for(String owner : owners) {
for (String owner : owners) {
if (networkId.equals(NetworkIdentifierType.CARDANO_TESTNET_NETWORK.getNetworkId())) {
Address address = CardanoAddressUtils.getAddress(null,
HexUtil.decodeHexString(owner), Constants.STAKE_KEY_HASH_HEADER_KIND,
Expand All @@ -118,46 +127,47 @@ public static List<String> getOwnerAddressesFromPoolRegistrations(String network
return poolOwners;
}

public static String getRewardAddressFromPoolRegistration(String networkId, PoolRegistration poolRegistration) {
public static String getRewardAddressFromPoolRegistration(String networkId,
PoolRegistration poolRegistration) {
String cutRewardAccount = poolRegistration.getRewardAccount();
if (cutRewardAccount.length() == Constants.HEX_PREFIX_AND_REWARD_ACCOUNT_LENGTH) {
// removing prefix 0x from reward account, reward account is 56 bytes
cutRewardAccount = poolRegistration.getRewardAccount().substring(2);
}
if (networkId.equals(NetworkIdentifierType.CARDANO_TESTNET_NETWORK.getNetworkId())) {
return CardanoAddressUtils.getAddress(null,
HexUtil.decodeHexString(cutRewardAccount),
Constants.STAKE_KEY_HASH_HEADER_KIND,
Networks.testnet(), Reward)
.getAddress();
HexUtil.decodeHexString(cutRewardAccount),
Constants.STAKE_KEY_HASH_HEADER_KIND,
Networks.testnet(), Reward)
.getAddress();
}
if (networkId.equals(NetworkIdentifierType.CARDANO_PREPROD_NETWORK.getNetworkId())) {
return CardanoAddressUtils.getAddress(null,
HexUtil.decodeHexString(cutRewardAccount),
HexUtil.decodeHexString(cutRewardAccount),
Constants.STAKE_KEY_HASH_HEADER_KIND,
Networks.preprod(), Reward)
.getAddress();
Networks.preprod(), Reward)
.getAddress();
}
if (networkId.equals(NetworkIdentifierType.CARDANO_MAINNET_NETWORK.getNetworkId())) {
return CardanoAddressUtils.getAddress(null,
HexUtil.decodeHexString(cutRewardAccount),
HexUtil.decodeHexString(cutRewardAccount),
Constants.STAKE_KEY_HASH_HEADER_KIND,
Networks.mainnet(), Reward)
.getAddress();
Networks.mainnet(), Reward)
.getAddress();
}

throw ExceptionFactory.invalidAddressError("Can't get Reward address from PoolRegistration");
}

public static Operation TransactionInputToOperation(TransactionInput input, Long index) {
public static Operation transactionInputToOperation(TransactionInput input, Long index) {
return new Operation(new OperationIdentifier(index, null), null, OperationType.INPUT.getValue(),
"", null, null,
new CoinChange(new CoinIdentifier(
input.getTransactionId() + ":"
+ input.getIndex()), CoinAction.SPENT), null);
}

public static Operation TransActionOutputToOperation(TransactionOutput output, Long index,
public static Operation transActionOutputToOperation(TransactionOutput output, Long index,
List<OperationIdentifier> relatedOperations) {
OperationIdentifier operationIdentifier = new OperationIdentifier(index, null);
AccountIdentifier account = new AccountIdentifier(output.getAddress(), null, null);
Expand Down Expand Up @@ -186,7 +196,8 @@ public static OperationMetadata parseTokenBundle(TransactionOutput output) {
.toList();
}

return !ObjectUtils.isEmpty(multiAssets) ? OperationMetadata.builder().tokenBundle(tokenBundle).build() : null;
return !ObjectUtils.isEmpty(multiAssets) ? OperationMetadata.builder().tokenBundle(tokenBundle)
.build() : null;
}

public static TokenBundleItem parseTokenAsset(List<MultiAsset> multiAssets, String policyId) {
Expand Down Expand Up @@ -256,11 +267,7 @@ public static List<Operation> parseCertsToOperations(TransactionBody transaction
for (int i = 0; i < certsCount; i++) {
Operation certOperation = certOps.get(i);
if (Constants.STAKING_OPERATIONS.contains(certOperation.getType())) {
String hex = null;
if (checkStakeCredential(certOperation)) {
hex = certOperation.getMetadata().getStakingCredential().getHexBytes();
}
Optional.ofNullable(hex).orElseThrow(ExceptionFactory::missingStakingKeyError);
String hex = getStakingCredentialHex(certOperation);
HdPublicKey hdPublicKey = new HdPublicKey();
hdPublicKey.setKeyData(HexUtil.decodeHexString(hex));
String address = CardanoAddressUtils.generateRewardAddress(
Expand Down Expand Up @@ -295,6 +302,18 @@ public static List<Operation> parseCertsToOperations(TransactionBody transaction
return parsedOperations;
}

private static String getStakingCredentialHex(Operation certOperation) {
String hex = null;
if (checkStakeCredential(certOperation)) {
hex = certOperation.getMetadata().getStakingCredential().getHexBytes();
}
if (hex == null) {
log.error("[parseCertsToOperations] Missing staking key");
throw ExceptionFactory.missingStakingKeyError();
}
return hex;
}

public static Operation parsePoolCertToOperation(Integer network, Certificate cert, Long index,
String type)
throws CborSerializationException, CborException {
Expand Down Expand Up @@ -517,12 +536,12 @@ public static List<Relay> parsePoolRelays(PoolRegistration poolRegistration) {
MultiHostName multiHostRelay = getMultiHostRelay(relay);
SingleHostName singleHostName = getSingleHostName(relay);
SingleHostAddr singleHostAddr = getSingleHostAddr(relay);
if (multiHostRelay!=null || singleHostName!=null) {
if (multiHostRelay != null || singleHostName != null) {
addRelayToPoolReLayOfTypeMultiHostOrSingleHostName(poolRelays, multiHostRelay,
singleHostName);
continue;
}
if (singleHostAddr!=null) {
if (singleHostAddr != null) {
addRelayToPoolReLayOfTypeSingleHostAddr(poolRelays, singleHostAddr);
}
}
Expand Down Expand Up @@ -598,7 +617,8 @@ public static Operation parseCertToOperation(Certificate cert, Long index, Strin
String address) {
Operation operation = new Operation(new OperationIdentifier(index, null), null, type, "",
new AccountIdentifier(address, null, null), null, null,
OperationMetadata.builder().stakingCredential(new PublicKey(hash, CurveType.EDWARDS25519)).build());
OperationMetadata.builder().stakingCredential(new PublicKey(hash, CurveType.EDWARDS25519))
.build());
StakeDelegation delegationCert = null;
try {
delegationCert = (StakeDelegation) cert;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,8 +187,12 @@ public static ProcessPoolRegistrationReturn getPoolRegistrationFromOperation(Ope

public static PoolRegistrationCertReturn getPoolRegistrationCertFromOperation(Operation operation,
NetworkIdentifierType networkIdentifierType) {
OperationMetadata operationMetadata = operation.getMetadata();
AccountIdentifier account = operation == null ? null : operation.getAccount();
OperationMetadata operationMetadata = null;
AccountIdentifier account = null;
if (operation != null) {
operationMetadata = operation.getMetadata();
account = operation.getAccount();
}
return ValidateParseUtil.validateAndParsePoolRegistrationCert(
networkIdentifierType,
operationMetadata == null ? null : operationMetadata.getPoolRegistrationCert(),
Expand Down

0 comments on commit c82012f

Please sign in to comment.