Search in sources :

Example 1 with DepositTransaction

use of io.nuls.consensus.poc.protocol.tx.DepositTransaction in project nuls by nuls-io.

the class ConsensusTool method getStopAgentCoinData.

public static CoinData getStopAgentCoinData(Agent agent, long lockTime, Long hight) throws IOException {
    if (null == agent) {
        return null;
    }
    NulsDigestData createTxHash = agent.getTxHash();
    CoinData coinData = new CoinData();
    List<Coin> toList = new ArrayList<>();
    if (agent.getAgentAddress()[2] == NulsContext.P2SH_ADDRESS_TYPE) {
        Script scriptPubkey = SignatureUtil.createOutputScript(agent.getAgentAddress());
        toList.add(new Coin(scriptPubkey.getProgram(), agent.getDeposit(), lockTime));
    } else {
        toList.add(new Coin(agent.getAgentAddress(), agent.getDeposit(), lockTime));
    }
    coinData.setTo(toList);
    CreateAgentTransaction transaction = (CreateAgentTransaction) ledgerService.getTx(createTxHash);
    if (null == transaction) {
        throw new NulsRuntimeException(TransactionErrorCode.TX_NOT_EXIST);
    }
    List<Coin> fromList = new ArrayList<>();
    for (int index = 0; index < transaction.getCoinData().getTo().size(); index++) {
        Coin coin = transaction.getCoinData().getTo().get(index);
        if (coin.getNa().equals(agent.getDeposit()) && coin.getLockTime() == -1L) {
            coin.setOwner(ArraysTool.concatenate(transaction.getHash().serialize(), new VarInt(index).encode()));
            fromList.add(coin);
            break;
        }
    }
    if (fromList.isEmpty()) {
        throw new NulsRuntimeException(KernelErrorCode.DATA_ERROR);
    }
    coinData.setFrom(fromList);
    List<Deposit> deposits = PocConsensusContext.getChainManager().getMasterChain().getChain().getDepositList();
    List<String> addressList = new ArrayList<>();
    Map<String, Coin> toMap = new HashMap<>();
    long blockHeight = null == hight ? -1 : hight;
    for (Deposit deposit : deposits) {
        if (deposit.getDelHeight() > 0 && (blockHeight <= 0 || deposit.getDelHeight() < blockHeight)) {
            continue;
        }
        if (!deposit.getAgentHash().equals(agent.getTxHash())) {
            continue;
        }
        DepositTransaction dtx = (DepositTransaction) ledgerService.getTx(deposit.getTxHash());
        Coin fromCoin = null;
        for (Coin coin : dtx.getCoinData().getTo()) {
            if (!coin.getNa().equals(deposit.getDeposit()) || coin.getLockTime() != -1L) {
                continue;
            }
            fromCoin = new Coin(ArraysTool.concatenate(dtx.getHash().serialize(), new VarInt(0).encode()), coin.getNa(), coin.getLockTime());
            fromCoin.setLockTime(-1L);
            fromList.add(fromCoin);
            break;
        }
        String address = AddressTool.getStringAddressByBytes(deposit.getAddress());
        Coin coin = toMap.get(address);
        if (null == coin) {
            if (deposit.getAddress()[2] == NulsContext.P2SH_ADDRESS_TYPE) {
                Script scriptPubkey = SignatureUtil.createOutputScript(deposit.getAddress());
                coin = new Coin(scriptPubkey.getProgram(), deposit.getDeposit(), 0);
            } else {
                coin = new Coin(deposit.getAddress(), deposit.getDeposit(), 0);
            }
            addressList.add(address);
            toMap.put(address, coin);
        } else {
            coin.setNa(coin.getNa().add(fromCoin.getNa()));
        }
    }
    for (String address : addressList) {
        coinData.getTo().add(toMap.get(address));
    }
    return coinData;
}
Also used : Script(io.nuls.kernel.script.Script) Deposit(io.nuls.consensus.poc.protocol.entity.Deposit) DepositTransaction(io.nuls.consensus.poc.protocol.tx.DepositTransaction) VarInt(io.nuls.kernel.utils.VarInt) NulsRuntimeException(io.nuls.kernel.exception.NulsRuntimeException) CreateAgentTransaction(io.nuls.consensus.poc.protocol.tx.CreateAgentTransaction)

Example 2 with DepositTransaction

use of io.nuls.consensus.poc.protocol.tx.DepositTransaction in project nuls by nuls-io.

the class DepositTxProcessor method conflictDetect.

/**
 * 冲突检测,检测如果传入的交易列表中有相冲突的交易,则返回失败,写明失败原因及所有的应该舍弃的交易列表
 * 本方法不检查双花冲突,双花由账本接口实现
 * <p>
 * Conflict detection, which detects conflicting transactions in the incoming transaction list, returns failure,
 * indicating the cause of failure and all the list of trades that should be discarded.
 * This method does not check the double flower conflict, the double flower is realized by the accounting interface.
 *
 * @param txList 需要检查的交易列表/A list of transactions to be checked.
 * @return 操作结果:成功则返回successResult,失败时,data中返回丢弃列表,msg中返回冲突原因
 * Operation result: success returns successResult. When failure, data returns the discard list, and MSG returns the cause of conflict.
 */
@Override
public ValidateResult conflictDetect(List<Transaction> txList) {
    if (null == txList || txList.isEmpty()) {
        return ValidateResult.getSuccessResult();
    }
    Set<NulsDigestData> outAgentHash = new HashSet<>();
    Map<NulsDigestData, Na> naMap = new HashMap<>();
    List<DepositTransaction> dTxList = new ArrayList<>();
    for (Transaction transaction : txList) {
        switch(transaction.getType()) {
            case ConsensusConstant.TX_TYPE_STOP_AGENT:
                StopAgentTransaction stopAgentTransaction = (StopAgentTransaction) transaction;
                outAgentHash.add(stopAgentTransaction.getTxData().getCreateTxHash());
                break;
            case ConsensusConstant.TX_TYPE_JOIN_CONSENSUS:
                DepositTransaction depositTransaction = (DepositTransaction) transaction;
                Na na = naMap.get(depositTransaction.getTxData().getAgentHash());
                if (null == na) {
                    na = getAgentTotalDeposit(depositTransaction.getTxData().getAgentHash());
                }
                if (na == null) {
                    na = depositTransaction.getTxData().getDeposit();
                } else {
                    na = na.add(depositTransaction.getTxData().getDeposit());
                }
                if (na.isGreaterThan(PocConsensusProtocolConstant.SUM_OF_DEPOSIT_OF_AGENT_UPPER_LIMIT)) {
                    ValidateResult validateResult = ValidateResult.getFailedResult(this.getClass().getName(), PocConsensusErrorCode.DEPOSIT_TOO_MUCH);
                    validateResult.setData(transaction);
                    return validateResult;
                } else {
                    naMap.put(depositTransaction.getTxData().getAgentHash(), na);
                }
                dTxList.add(depositTransaction);
                break;
            case ConsensusConstant.TX_TYPE_RED_PUNISH:
                RedPunishTransaction redPunishTransaction = (RedPunishTransaction) transaction;
                RedPunishData redPunishData = redPunishTransaction.getTxData();
                AgentPo agent = this.getAgentByAddress(redPunishData.getAddress());
                if (null != agent) {
                    outAgentHash.add(agent.getHash());
                }
                break;
            default:
                continue;
        }
    }
    if (dTxList.isEmpty() || outAgentHash.isEmpty()) {
        return ValidateResult.getSuccessResult();
    }
    for (DepositTransaction depositTransaction : dTxList) {
        if (outAgentHash.contains(depositTransaction.getTxData().getAgentHash())) {
            ValidateResult validateResult = ValidateResult.getFailedResult(this.getClass().getName(), PocConsensusErrorCode.AGENT_STOPPED);
            validateResult.setData(depositTransaction);
            return validateResult;
        }
    }
    return ValidateResult.getSuccessResult();
}
Also used : DepositTransaction(io.nuls.consensus.poc.protocol.tx.DepositTransaction) RedPunishTransaction(io.nuls.consensus.poc.protocol.tx.RedPunishTransaction) ValidateResult(io.nuls.kernel.validate.ValidateResult) StopAgentTransaction(io.nuls.consensus.poc.protocol.tx.StopAgentTransaction) DepositTransaction(io.nuls.consensus.poc.protocol.tx.DepositTransaction) RedPunishTransaction(io.nuls.consensus.poc.protocol.tx.RedPunishTransaction) RedPunishData(io.nuls.consensus.poc.protocol.entity.RedPunishData) StopAgentTransaction(io.nuls.consensus.poc.protocol.tx.StopAgentTransaction) AgentPo(io.nuls.consensus.poc.storage.po.AgentPo)

Example 3 with DepositTransaction

use of io.nuls.consensus.poc.protocol.tx.DepositTransaction 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 4 with DepositTransaction

use of io.nuls.consensus.poc.protocol.tx.DepositTransaction in project nuls by nuls-io.

the class PocConsensusResource method getWithdrawFee.

@GET
@Path("/withdraw/fee")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "get the fee of cancel deposit! 获取撤销委托的手续费", notes = "返回撤销委托交易手续费")
@ApiResponses(value = { @ApiResponse(code = 200, message = "success", response = String.class) })
public RpcClientResult getWithdrawFee(@ApiParam(name = "address", value = "委托账户地址", required = true) @QueryParam("address") String address, @ApiParam(name = "depositTxHash", value = "委托交易摘要", required = true) @QueryParam("depositTxHash") String depositTxHash) throws NulsException, IOException {
    AssertUtil.canNotEmpty(depositTxHash);
    if (!NulsDigestData.validHash(depositTxHash)) {
        return Result.getFailed(KernelErrorCode.PARAMETER_ERROR).toRpcClientResult();
    }
    AssertUtil.canNotEmpty(address);
    if (!AddressTool.validAddress(address)) {
        return Result.getFailed(AccountErrorCode.ADDRESS_ERROR).toRpcClientResult();
    }
    Account account = accountService.getAccount(address).getData();
    if (null == account) {
        return Result.getFailed(AccountErrorCode.ACCOUNT_NOT_EXIST).toRpcClientResult();
    }
    if (!account.isOk()) {
        return Result.getFailed(AccountErrorCode.IMPORTING_ACCOUNT).toRpcClientResult();
    }
    CancelDepositTransaction tx = new CancelDepositTransaction();
    CancelDeposit cancelDeposit = new CancelDeposit();
    NulsDigestData hash = NulsDigestData.fromDigestHex(depositTxHash);
    DepositTransaction depositTransaction = (DepositTransaction) ledgerService.getTx(hash);
    if (null == depositTransaction) {
        return Result.getFailed(TransactionErrorCode.TX_NOT_EXIST).toRpcClientResult();
    }
    cancelDeposit.setAddress(account.getAddress().getAddressBytes());
    cancelDeposit.setJoinTxHash(hash);
    tx.setTxData(cancelDeposit);
    CoinData coinData = new CoinData();
    List<Coin> toList = new ArrayList<>();
    toList.add(new Coin(cancelDeposit.getAddress(), depositTransaction.getTxData().getDeposit(), 0));
    coinData.setTo(toList);
    List<Coin> fromList = new ArrayList<>();
    for (int index = 0; index < depositTransaction.getCoinData().getTo().size(); index++) {
        Coin coin = depositTransaction.getCoinData().getTo().get(index);
        if (coin.getLockTime() == -1L && coin.getNa().equals(depositTransaction.getTxData().getDeposit())) {
            coin.setOwner(ArraysTool.concatenate(hash.serialize(), new VarInt(index).encode()));
            fromList.add(coin);
            break;
        }
    }
    if (fromList.isEmpty()) {
        return Result.getFailed(KernelErrorCode.DATA_ERROR).toRpcClientResult();
    }
    coinData.setFrom(fromList);
    tx.setCoinData(coinData);
    Na fee = TransactionFeeCalculator.getMaxFee(108 + tx.size());
    coinData.getTo().get(0).setNa(coinData.getTo().get(0).getNa().subtract(fee));
    Na resultFee = TransactionFeeCalculator.getMaxFee(108 + tx.size());
    Map<String, Long> map = new HashMap<>();
    map.put("fee", fee.getValue());
    map.put("maxAmount", getMaxAmount(resultFee, account.getAddress().getBase58(), tx));
    return Result.getSuccess().setData(map).toRpcClientResult();
}
Also used : CancelDeposit(io.nuls.consensus.poc.protocol.entity.CancelDeposit) Account(io.nuls.account.model.Account) MultiSigAccount(io.nuls.account.model.MultiSigAccount) CancelDepositTransaction(io.nuls.consensus.poc.protocol.tx.CancelDepositTransaction) DepositTransaction(io.nuls.consensus.poc.protocol.tx.DepositTransaction) VarInt(io.nuls.kernel.utils.VarInt) CancelDepositTransaction(io.nuls.consensus.poc.protocol.tx.CancelDepositTransaction)

Example 5 with DepositTransaction

use of io.nuls.consensus.poc.protocol.tx.DepositTransaction in project nuls by nuls-io.

the class PocConsensusResource method depositToAgent.

@POST
@Path("/deposit")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "deposit nuls to a bank! 申请参与共识 ", notes = "返回申请成功交易hash")
@ApiResponses(value = { @ApiResponse(code = 200, message = "success", response = String.class) })
public RpcClientResult depositToAgent(@ApiParam(name = "form", value = "申请参与共识表单数据", required = true) DepositForm form) throws NulsException {
    AssertUtil.canNotEmpty(form);
    AssertUtil.canNotEmpty(form.getAddress());
    AssertUtil.canNotEmpty(form.getAgentHash());
    if (!NulsDigestData.validHash(form.getAgentHash())) {
        return Result.getFailed(PocConsensusErrorCode.AGENT_NOT_EXIST).toRpcClientResult();
    }
    AssertUtil.canNotEmpty(form.getDeposit());
    if (!AddressTool.validAddress(form.getAddress())) {
        throw new NulsRuntimeException(KernelErrorCode.PARAMETER_ERROR);
    }
    Account account = accountService.getAccount(form.getAddress()).getData();
    if (null == account) {
        return Result.getFailed(AccountErrorCode.ACCOUNT_NOT_EXIST).toRpcClientResult();
    }
    if (account.isEncrypted() && account.isLocked()) {
        AssertUtil.canNotEmpty(form.getPassword(), "password is wrong");
        if (!account.validatePassword(form.getPassword())) {
            return Result.getFailed(AccountErrorCode.PASSWORD_IS_WRONG).toRpcClientResult();
        }
    }
    if (!account.isOk()) {
        return Result.getFailed(AccountErrorCode.IMPORTING_ACCOUNT).toRpcClientResult();
    }
    DepositTransaction tx = new DepositTransaction();
    Deposit deposit = new Deposit();
    deposit.setAddress(AddressTool.getAddress(form.getAddress()));
    deposit.setAgentHash(NulsDigestData.fromDigestHex(form.getAgentHash()));
    deposit.setDeposit(Na.valueOf(form.getDeposit()));
    tx.setTxData(deposit);
    CoinData coinData = new CoinData();
    List<Coin> toList = new ArrayList<>();
    toList.add(new Coin(deposit.getAddress(), deposit.getDeposit(), PocConsensusConstant.CONSENSUS_LOCK_TIME));
    coinData.setTo(toList);
    tx.setCoinData(coinData);
    CoinDataResult result = accountLedgerService.getCoinData(deposit.getAddress(), deposit.getDeposit(), tx.size(), TransactionFeeCalculator.OTHER_PRICE_PRE_1024_BYTES);
    RpcClientResult result1 = this.txProcessing(tx, result, account, form.getPassword());
    if (!result1.isSuccess()) {
        return result1;
    }
    Map<String, String> valueMap = new HashMap<>();
    valueMap.put("value", tx.getHash().getDigestHex());
    return Result.getSuccess().setData(valueMap).toRpcClientResult();
}
Also used : Account(io.nuls.account.model.Account) MultiSigAccount(io.nuls.account.model.MultiSigAccount) CancelDepositTransaction(io.nuls.consensus.poc.protocol.tx.CancelDepositTransaction) DepositTransaction(io.nuls.consensus.poc.protocol.tx.DepositTransaction) Deposit(io.nuls.consensus.poc.protocol.entity.Deposit) CancelDeposit(io.nuls.consensus.poc.protocol.entity.CancelDeposit) NulsRuntimeException(io.nuls.kernel.exception.NulsRuntimeException) CoinDataResult(io.nuls.account.ledger.model.CoinDataResult)

Aggregations

DepositTransaction (io.nuls.consensus.poc.protocol.tx.DepositTransaction)13 CancelDepositTransaction (io.nuls.consensus.poc.protocol.tx.CancelDepositTransaction)9 MultiSigAccount (io.nuls.account.model.MultiSigAccount)7 CancelDeposit (io.nuls.consensus.poc.protocol.entity.CancelDeposit)7 Deposit (io.nuls.consensus.poc.protocol.entity.Deposit)7 Account (io.nuls.account.model.Account)6 CoinDataResult (io.nuls.account.ledger.model.CoinDataResult)5 NulsRuntimeException (io.nuls.kernel.exception.NulsRuntimeException)5 VarInt (io.nuls.kernel.utils.VarInt)4 CreateAgentTransaction (io.nuls.consensus.poc.protocol.tx.CreateAgentTransaction)3 IOException (java.io.IOException)3 Agent (io.nuls.consensus.poc.protocol.entity.Agent)2 DepositPo (io.nuls.consensus.poc.storage.po.DepositPo)2 NulsException (io.nuls.kernel.exception.NulsException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ChainContainer (io.nuls.consensus.poc.container.ChainContainer)1 RedPunishData (io.nuls.consensus.poc.protocol.entity.RedPunishData)1 RedPunishTransaction (io.nuls.consensus.poc.protocol.tx.RedPunishTransaction)1 StopAgentTransaction (io.nuls.consensus.poc.protocol.tx.StopAgentTransaction)1 AgentPo (io.nuls.consensus.poc.storage.po.AgentPo)1