Skip to content

Commit

Permalink
refactor: RA-106 change to Optional<Block> findBlock
Browse files Browse the repository at this point in the history
  • Loading branch information
shleger committed May 8, 2024
1 parent cf30a02 commit 4e97a45
Show file tree
Hide file tree
Showing 7 changed files with 78 additions and 78 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -82,37 +83,36 @@ public AccountCoinsResponse getAccountCoins(AccountCoinsRequest accountCoinsRequ

private AccountBalanceResponse findBalanceDataByAddressAndBlock(String address, Long number,
String hash) {
Block blockDto;
if (number != null || hash != null) {
blockDto = ledgerBlockService.findBlock(number, hash);
} else {
blockDto = ledgerBlockService.findLatestBlock();
}

if (Objects.isNull(blockDto)) {
log.error("[findBalanceDataByAddressAndBlock] Block not found");
throw ExceptionFactory.blockNotFoundException();
}
log.info(
"[findBalanceDataByAddressAndBlock] Looking for utxos for address {} and block {}",
address,
blockDto.getHash());
if (CardanoAddressUtils.isStakeAddress(address)) {
log.debug("[findBalanceDataByAddressAndBlock] Address is StakeAddress");
log.debug("[findBalanceDataByAddressAndBlock] About to get balance for {}", address);
List<StakeAddressBalance> balances = ledgerDataProviderService.findStakeAddressBalanceByAddressAndBlock(
address, blockDto.getNumber());
if (Objects.isNull(balances) || balances.isEmpty()) {
log.error("[findBalanceDataByAddressAndBlock] No balance found for {}", address);
throw ExceptionFactory.invalidAddressError();
}
return DataMapper.mapToStakeAddressBalanceResponse(blockDto, balances.getFirst());
} else {
log.debug("[findBalanceDataByAddressAndBlock] Address isn't StakeAddress");
return findBlockOrLast(number, hash)
.map(blockDto -> {
log.info("Looking for utxos for address {} and block {}",
address,
blockDto.getHash());
if (CardanoAddressUtils.isStakeAddress(address)) {
log.debug("Address is StakeAddress, get balance for {}", address);
List<StakeAddressBalance> balances = ledgerDataProviderService.findStakeAddressBalanceByAddressAndBlock(
address, blockDto.getNumber());
if (Objects.isNull(balances) || balances.isEmpty()) {
log.error("[findBalanceDataByAddressAndBlock] No balance found for {}", address);
throw ExceptionFactory.invalidAddressError();
}
return DataMapper.mapToStakeAddressBalanceResponse(blockDto, balances.getFirst());
} else {
log.debug("Address isn't StakeAddress");
List<AddressBalance> balances = ledgerDataProviderService.findBalanceByAddressAndBlock(
address, blockDto.getNumber());
return DataMapper.mapToAccountBalanceResponse(blockDto, balances);
}
})
.orElseThrow(ExceptionFactory::blockNotFoundException);
}

List<AddressBalance> balances = ledgerDataProviderService.findBalanceByAddressAndBlock(
address, blockDto.getNumber());
return DataMapper.mapToAccountBalanceResponse(blockDto, balances);
private Optional<Block> findBlockOrLast(Long number, String hash) {
if (number != null || hash != null) {
return ledgerBlockService.findBlock(number, hash);
} else {
return Optional.of(ledgerBlockService.findLatestBlock());
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.cardanofoundation.rosetta.api.block.service;

import java.util.Optional;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

Expand All @@ -10,8 +12,6 @@
import org.cardanofoundation.rosetta.common.exception.ExceptionFactory;
import org.cardanofoundation.rosetta.common.services.ProtocolParamService;

import static java.util.Objects.nonNull;

@Slf4j
@Service
@RequiredArgsConstructor
Expand All @@ -23,18 +23,16 @@ public class BlockServiceImpl implements BlockService {

@Override
public Block findBlock(Long index, String hash) {

log.info("[block] Looking for block: hash={}, index={}", hash, index);
Block block = ledgerBlockService.findBlock(index, hash);
if (nonNull(block)) {
log.info("[block] Block was found, hash={}", block.getHash());

Optional<Block> blockOpt = ledgerBlockService.findBlock(index, hash);
if (blockOpt.isPresent()) {
var block = blockOpt.get();
log.info("Block was found, hash={}", block.getHash());
block.setPoolDeposit(String.valueOf(protocolParamService.getProtocolParameters().getPoolDeposit()));

log.debug("[block] full data {}", block);
log.debug("full data {}", block);
return block;
}
log.error("[block] Block was not found");
log.error("Block was not found");
throw ExceptionFactory.blockNotFoundException();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.cardanofoundation.rosetta.api.block.service;

import java.util.List;
import java.util.Optional;

import org.cardanofoundation.rosetta.api.block.model.domain.Block;
import org.cardanofoundation.rosetta.api.block.model.domain.BlockTx;
Expand All @@ -13,9 +14,9 @@ public interface LedgerBlockService {
*
* @param number block number
* @param hash block hash
* @return the block
* @return the block if found or empty otherwise
*/
Block findBlock(Long number, String hash);
Optional<Block> findBlock(Long number, String hash);


/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,22 +65,17 @@ public class LedgerBlockServiceImpl implements LedgerBlockService {


@Override
public Block findBlock(Long blockNumber, String blockHash) {
public Optional<Block> findBlock(Long blockNumber, String blockHash) {
log.debug("Query blockNumber: {} , blockHash: {}", blockNumber, blockHash);
Optional<BlockEntity> blockEntity;
if (blockHash == null && blockNumber != null) {
blockEntity = blockRepository.findByNumber(blockNumber);
return blockRepository.findByNumber(blockNumber).map(this::toModelFrom);
} else if (blockHash != null && blockNumber == null) {
blockEntity = blockRepository.findByHash(blockHash);
return blockRepository.findByHash(blockHash).map(this::toModelFrom);
} else {
blockEntity = blockRepository.findByNumberAndHash(blockNumber, blockHash);
return blockRepository
.findByNumberAndHash(blockNumber, blockHash)
.map(this::toModelFrom);
}
if (blockEntity.isPresent()) {
log.debug("Block found! {}", blockEntity);
return toModelFrom(blockEntity.get());
}
log.debug("[findBlock] No block was found");
return null; //TODO saa: replace with optional
}

@NotNull
Expand All @@ -92,14 +87,14 @@ private Block toModelFrom(BlockEntity blockEntity) {

@Override
public List<BlockTx> findTransactionsByBlock(Long blk, String blkHash) {
log.debug("[findTransactionsByBlock] query blockNumber: {} blockHash: {}", blk, blkHash);
log.debug("query blockNumber: {} blockHash: {}", blk, blkHash);
Optional<BlockEntity> blkEntity = blockRepository.findByNumberAndHash(blk, blkHash);
if (blkEntity.isEmpty()) {
log.debug("[findTransactionsByBlock] Block Not found: {} blockHash: {}", blk, blkHash);
log.debug("Block Not found: {} blockHash: {}", blk, blkHash);
return Collections.emptyList();
}
List<TxnEntity> txList = txRepository.findTransactionsByBlockHash(blkEntity.get().getHash());
log.debug("[findTransactionsByBlock] Found {} transactions", txList.size());
log.debug("Found {} transactions", txList.size());
if (ObjectUtils.isNotEmpty(txList)) {
List<BlockTx> transactions = txList.stream().map(mapperTran::fromEntity).toList();
transactions.forEach(this::populateTransaction);
Expand All @@ -111,15 +106,15 @@ public List<BlockTx> findTransactionsByBlock(Long blk, String blkHash) {

@Override
public Block findLatestBlock() {
log.info("[getLatestBlock] About to look for latest block");
log.debug("About to look for latest block");
BlockEntity latestBlock = blockRepository.findLatestBlock();
log.debug("[getLatestBlock] Returning latest block {}", latestBlock);
log.debug("Returning latest block {}", latestBlock);
return toModelFrom(latestBlock);
}

@Override
public GenesisBlock findGenesisBlock() {
log.debug("[findGenesisBlock] About to run findGenesisBlock query");
log.debug("About to run findGenesisBlock query");
return blockRepository.findGenesisBlock()
.map(b -> mapper.map(b, GenesisBlock.class))
.orElseThrow(ExceptionFactory::genesisBlockNotFound);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.math.BigInteger;
import java.util.Collections;
import java.util.Optional;

import org.jetbrains.annotations.NotNull;
import org.mockito.InjectMocks;
Expand Down Expand Up @@ -52,7 +53,6 @@ class AccountServiceImplTest {
@InjectMocks
AccountServiceImpl accountService;

private final String ADA = "ADA";
private final String HASH = "hash";

@Test
Expand All @@ -65,7 +65,7 @@ void getAccountBalanceNoStakeAddressPositiveTest() {
Block block = getMockBlock();
AddressBalance addressBalance = new AddressBalance(accountAddress, LOVELACE, 1L,
BigInteger.valueOf(1000L), 1L);
when(ledgerBlockService.findBlock(1L, HASH)).thenReturn(block);
when(ledgerBlockService.findBlock(1L, HASH)).thenReturn(Optional.of(block));
when(ledgerDataProviderService.findBalanceByAddressAndBlock(accountAddress, 1L))
.thenReturn(Collections.singletonList(addressBalance));

Expand Down Expand Up @@ -98,7 +98,7 @@ void getAccountBalanceStakeAddressPositiveTest() {
StakeAddressBalance addressBalance = Mockito.mock(StakeAddressBalance.class);
Block block = getMockBlock();
when(addressBalance.getQuantity()).thenReturn(BigInteger.valueOf(1000L));
when(ledgerBlockService.findBlock(1L, HASH)).thenReturn(block);
when(ledgerBlockService.findBlock(1L, HASH)).thenReturn(Optional.of(block));
when(ledgerDataProviderService.findStakeAddressBalanceByAddressAndBlock(accountAddress, 1L))
.thenReturn(Collections.singletonList(addressBalance));

Expand Down Expand Up @@ -159,7 +159,7 @@ void getAccountBalanceStakeAddressWithEmptyBalancesThrowTest() {
AccountBalanceRequest accountBalanceRequest = Mockito.mock(AccountBalanceRequest.class);
AccountIdentifier accountIdentifier = getMockedAccountIdentifierAndMockAccountBalanceRequest(
accountBalanceRequest, blockIdentifier, accountAddress);
when(ledgerBlockService.findBlock(1L, HASH)).thenReturn(block);
when(ledgerBlockService.findBlock(1L, HASH)).thenReturn(Optional.of(block));
when(ledgerDataProviderService.findStakeAddressBalanceByAddressAndBlock(accountAddress, 1L))
.thenReturn(Collections.emptyList());

Expand All @@ -185,7 +185,7 @@ void getAccountBalanceStakeAddressWithBlockDtoNullThrowTest() {
AccountBalanceRequest accountBalanceRequest = Mockito.mock(AccountBalanceRequest.class);
AccountIdentifier accountIdentifier = getMockedAccountIdentifierAndMockAccountBalanceRequest(
accountBalanceRequest, blockIdentifier, accountAddress);
when(ledgerBlockService.findBlock(1L, HASH)).thenReturn(null);
when(ledgerBlockService.findBlock(1L, HASH)).thenReturn(Optional.empty());

ApiException actualException = assertThrows(ApiException.class,
() -> accountService.getAccountBalance(accountBalanceRequest));
Expand Down Expand Up @@ -227,7 +227,7 @@ void getAccountBalanceWithStakeAddressAndNullBalanceThrowTest() {
AccountIdentifier accountIdentifier = getMockedAccountIdentifierAndMockAccountBalanceRequest(
accountBalanceRequest, blockIdentifier, accountAddress);
Block block = getMockBlock();
when(ledgerBlockService.findBlock(1L, HASH)).thenReturn(block);
when(ledgerBlockService.findBlock(1L, HASH)).thenReturn(Optional.of(block));
when(ledgerDataProviderService.findStakeAddressBalanceByAddressAndBlock(accountAddress, 1L))
.thenReturn(null);

Expand Down Expand Up @@ -260,7 +260,7 @@ void getAccountCoinsWithCurrenciesPositiveTest() {
when(accountCoinsRequest.getAccountIdentifier()).thenReturn(accountIdentifier);
when(accountCoinsRequest.getCurrencies()).thenReturn(Collections.singletonList(currency));
when(accountIdentifier.getAddress()).thenReturn(accountAddress);
when(currency.getSymbol()).thenReturn(ADA);
when(currency.getSymbol()).thenReturn("ADA");
when(ledgerBlockService.findLatestBlock()).thenReturn(block);
when(ledgerDataProviderService.findUtxoByAddressAndCurrency(accountAddress,
Collections.emptyList())).thenReturn(Collections.singletonList(utxo));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.math.BigInteger;
import java.util.List;
import java.util.Optional;

import org.mockito.InjectMocks;
import org.mockito.Mock;
Expand Down Expand Up @@ -45,12 +46,12 @@ void getBlockByBlockRequest_OK() {
givenProtocolParam();
long index = 1;
String hash = "hash1";
Block expected = newBlock();
Optional<Block> expected = newBlock();
when(ledgerBlockService.findBlock(index, hash)).thenReturn(expected);
//when
Block block = blockService.findBlock(index, hash);
//then
assertThat(block).isEqualTo(expected);
assertThat(block).isEqualTo(expected.orElse(null)); //idea complains on .get()
}

@Test
Expand Down Expand Up @@ -98,8 +99,8 @@ void getBlockByBlockRequest_canNotReadGenesis() {
}


private Block newBlock() {
return new Block(
private Optional<Block> newBlock() {
return Optional.of(new Block(
"hash1",
1L,
2L,
Expand All @@ -111,7 +112,7 @@ private Block newBlock() {
4,
6L, null,
"poolDeposit1"
);
));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.cardanofoundation.rosetta.api.block.service;

import java.util.List;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;

Expand Down Expand Up @@ -45,7 +46,7 @@ void findBlock_Test_OK_tx_blk() {
//given
TransactionBlockDetails tx = generatedDataMap.get(SIMPLE_TRANSACTION.getName());
//when
Block block = ledgerBlockService.findBlock(tx.blockNumber(), tx.blockHash());
Optional<Block> block = ledgerBlockService.findBlock(tx.blockNumber(), tx.blockHash());
//then
assertBlockAndTx(block, tx);
}
Expand All @@ -55,7 +56,7 @@ void findBlock_Test_OK_tx_null() {
//given
TransactionBlockDetails tx = generatedDataMap.get(SIMPLE_TRANSACTION.getName());
//when
Block block = ledgerBlockService.findBlock(tx.blockNumber(), null);
Optional<Block> block = ledgerBlockService.findBlock(tx.blockNumber(), null);
//then
assertBlockAndTx(block, tx);
}
Expand All @@ -65,19 +66,18 @@ void findBlock_Test_OK_null_blk() {
//given
TransactionBlockDetails tx = generatedDataMap.get(SIMPLE_TRANSACTION.getName());
//when
Block block = ledgerBlockService.findBlock(null, tx.blockHash());
Optional<Block> block = ledgerBlockService.findBlock(null, tx.blockHash());
//then
assertBlockAndTx(block, tx);
}

@Test
void findBlock_Test_OK_empty() {
//given
TransactionBlockDetails tx = generatedDataMap.get(SIMPLE_TRANSACTION.getName());
//when
Block block = ledgerBlockService.findBlock(-234L, "#####2");
Optional<Block> block = ledgerBlockService.findBlock(-234L, "#####2");
//then
assertThat(block).isNull();
assertThat(block).isEmpty();
}

@Test
Expand Down Expand Up @@ -213,7 +213,8 @@ void findTransactionsByBlock_Test_stake_pool_tx() {
assertThat(blockTx.getStakeRegistrations()).hasSize(1);

List<StakeRegistrationEntity> entity = entityManager
.createQuery("FROM StakeRegistrationEntity b where b.txHash=:hash", StakeRegistrationEntity.class)
.createQuery("FROM StakeRegistrationEntity b where b.txHash=:hash",
StakeRegistrationEntity.class)
.setParameter("hash", tx.txHash())
.getResultList();
assertThat(entity).isNotNull().hasSize(1);
Expand Down Expand Up @@ -266,7 +267,11 @@ private static void assertBlocks(Block latestBlock, BlockEntity fromBlockB) {
assertThat(latestBlock.getEpochNo()).isEqualTo(fromBlockB.getEpochNumber());
}

private static void assertBlockAndTx(Block block, TransactionBlockDetails tx) {
private static void assertBlockAndTx(Optional<Block> blockOpt, TransactionBlockDetails tx) {
if (blockOpt.isEmpty()) {
throw new AssertionError("Not a block");
}
var block = blockOpt.get();
assertThat(block).isNotNull();
assertThat(block.getHash()).isEqualTo(tx.blockHash());
assertThat(block.getSlotNo()).isEqualTo(tx.blockNumber());
Expand Down

0 comments on commit 4e97a45

Please sign in to comment.