Search in sources :

Example 21 with Coin

use of io.nuls.kernel.model.Coin in project nuls by nuls-io.

the class BalanceManager method calBalanceByAddress.

/**
 * 计算账户的余额,这个方法应该和获取余额方法互斥,避免并发导致数据不准确
 */
public Balance calBalanceByAddress(byte[] address) throws NulsException {
    lock.lock();
    try {
        if (accountService.getAccount(address).isFailed()) {
            return null;
        }
        List<Coin> coinList = getCoinListByAddress(address);
        Collections.sort(coinList, CoinComparator.getInstance());
        BalanceCacheEntity balanceCacheEntity = new BalanceCacheEntity();
        Na usable = Na.ZERO;
        Na locked = Na.ZERO;
        for (Coin coin : coinList) {
            if (coin.usable()) {
                usable = usable.add(coin.getNa());
            } else {
                locked = locked.add(coin.getNa());
                long lockTime = coin.getLockTime();
                // the consensus lock type
                if (lockTime <= 0L) {
                    continue;
                }
                // the height lock type
                if (balanceCacheEntity.getLowestLockHeigh() == 0L || (lockTime < NulsConstant.BlOCKHEIGHT_TIME_DIVIDE && lockTime < balanceCacheEntity.getLowestLockHeigh())) {
                    balanceCacheEntity.setLowestLockHeigh(lockTime);
                    continue;
                }
                // the time lock type
                if (balanceCacheEntity.getEarlistLockTime() == 0L || (lockTime > NulsConstant.BlOCKHEIGHT_TIME_DIVIDE && lockTime < balanceCacheEntity.getEarlistLockTime())) {
                    balanceCacheEntity.setEarlistLockTime(lockTime);
                    continue;
                }
            }
        }
        Balance balance = new Balance();
        balance.setUsable(usable);
        balance.setLocked(locked);
        balance.setBalance(usable.add(locked));
        balanceCacheEntity.setBalance(balance);
        balanceMap.put(AddressTool.getStringAddressByBytes(address), balanceCacheEntity);
        return balance;
    } finally {
        lock.unlock();
    }
}
Also used : Coin(io.nuls.kernel.model.Coin) Na(io.nuls.kernel.model.Na) Balance(io.nuls.account.model.Balance)

Example 22 with Coin

use of io.nuls.kernel.model.Coin in project nuls by nuls-io.

the class UtxoResource method getUtxoByAddressAndLimit.

@GET
@Path("/limit/{address}/{limit}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "根据address和limit查询UTXO")
@ApiResponses(value = { @ApiResponse(code = 200, message = "success", response = AccountUtxoDto.class) })
public RpcClientResult getUtxoByAddressAndLimit(@ApiParam(name = "address", value = "地址", required = true) @PathParam("address") String address, @ApiParam(name = "limit", value = "数量", required = true) @PathParam("limit") Integer limit) {
    if (StringUtils.isBlank(address) || limit == null) {
        return Result.getFailed(LedgerErrorCode.NULL_PARAMETER).toRpcClientResult();
    }
    if (!AddressTool.validAddress(address)) {
        return Result.getFailed(LedgerErrorCode.PARAMETER_ERROR).toRpcClientResult();
    }
    Result result = null;
    try {
        List<Coin> coinList = getAllUtxoByAddress(address);
        int limitValue = limit.intValue();
        boolean isLoadAll = (limitValue == 0);
        AccountUtxoDto accountUtxoDto = new AccountUtxoDto();
        List<UtxoDto> list = new LinkedList<>();
        int i = 0;
        for (Coin coin : coinList) {
            if (!coin.usable()) {
                continue;
            }
            if (coin.getNa().equals(Na.ZERO)) {
                continue;
            }
            if (!isLoadAll) {
                if (i >= limitValue) {
                    break;
                }
                i++;
            }
            list.add(new UtxoDto(coin));
        }
        accountUtxoDto.setUtxoDtoList(list);
        result = Result.getSuccess().setData(accountUtxoDto);
        return result.toRpcClientResult();
    } catch (Exception e) {
        Log.error(e);
        result = Result.getFailed(LedgerErrorCode.SYS_UNKOWN_EXCEPTION);
        return result.toRpcClientResult();
    }
}
Also used : Coin(io.nuls.kernel.model.Coin) NulsException(io.nuls.kernel.exception.NulsException) RpcClientResult(io.nuls.kernel.model.RpcClientResult) Result(io.nuls.kernel.model.Result) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 23 with Coin

use of io.nuls.kernel.model.Coin in project nuls by nuls-io.

the class UtxoResource method getAllUtxoByAddress.

private List<Coin> getAllUtxoByAddress(String address) {
    List<Coin> coinList = new ArrayList<>();
    byte[] addressBytes = AddressTool.getAddress(address);
    List<Entry<byte[], byte[]>> coinBytesList = utxoLedgerUtxoStorageService.getAllUtxoEntryBytes();
    Coin coin;
    for (Entry<byte[], byte[]> coinEntryBytes : coinBytesList) {
        coin = new Coin();
        try {
            coin.parse(coinEntryBytes.getValue(), 0);
        } catch (NulsException e) {
            Log.info("parse coin form db error");
            continue;
        }
        // if (Arrays.equals(coin.(), addressBytes))
        if (Arrays.equals(coin.getAddress(), addressBytes)) {
            coin.setOwner(coinEntryBytes.getKey());
            coinList.add(coin);
        }
    }
    Collections.sort(coinList, CoinComparator.getInstance());
    return coinList;
}
Also used : Coin(io.nuls.kernel.model.Coin) Entry(io.nuls.db.model.Entry) NulsException(io.nuls.kernel.exception.NulsException)

Example 24 with Coin

use of io.nuls.kernel.model.Coin in project nuls by nuls-io.

the class UtxoResource method getInfo.

@GET
@Path("/info")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "查询代币情况")
@ApiResponses(value = { @ApiResponse(code = 200, message = "success", response = TokenInfoDto.class) })
public RpcClientResult getInfo() throws NulsException {
    long height = NulsContext.getInstance().getBestHeight();
    List<Entry<byte[], byte[]>> coinBytesList = utxoLedgerUtxoStorageService.getAllUtxoEntryBytes();
    double totalNuls = 0d;
    double lockedNuls = 0d;
    Map<String, Holder> map = new HashMap<>();
    Coin coin = new Coin();
    int index = 0;
    for (Entry<byte[], byte[]> coinEntryBytes : coinBytesList) {
        coin.parse(coinEntryBytes.getValue(), 0);
        double value = coin.getNa().toDouble();
        String address = AddressTool.getStringAddressByBytes(coin.getOwner());
        Holder holder = map.get(address);
        if (null == holder) {
            holder = new Holder();
            holder.setAddress(address);
            map.put(address, holder);
        }
        holder.addTotal(value);
        totalNuls = DoubleUtils.sum(totalNuls, value);
        if (coin.getLockTime() == -1 || coin.getLockTime() > System.currentTimeMillis() || (coin.getLockTime() < 1531152000000L && coin.getLockTime() > height)) {
            holder.addLocked(value);
            lockedNuls = DoubleUtils.sum(lockedNuls, value);
        }
        System.out.println(index++);
    }
    Result<TokenInfoDto> result = Result.getSuccess();
    TokenInfoDto info = new TokenInfoDto();
    info.setTotalNuls(DoubleUtils.getRoundStr(totalNuls, 8, true));
    info.setLockedNuls(DoubleUtils.getRoundStr(lockedNuls, 8, true));
    List<Holder> holderList = new ArrayList<>(map.values());
    Collections.sort(holderList);
    List<HolderDto> dtoList = new ArrayList<>();
    for (Holder holder : holderList) {
        HolderDto dto = new HolderDto(holder);
        dtoList.add(dto);
    }
    info.setAddressList(dtoList);
    result.setData(info);
    return result.toRpcClientResult();
}
Also used : Coin(io.nuls.kernel.model.Coin) Entry(io.nuls.db.model.Entry) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 25 with Coin

use of io.nuls.kernel.model.Coin in project nuls by nuls-io.

the class UtxoLedgerUtxoStorageServiceImpl method getUtxo.

@Override
public Coin getUtxo(byte[] owner) {
    byte[] utxoBytes = getUtxoBytes(owner);
    Coin coin = null;
    try {
        if (utxoBytes != null) {
            coin = new Coin();
            coin.parse(utxoBytes, 0);
        }
    } catch (NulsException e) {
        Log.error(e);
        return null;
    }
    return coin;
}
Also used : Coin(io.nuls.kernel.model.Coin) NulsException(io.nuls.kernel.exception.NulsException)

Aggregations

Coin (io.nuls.kernel.model.Coin)31 NulsException (io.nuls.kernel.exception.NulsException)16 Na (io.nuls.kernel.model.Na)8 Entry (io.nuls.db.model.Entry)6 ValidateResult (io.nuls.kernel.validate.ValidateResult)6 CoinData (io.nuls.kernel.model.CoinData)5 TransactionSignature (io.nuls.kernel.script.TransactionSignature)4 ContractBalance (io.nuls.contract.ledger.module.ContractBalance)3 Result (io.nuls.kernel.model.Result)3 LedgerUtil.asString (io.nuls.ledger.util.LedgerUtil.asString)3 ArrayList (java.util.ArrayList)3 GET (javax.ws.rs.GET)3 Path (javax.ws.rs.Path)3 Produces (javax.ws.rs.Produces)3 AgentPo (io.nuls.consensus.poc.storage.po.AgentPo)2 DepositPo (io.nuls.consensus.poc.storage.po.DepositPo)2 ECKey (io.nuls.core.tools.crypto.ECKey)2 RpcClientResult (io.nuls.kernel.model.RpcClientResult)2 Transaction (io.nuls.kernel.model.Transaction)2 Script (io.nuls.kernel.script.Script)2