Search in sources :

Example 1 with UtxoAccountsBalancePo

use of io.nuls.utxo.accounts.storage.po.UtxoAccountsBalancePo in project nuls by nuls-io.

the class UtxoAccountsServiceImpl method buildUtxoAccountsBalance.

/**
 * build utxoAccounts Map(address,balance)
 *
 * @param utxoAccountsMap
 * @param coin
 * @param tx
 * @param txIndex
 * @param isInput
 */
private void buildUtxoAccountsBalance(Map<String, UtxoAccountsBalancePo> utxoAccountsMap, Coin coin, Transaction tx, int txIndex, boolean isInput) {
    long netBlockHeight = NulsContext.getInstance().getNetBestBlockHeight();
    // change coin.getOwner() to coin.getAddress() for support multiSig
    String address = AddressTool.getStringAddressByBytes(coin.getAddress());
    UtxoAccountsBalancePo balance = utxoAccountsMap.get(address);
    if (null == balance) {
        balance = new UtxoAccountsBalancePo();
        balance.setOwner(coin.getOwner());
        utxoAccountsMap.put(address, balance);
    }
    if (isInput) {
        if (coin.getLockTime() == -1) {
            // remove balance
            balance.setUnLockedPermanentBalance(balance.getUnLockedPermanentBalance() + (coin.getNa().getValue()));
        }
        balance.setInputBalance(balance.getInputBalance() + (coin.getNa().getValue()));
    } else {
        // add locked balance
        if (coin.getLockTime() == -1) {
            balance.setLockedPermanentBalance(balance.getLockedPermanentBalance() + (coin.getNa().getValue()));
        } else // by time
        if (coin.getLockTime() > TimeService.currentTimeMillis()) {
            LockedBalance lockedBalance = new LockedBalance();
            lockedBalance.setLockedBalance(coin.getNa().getValue());
            lockedBalance.setLockedTime(coin.getLockTime());
            balance.getLockedTimeList().add(lockedBalance);
        } else if (coin.getLockTime() > netBlockHeight) {
            LockedBalance lockedBalance = new LockedBalance();
            lockedBalance.setLockedBalance(coin.getNa().getValue());
            lockedBalance.setLockedTime(coin.getLockTime());
            balance.getLockedHeightList().add(lockedBalance);
        }
        balance.setOutputBalance(balance.getOutputBalance() + (coin.getNa()).getValue());
    }
    // balance.setOwner(coin.getOwner());
    balance.setBlockHeight(tx.getBlockHeight());
    balance.setTxIndex(txIndex);
}
Also used : UtxoAccountsBalancePo(io.nuls.utxo.accounts.storage.po.UtxoAccountsBalancePo) LockedBalance(io.nuls.utxo.accounts.storage.po.LockedBalance)

Example 2 with UtxoAccountsBalancePo

use of io.nuls.utxo.accounts.storage.po.UtxoAccountsBalancePo in project nuls by nuls-io.

the class UtxoAccountsServiceImpl method synBlock.

/**
 * @param blockHeight
 * @return
 */
@Override
public boolean synBlock(long blockHeight) {
    Log.debug("synBlock begin===blockHeight:" + blockHeight);
    Block nodeBlock = utxoAccountsStorageService.getBlock(blockHeight).getData();
    if (nodeBlock == null) {
        Log.error("utxoAccounts getBlock faile,blockHeight:" + blockHeight);
        return false;
    }
    boolean hadRoll = false;
    try {
        // get local pre block info /从本地取上一个已同步的区块
        LocalCacheBlockBalance localLatestCacheBlock = utxoAccountsStorageService.getLocalCacheBlock(blockHeight - 1).getData();
        // rollback judge /判断回滚
        while (localLatestCacheBlock != null && !nodeBlock.getHeader().getPreHash().equals(localLatestCacheBlock.getHash())) {
            // roll back info /进行数据回滚
            rollbackBlock(localLatestCacheBlock);
            blockHeight--;
            // get pre block
            localLatestCacheBlock = utxoAccountsStorageService.getLocalCacheBlock(blockHeight - 1).getData();
            nodeBlock = utxoAccountsStorageService.getBlock(blockHeight).getData();
            hadRoll = true;
        }
        if (hadRoll) {
            return false;
        }
    } catch (NulsException e) {
        Log.error(e);
        Log.error("block syn error======blockHeight:" + blockHeight);
        return false;
    }
    // begin syn block/开始同步区块
    // analysis block/解析区块
    Map<String, UtxoAccountsBalancePo> utxoAccountsMap = new HashMap<>();
    if (!buildUtxoAccountsMap(utxoAccountsMap, nodeBlock)) {
        return false;
    }
    List<UtxoAccountsBalancePo> list = new ArrayList<>();
    LocalCacheBlockBalance localCacheBlockBalance = new LocalCacheBlockBalance();
    // LocalCacheBlockBalance preSnapshot=new LocalCacheBlockBalance();
    try {
        list = utxoAccountsMapToList(utxoAccountsMap, localCacheBlockBalance);
    } catch (NulsException e) {
        Log.info("utxoAccountsMapToList error======blockHeight:" + blockHeight);
        return false;
    }
    localCacheBlockBalance.setHash(nodeBlock.getHeader().getHash());
    localCacheBlockBalance.setPreHash(nodeBlock.getHeader().getPreHash());
    // localCacheBlockBalance.setBalanceList(list);
    localCacheBlockBalance.setBlockHeight(blockHeight);
    // save cache block info/缓存最近解析信息
    utxoAccountsStorageService.saveLocalCacheBlock(blockHeight, localCacheBlockBalance);
    // utxoAccountsStorageService.saveLocalCacheChangeSnapshot(blockHeight,localCacheBlockBalance);
    utxoAccountsStorageService.batchSaveByteUtxoAcountsInfo(list);
    // update latest block height/更新最近高度
    utxoAccountsStorageService.saveHadSynBlockHeight(blockHeight);
    // delete overdue cache data/删除过期缓存数据
    if (blockHeight > UtxoAccountsStorageConstant.MAX_CACHE_BLOCK_NUM) {
        utxoAccountsStorageService.deleteLocalCacheBlock(blockHeight - UtxoAccountsStorageConstant.MAX_CACHE_BLOCK_NUM);
    }
    Log.debug("utxoAccounts synBlock success==blockHeight:" + blockHeight);
    return true;
}
Also used : UtxoAccountsBalancePo(io.nuls.utxo.accounts.storage.po.UtxoAccountsBalancePo) NulsException(io.nuls.kernel.exception.NulsException) Block(io.nuls.kernel.model.Block) LocalCacheBlockBalance(io.nuls.utxo.accounts.storage.po.LocalCacheBlockBalance)

Example 3 with UtxoAccountsBalancePo

use of io.nuls.utxo.accounts.storage.po.UtxoAccountsBalancePo in project nuls by nuls-io.

the class UtxoAccountsResource method get.

@GET
@Path("/{address}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation("[查询] 查询账户信息")
@ApiResponses(value = { @ApiResponse(code = 200, message = "success", response = RpcClientResult.class) })
public RpcClientResult get(@ApiParam(name = "address", value = "账户地址", required = true) @PathParam("address") String address) {
    if (!AddressTool.validAddress(address)) {
        return Result.getFailed(AccountErrorCode.ADDRESS_ERROR).toRpcClientResult();
    }
    try {
        Result<UtxoAccountsBalancePo> utxoAccountsBalance = utxoAccountsStorageService.getUtxoAccountsBalanceByAddress(AddressTool.getAddress(address));
        long synBlockHeight = utxoAccountsStorageService.getHadSynBlockHeight();
        if (null == utxoAccountsBalance || null == utxoAccountsBalance.getData()) {
            return Result.getFailed(UtxoAccountsErrorCode.DATA_NOT_FOUND).toRpcClientResult();
        }
        UtxoAccountsBalancePo dbAccountsBalance = utxoAccountsBalance.getData();
        AccountBalanceDto accountBalance = new AccountBalanceDto();
        accountBalance.setLockedTimeList(new ArrayList<>());
        accountBalance.setLockedHeightList(new ArrayList<>());
        accountBalance.setAddress(address);
        long totalNa = dbAccountsBalance.getOutputBalance() - (dbAccountsBalance.getInputBalance());
        totalNa += dbAccountsBalance.getContractToBalance();
        totalNa -= dbAccountsBalance.getContractFromBalance();
        accountBalance.setNuls(new BigDecimal(totalNa).toPlainString());
        long timeLockedNa = 0;
        long heightLockedNa = 0;
        long permanentLockedNa = dbAccountsBalance.getLockedPermanentBalance() - (dbAccountsBalance.getUnLockedPermanentBalance());
        long lockedNa = permanentLockedNa;
        List<LockedBalance> timeLockedBalance = dbAccountsBalance.getLockedTimeList();
        long currentTime = TimeService.currentTimeMillis();
        for (LockedBalance balance : timeLockedBalance) {
            if (balance.getLockedTime() > currentTime) {
                lockedNa += balance.getLockedBalance();
                timeLockedNa += balance.getLockedBalance();
                accountBalance.getLockedTimeList().add(balance);
            } else {
                break;
            }
        }
        List<LockedBalance> heightLockedBalance = dbAccountsBalance.getLockedHeightList();
        for (LockedBalance balance : heightLockedBalance) {
            if (balance.getLockedTime() > synBlockHeight) {
                lockedNa += balance.getLockedBalance();
                heightLockedNa += balance.getLockedBalance();
                accountBalance.getLockedHeightList().add(balance);
            } else {
                break;
            }
        }
        accountBalance.setPermanentLocked(new BigDecimal(permanentLockedNa).toPlainString());
        accountBalance.setLocked(new BigDecimal(lockedNa).toPlainString());
        accountBalance.setTimeLocked(new BigDecimal(timeLockedNa).toPlainString());
        accountBalance.setHeightLocked(new BigDecimal(heightLockedNa).toPlainString());
        accountBalance.setSynBlockHeight(String.valueOf(synBlockHeight));
        long netHeight = NulsContext.getInstance().getNetBestBlockHeight();
        accountBalance.setNetBlockHeight(String.valueOf(netHeight));
        accountBalance.setContractIn(String.valueOf(dbAccountsBalance.getContractToBalance()));
        accountBalance.setContractOut(String.valueOf(dbAccountsBalance.getContractFromBalance()));
        return Result.getSuccess().setData(accountBalance).toRpcClientResult();
    } catch (NulsException e) {
        Log.error(e);
    }
    return Result.getFailed(UtxoAccountsErrorCode.SYS_UNKOWN_EXCEPTION).toRpcClientResult();
}
Also used : UtxoAccountsBalancePo(io.nuls.utxo.accounts.storage.po.UtxoAccountsBalancePo) LockedBalance(io.nuls.utxo.accounts.storage.po.LockedBalance) AccountBalanceDto(io.nuls.utxo.accounts.rpc.dto.AccountBalanceDto) NulsException(io.nuls.kernel.exception.NulsException) BigDecimal(java.math.BigDecimal) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 4 with UtxoAccountsBalancePo

use of io.nuls.utxo.accounts.storage.po.UtxoAccountsBalancePo in project nuls by nuls-io.

the class UtxoAccountsServiceImpl method rollbackBlock.

public boolean rollbackBlock(LocalCacheBlockBalance block) throws NulsException {
    Log.info("rollbackBlock:" + block.getBlockHeight());
    if (block.getBlockHeight() == 0) {
        utxoAccountsStorageService.deleteLocalCacheBlock(block.getBlockHeight());
        return true;
    }
    // 更新最新高度
    utxoAccountsStorageService.saveHadSynBlockHeight(block.getBlockHeight() - 1);
    LocalCacheBlockBalance localPreBlock = utxoAccountsStorageService.getLocalCacheBlock(block.getBlockHeight()).getData();
    // 批量更新上一区块数据
    List<UtxoAccountsBalancePo> list = localPreBlock.getBalanceList();
    if (list.size() > 0) {
        utxoAccountsStorageService.batchSaveByteUtxoAcountsInfo(list);
    }
    // 删除本地缓存区块
    utxoAccountsStorageService.deleteLocalCacheBlock(block.getBlockHeight());
    return true;
}
Also used : UtxoAccountsBalancePo(io.nuls.utxo.accounts.storage.po.UtxoAccountsBalancePo) LocalCacheBlockBalance(io.nuls.utxo.accounts.storage.po.LocalCacheBlockBalance)

Example 5 with UtxoAccountsBalancePo

use of io.nuls.utxo.accounts.storage.po.UtxoAccountsBalancePo in project nuls by nuls-io.

the class UtxoAccountsServiceImpl method buildContractTranfersBalance.

/**
 * @param utxoAccountsMap
 * @param transferList
 * @param blockHeight
 * @param txIndex
 */
private void buildContractTranfersBalance(Map<String, UtxoAccountsBalancePo> utxoAccountsMap, List<ContractTransfer> transferList, long blockHeight, int txIndex) {
    for (ContractTransfer contractTransfer : transferList) {
        byte[] from = contractTransfer.getFrom();
        byte[] to = contractTransfer.getTo();
        String addressFrom = AddressTool.getStringAddressByBytes(from);
        String addressTo = AddressTool.getStringAddressByBytes(to);
        UtxoAccountsBalancePo balanceFrom = utxoAccountsMap.get(addressFrom);
        UtxoAccountsBalancePo balanceTo = utxoAccountsMap.get(addressTo);
        if (null == balanceFrom) {
            balanceFrom = new UtxoAccountsBalancePo();
            balanceFrom.setOwner(from);
            utxoAccountsMap.put(addressFrom, balanceFrom);
        }
        balanceFrom.setBlockHeight(blockHeight);
        balanceFrom.setTxIndex(txIndex);
        balanceFrom.setContractFromBalance(balanceFrom.getContractFromBalance() + contractTransfer.getValue().getValue());
        if (null == balanceTo) {
            balanceTo = new UtxoAccountsBalancePo();
            balanceTo.setOwner(to);
            utxoAccountsMap.put(addressTo, balanceTo);
        }
        balanceTo.setBlockHeight(blockHeight);
        balanceTo.setTxIndex(txIndex);
        balanceTo.setContractToBalance(balanceTo.getContractToBalance() + contractTransfer.getValue().getValue());
    }
}
Also used : UtxoAccountsBalancePo(io.nuls.utxo.accounts.storage.po.UtxoAccountsBalancePo) ContractTransfer(io.nuls.contract.dto.ContractTransfer)

Aggregations

UtxoAccountsBalancePo (io.nuls.utxo.accounts.storage.po.UtxoAccountsBalancePo)10 NulsException (io.nuls.kernel.exception.NulsException)5 LockedBalance (io.nuls.utxo.accounts.storage.po.LockedBalance)4 LocalCacheBlockBalance (io.nuls.utxo.accounts.storage.po.LocalCacheBlockBalance)3 AccountBalanceDto (io.nuls.utxo.accounts.rpc.dto.AccountBalanceDto)2 BigDecimal (java.math.BigDecimal)2 GET (javax.ws.rs.GET)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 ContractTransfer (io.nuls.contract.dto.ContractTransfer)1 Block (io.nuls.kernel.model.Block)1 Script (io.nuls.kernel.script.Script)1 UtxoAccountsBalance (io.nuls.utxo.accounts.model.UtxoAccountsBalance)1