Search in sources :

Example 6 with Deposit

use of io.nuls.consensus.poc.protocol.entity.Deposit in project nuls by nuls-io.

the class ConsensusTool method calcReward.

private static List<Coin> calcReward(List<Transaction> txList, MeetingMember self, MeetingRound localRound, long unlockHeight) {
    List<Coin> rewardList = new ArrayList<>();
    if (NulsContext.isNetFinished(NulsConfig.MODULES_CONFIG.getCfgValue(PocConsensusProtocolConstant.CFG_CONSENSUS_SECTION, PocConsensusProtocolConstant.STOP_DELAY, Integer.MAX_VALUE))) {
        return rewardList;
    }
    if (self.getOwnDeposit().getValue() == Na.ZERO.getValue()) {
        long totalFee = 0;
        for (Transaction tx : txList) {
            totalFee += tx.getFee().getValue();
        }
        if (totalFee == 0L) {
            return rewardList;
        }
        double caReward = totalFee;
        Coin agentReword = new Coin(self.getRewardAddress(), Na.valueOf((long) caReward), unlockHeight);
        rewardList.add(agentReword);
        return rewardList;
    }
    long totalFee = 0;
    for (Transaction tx : txList) {
        totalFee += tx.getFee().getValue();
    }
    double totalAll = DoubleUtils.mul(localRound.getMemberCount(), PocConsensusConstant.BLOCK_REWARD.getValue());
    double commissionRate = DoubleUtils.div(self.getCommissionRate(), 100, 2);
    double agentWeight = DoubleUtils.mul(DoubleUtils.sum(self.getOwnDeposit().getValue(), self.getTotalDeposit().getValue()), self.getCalcCreditVal());
    double blockReword = totalFee;
    if (localRound.getTotalWeight() > 0d && agentWeight > 0d) {
        blockReword = DoubleUtils.sum(blockReword, DoubleUtils.mul(totalAll, DoubleUtils.div(agentWeight, localRound.getTotalWeight())));
    }
    if (blockReword == 0d) {
        return rewardList;
    }
    long realTotalAllDeposit = self.getOwnDeposit().getValue() + self.getTotalDeposit().getValue();
    double caReward = DoubleUtils.mul(blockReword, DoubleUtils.div(self.getOwnDeposit().getValue(), realTotalAllDeposit));
    for (Deposit deposit : self.getDepositList()) {
        double weight = DoubleUtils.div(deposit.getDeposit().getValue(), realTotalAllDeposit);
        if (Arrays.equals(deposit.getAddress(), self.getAgentAddress())) {
            caReward = caReward + DoubleUtils.mul(blockReword, weight);
        } else {
            double reward = DoubleUtils.mul(blockReword, weight);
            double fee = DoubleUtils.mul(reward, commissionRate);
            caReward = caReward + fee;
            double hisReward = DoubleUtils.sub(reward, fee);
            if (hisReward == 0D) {
                continue;
            }
            Na depositReward = Na.valueOf(DoubleUtils.longValue(hisReward));
            Coin rewardCoin = null;
            for (Coin coin : rewardList) {
                if (Arrays.equals(coin.getAddress(), deposit.getAddress())) {
                    rewardCoin = coin;
                    break;
                }
            }
            if (rewardCoin == null) {
                rewardCoin = new Coin(deposit.getAddress(), depositReward, unlockHeight);
                rewardList.add(rewardCoin);
            } else {
                rewardCoin.setNa(rewardCoin.getNa().add(depositReward));
            }
        }
    }
    rewardList.sort(new Comparator<Coin>() {

        @Override
        public int compare(Coin o1, Coin o2) {
            return Arrays.hashCode(o1.getOwner()) > Arrays.hashCode(o2.getOwner()) ? 1 : -1;
        }
    });
    Coin agentReward = new Coin(self.getRewardAddress(), Na.valueOf(DoubleUtils.longValue(caReward)), unlockHeight);
    rewardList.add(0, agentReward);
    return rewardList;
}
Also used : Deposit(io.nuls.consensus.poc.protocol.entity.Deposit) DepositTransaction(io.nuls.consensus.poc.protocol.tx.DepositTransaction) YellowPunishTransaction(io.nuls.consensus.poc.protocol.tx.YellowPunishTransaction) CreateAgentTransaction(io.nuls.consensus.poc.protocol.tx.CreateAgentTransaction) ContractTransaction(io.nuls.contract.entity.tx.ContractTransaction) CoinBaseTransaction(io.nuls.protocol.model.tx.CoinBaseTransaction)

Example 7 with Deposit

use of io.nuls.consensus.poc.protocol.entity.Deposit in project nuls by nuls-io.

the class DepositTxValidator method validate.

@Override
public ValidateResult validate(DepositTransaction tx) throws NulsException {
    if (null == tx || null == tx.getTxData() || null == tx.getTxData().getAgentHash() || null == tx.getTxData().getDeposit() || null == tx.getTxData().getAddress()) {
        return ValidateResult.getFailedResult(this.getClass().getName(), TransactionErrorCode.TX_DATA_VALIDATION_ERROR);
    }
    Deposit deposit = tx.getTxData();
    AgentPo agentPo = agentStorageService.get(deposit.getAgentHash());
    if (null == agentPo || agentPo.getDelHeight() > 0) {
        return ValidateResult.getFailedResult(this.getClass().getName(), PocConsensusErrorCode.AGENT_NOT_EXIST);
    }
    List<DepositPo> poList = this.getDepositListByAgent(deposit.getAgentHash());
    if (null != poList && poList.size() >= PocConsensusProtocolConstant.MAX_ACCEPT_NUM_OF_DEPOSIT) {
        return ValidateResult.getFailedResult(this.getClass().getName(), PocConsensusErrorCode.DEPOSIT_OVER_COUNT);
    }
    Na limit = PocConsensusProtocolConstant.ENTRUSTER_DEPOSIT_LOWER_LIMIT;
    Na max = PocConsensusProtocolConstant.SUM_OF_DEPOSIT_OF_AGENT_UPPER_LIMIT;
    Na total = Na.ZERO;
    for (DepositPo cd : poList) {
        total = total.add(cd.getDeposit());
    }
    if (limit.isGreaterThan(deposit.getDeposit())) {
        return ValidateResult.getFailedResult(this.getClass().getName(), PocConsensusErrorCode.DEPOSIT_NOT_ENOUGH);
    }
    if (max.isLessThan(total.add(deposit.getDeposit()))) {
        return ValidateResult.getFailedResult(this.getClass().getName(), PocConsensusErrorCode.DEPOSIT_TOO_MUCH);
    }
    if (!isDepositOk(deposit.getDeposit(), tx.getCoinData())) {
        return ValidateResult.getFailedResult(this.getClass().getName(), SeverityLevelEnum.FLAGRANT_FOUL, PocConsensusErrorCode.DEPOSIT_ERROR);
    }
    TransactionSignature sig = new TransactionSignature();
    try {
        sig.parse(tx.getTransactionSignature(), 0);
    } catch (NulsException e) {
        Log.error(e);
        return ValidateResult.getFailedResult(this.getClass().getName(), e.getErrorCode());
    }
    if (!SignatureUtil.containsAddress(tx, deposit.getAddress())) {
        ValidateResult result = ValidateResult.getFailedResult(this.getClass().getName(), KernelErrorCode.SIGNATURE_ERROR);
        result.setLevel(SeverityLevelEnum.FLAGRANT_FOUL);
        return result;
    }
    CoinData coinData = tx.getCoinData();
    Set<String> addressSet = new HashSet<>();
    int lockCount = 0;
    for (Coin coin : coinData.getTo()) {
        if (coin.getLockTime() == PocConsensusConstant.CONSENSUS_LOCK_TIME) {
            lockCount++;
        }
        // addressSet.add(AddressTool.getStringAddressByBytes(coin.()));
        addressSet.add(AddressTool.getStringAddressByBytes(coin.getAddress()));
    }
    if (lockCount > 1) {
        return ValidateResult.getFailedResult(this.getClass().getName(), TransactionErrorCode.TX_DATA_VALIDATION_ERROR);
    }
    if (addressSet.size() > 1) {
        return ValidateResult.getFailedResult(this.getClass().getName(), TransactionErrorCode.TX_DATA_VALIDATION_ERROR);
    }
    return ValidateResult.getSuccessResult();
}
Also used : Deposit(io.nuls.consensus.poc.protocol.entity.Deposit) CoinData(io.nuls.kernel.model.CoinData) ValidateResult(io.nuls.kernel.validate.ValidateResult) TransactionSignature(io.nuls.kernel.script.TransactionSignature) Coin(io.nuls.kernel.model.Coin) DepositPo(io.nuls.consensus.poc.storage.po.DepositPo) Na(io.nuls.kernel.model.Na) NulsException(io.nuls.kernel.exception.NulsException) AgentPo(io.nuls.consensus.poc.storage.po.AgentPo)

Example 8 with Deposit

use of io.nuls.consensus.poc.protocol.entity.Deposit in project nuls by nuls-io.

the class ChainContainerTest method addTx.

protected void addTx(Block block) {
    BlockHeader blockHeader = block.getHeader();
    List<Transaction> txs = block.getTxs();
    Transaction<Agent> agentTx = new CreateAgentTransaction();
    Agent agent = new Agent();
    agent.setPackingAddress(AddressTool.getAddress(ecKey.getPubKey()));
    agent.setAgentAddress(AddressTool.getAddress(ecKey.getPubKey()));
    agent.setTime(System.currentTimeMillis());
    agent.setDeposit(Na.NA.multiply(20000));
    agent.setCommissionRate(0.3d);
    agent.setBlockHeight(blockHeader.getHeight());
    agentTx.setTxData(agent);
    agentTx.setTime(agent.getTime());
    agentTx.setBlockHeight(blockHeader.getHeight());
    NulsSignData signData = signDigest(agentTx.getHash().getDigestBytes(), ecKey);
    agentTx.setTransactionSignature(signData.getSignBytes());
    // add the agent tx into agent list
    txs.add(agentTx);
    // new a deposit
    Deposit deposit = new Deposit();
    deposit.setAddress(AddressTool.getAddress(ecKey.getPubKey()));
    deposit.setAgentHash(agentTx.getHash());
    deposit.setTime(System.currentTimeMillis());
    deposit.setDeposit(Na.NA.multiply(200000));
    deposit.setBlockHeight(blockHeader.getHeight());
    DepositTransaction depositTx = new DepositTransaction();
    depositTx.setTime(deposit.getTime());
    depositTx.setTxData(deposit);
    depositTx.setBlockHeight(blockHeader.getHeight());
    txs.add(depositTx);
}
Also used : Agent(io.nuls.consensus.poc.protocol.entity.Agent) Deposit(io.nuls.consensus.poc.protocol.entity.Deposit) DepositTransaction(io.nuls.consensus.poc.protocol.tx.DepositTransaction) DepositTransaction(io.nuls.consensus.poc.protocol.tx.DepositTransaction) CreateAgentTransaction(io.nuls.consensus.poc.protocol.tx.CreateAgentTransaction) CreateAgentTransaction(io.nuls.consensus.poc.protocol.tx.CreateAgentTransaction)

Example 9 with Deposit

use of io.nuls.consensus.poc.protocol.entity.Deposit in project nuls by nuls-io.

the class PocConsensusResource method getAgentListByDepositAddress.

@GET
@Path("/agent/address/{address}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "根据地址查询其委托的节点信息列表 [3.6.12]", notes = "result.data.page.list: List<Map<String, Object>>")
@ApiResponses(value = { @ApiResponse(code = 200, message = "success", response = Page.class) })
public RpcClientResult getAgentListByDepositAddress(@ApiParam(name = "pageNumber", value = "页码") @QueryParam("pageNumber") Integer pageNumber, @ApiParam(name = "pageSize", value = "每页条数") @QueryParam("pageSize") Integer pageSize, @ApiParam(name = "address", value = "账户地址", required = true) @PathParam("address") String address) {
    AssertUtil.canNotEmpty(address);
    if (!AddressTool.validAddress(address)) {
        return Result.getFailed(AccountErrorCode.ADDRESS_ERROR).toRpcClientResult();
    }
    if (null == pageNumber || pageNumber == 0) {
        pageNumber = 1;
    }
    if (null == pageSize || pageSize == 0) {
        pageSize = 10;
    }
    if (pageNumber < 0 || pageSize < 0 || pageSize > 100) {
        return Result.getFailed(KernelErrorCode.PARAMETER_ERROR).toRpcClientResult();
    }
    Result result = Result.getSuccess();
    List<Deposit> allList = PocConsensusContext.getChainManager().getMasterChain().getChain().getDepositList();
    long startBlockHeight = NulsContext.getInstance().getBestHeight();
    byte[] addressBytes = AddressTool.getAddress(address);
    Set<NulsDigestData> agentHashSet = new HashSet<>();
    for (Deposit deposit : allList) {
        if (deposit.getDelHeight() != -1L && deposit.getDelHeight() <= startBlockHeight) {
            continue;
        }
        if (deposit.getBlockHeight() > startBlockHeight || deposit.getBlockHeight() < 0L) {
            continue;
        }
        if (!Arrays.equals(deposit.getAddress(), addressBytes)) {
            continue;
        }
        agentHashSet.add(deposit.getAgentHash());
    }
    List<Agent> allAgentList = PocConsensusContext.getChainManager().getMasterChain().getChain().getAgentList();
    List<Agent> agentList = new ArrayList<>();
    Agent ownAgent = null;
    for (int i = allAgentList.size() - 1; i >= 0; i--) {
        Agent agent = allAgentList.get(i);
        if (agent.getDelHeight() != -1L && agent.getDelHeight() <= startBlockHeight) {
            continue;
        } else if (agent.getBlockHeight() > startBlockHeight || agent.getBlockHeight() < 0L) {
            continue;
        }
        if (Arrays.equals(agent.getAgentAddress(), addressBytes)) {
            ownAgent = agent;
            continue;
        }
        if (!agentHashSet.contains(agent.getTxHash())) {
            continue;
        }
        agentList.add(agent);
    }
    if (null != ownAgent) {
        agentList.add(0, ownAgent);
    }
    int start = pageNumber * pageSize - pageSize;
    Page<AgentDTO> page = new Page<>(pageNumber, pageSize, agentList.size());
    if (start >= agentList.size()) {
        result.setData(page);
        return result.toRpcClientResult();
    }
    fillAgentList(agentList, allList);
    List<AgentDTO> resultList = new ArrayList<>();
    for (int i = start; i < agentList.size() && i < (start + pageSize); i++) {
        Agent agent = agentList.get(i);
        resultList.add(new AgentDTO(agent, accountService.getAlias(agent.getAgentAddress()).getData()));
    }
    page.setList(resultList);
    result.setData(page);
    return result.toRpcClientResult();
}
Also used : Deposit(io.nuls.consensus.poc.protocol.entity.Deposit) CancelDeposit(io.nuls.consensus.poc.protocol.entity.CancelDeposit) StopAgent(io.nuls.consensus.poc.protocol.entity.StopAgent) Agent(io.nuls.consensus.poc.protocol.entity.Agent) Page(io.nuls.core.tools.page.Page) CoinDataResult(io.nuls.account.ledger.model.CoinDataResult)

Example 10 with Deposit

use of io.nuls.consensus.poc.protocol.entity.Deposit in project nuls by nuls-io.

the class PocConsensusResource method getInfo.

@GET
@Path("/address/{address}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation("获取钱包内某个账户参与共识信息")
@ApiResponses(value = { @ApiResponse(code = 200, message = "success", response = Map.class) })
public RpcClientResult getInfo(@ApiParam(name = "address", value = "钱包账户地", required = true) @PathParam("address") String address) {
    if (!AddressTool.validAddress(StringUtils.formatStringPara(address))) {
        return Result.getFailed(AccountErrorCode.ADDRESS_ERROR).toRpcClientResult();
    }
    Result accountResult = accountService.getAccount(address);
    if (accountResult.isFailed()) {
        return accountResult.toRpcClientResult();
    }
    // Account account = (Account) accountResult.getData();
    Result result = Result.getSuccess();
    AccountConsensusInfoDTO dto = new AccountConsensusInfoDTO();
    List<Agent> allAgentList = PocConsensusContext.getChainManager().getMasterChain().getChain().getAgentList();
    long startBlockHeight = NulsContext.getInstance().getBestHeight();
    int agentCount = 0;
    String agentHash = null;
    byte[] addressBytes = AddressTool.getAddress(address);
    for (int i = allAgentList.size() - 1; i >= 0; i--) {
        Agent agent = allAgentList.get(i);
        if (agent.getDelHeight() != -1L && agent.getDelHeight() <= startBlockHeight) {
            continue;
        } else if (agent.getBlockHeight() > startBlockHeight || agent.getBlockHeight() < 0L) {
            continue;
        }
        if (Arrays.equals(agent.getAgentAddress(), addressBytes)) {
            agentCount = 1;
            agentHash = agent.getTxHash().getDigestHex();
            break;
        }
    }
    List<Deposit> depositList = PocConsensusContext.getChainManager().getMasterChain().getChain().getDepositList();
    Set<NulsDigestData> agentSet = new HashSet<>();
    long totalDeposit = 0;
    for (Deposit deposit : depositList) {
        if (deposit.getDelHeight() != -1L && deposit.getDelHeight() <= startBlockHeight) {
            continue;
        }
        if (deposit.getBlockHeight() > startBlockHeight || deposit.getBlockHeight() < 0L) {
            continue;
        }
        if (!Arrays.equals(deposit.getAddress(), addressBytes)) {
            continue;
        }
        agentSet.add(deposit.getAgentHash());
        totalDeposit += deposit.getDeposit().getValue();
    }
    dto.setAgentCount(agentCount);
    dto.setAgentHash(agentHash);
    dto.setJoinAgentCount(agentSet.size());
    dto.setReward(this.rewardCacheService.getReward(address).getValue());
    dto.setRewardOfDay(rewardCacheService.getRewardToday(address).getValue());
    dto.setTotalDeposit(totalDeposit);
    try {
        dto.setUsableBalance(accountLedgerService.getBalance(addressBytes).getData().getUsable().getValue());
    } catch (Exception e) {
        Log.error(e);
        dto.setUsableBalance(0L);
    }
    result.setData(dto);
    return result.toRpcClientResult();
}
Also used : StopAgent(io.nuls.consensus.poc.protocol.entity.StopAgent) Agent(io.nuls.consensus.poc.protocol.entity.Agent) Deposit(io.nuls.consensus.poc.protocol.entity.Deposit) CancelDeposit(io.nuls.consensus.poc.protocol.entity.CancelDeposit) NulsException(io.nuls.kernel.exception.NulsException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NulsRuntimeException(io.nuls.kernel.exception.NulsRuntimeException) IOException(java.io.IOException) CoinDataResult(io.nuls.account.ledger.model.CoinDataResult)

Aggregations

Deposit (io.nuls.consensus.poc.protocol.entity.Deposit)27 Agent (io.nuls.consensus.poc.protocol.entity.Agent)12 CancelDeposit (io.nuls.consensus.poc.protocol.entity.CancelDeposit)10 CoinDataResult (io.nuls.account.ledger.model.CoinDataResult)9 DepositTransaction (io.nuls.consensus.poc.protocol.tx.DepositTransaction)8 NulsRuntimeException (io.nuls.kernel.exception.NulsRuntimeException)6 MultiSigAccount (io.nuls.account.model.MultiSigAccount)4 MeetingMember (io.nuls.consensus.poc.model.MeetingMember)4 StopAgent (io.nuls.consensus.poc.protocol.entity.StopAgent)4 CancelDepositTransaction (io.nuls.consensus.poc.protocol.tx.CancelDepositTransaction)4 CreateAgentTransaction (io.nuls.consensus.poc.protocol.tx.CreateAgentTransaction)4 PunishLogPo (io.nuls.consensus.poc.storage.po.PunishLogPo)4 Account (io.nuls.account.model.Account)3 DepositPo (io.nuls.consensus.poc.storage.po.DepositPo)3 Page (io.nuls.core.tools.page.Page)3 NulsException (io.nuls.kernel.exception.NulsException)3 ValidateResult (io.nuls.kernel.validate.ValidateResult)3 ChainContainer (io.nuls.consensus.poc.container.ChainContainer)2 Chain (io.nuls.consensus.poc.model.Chain)2 NulsDigestData (io.nuls.kernel.model.NulsDigestData)2