Search in sources :

Example 1 with NulsByteBuffer

use of io.nuls.kernel.utils.NulsByteBuffer in project nuls by nuls-io.

the class UtxoLedgerServiceImpl method rollbackCoinData.

private Result rollbackCoinData(Transaction tx) throws IOException, NulsException {
    byte[] txHashBytes = tx.getHash().serialize();
    BatchOperation batch = utxoLedgerUtxoStorageService.createWriteBatch();
    CoinData coinData = tx.getCoinData();
    if (coinData != null) {
        // 保存utxo已花费 - from
        List<Coin> froms = coinData.getFrom();
        Coin recovery;
        for (Coin from : froms) {
            try {
                NulsByteBuffer byteBuffer = new NulsByteBuffer(from.getOwner());
                NulsDigestData fromTxHash = byteBuffer.readHash();
                int fromIndex = (int) byteBuffer.readVarInt();
                Transaction fromTx = utxoLedgerTransactionStorageService.getTx(fromTxHash);
                recovery = fromTx.getCoinData().getTo().get(fromIndex);
                recovery.setFrom(from.getFrom());
                batch.put(from.getOwner(), recovery.serialize());
            } catch (IOException e) {
                Log.error(e);
                return Result.getFailed(KernelErrorCode.IO_ERROR);
            }
        }
        // 删除utxo - to
        List<Coin> tos = coinData.getTo();
        for (int i = 0, length = tos.size(); i < length; i++) {
            byte[] owner = Arrays.concatenate(txHashBytes, new VarInt(i).encode());
            // Log.info("批量删除:" + Hex.encode(owner));
            batch.delete(owner);
        }
        // 执行批量
        Result batchResult = batch.executeBatch();
        if (batchResult.isFailed()) {
            return batchResult;
        }
    }
    return Result.getSuccess();
}
Also used : VarInt(io.nuls.kernel.utils.VarInt) BatchOperation(io.nuls.db.service.BatchOperation) IOException(java.io.IOException) NulsByteBuffer(io.nuls.kernel.utils.NulsByteBuffer) ValidateResult(io.nuls.kernel.validate.ValidateResult)

Example 2 with NulsByteBuffer

use of io.nuls.kernel.utils.NulsByteBuffer in project nuls by nuls-io.

the class TransactionResource method getTxByHash.

@GET
@Path("/hash/{hash}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "根据hash查询交易")
@ApiResponses(value = { @ApiResponse(code = 200, message = "success", response = TransactionDto.class) })
public RpcClientResult getTxByHash(@ApiParam(name = "hash", value = "交易hash", required = true) @PathParam("hash") String hash) {
    if (StringUtils.isBlank(hash)) {
        return Result.getFailed(LedgerErrorCode.NULL_PARAMETER).toRpcClientResult();
    }
    if (!NulsDigestData.validHash(hash)) {
        return Result.getFailed(LedgerErrorCode.PARAMETER_ERROR).toRpcClientResult();
    }
    Result result = null;
    try {
        Transaction tx = ledgerService.getTx(NulsDigestData.fromDigestHex(hash));
        if (tx == null) {
            result = Result.getFailed(TransactionErrorCode.TX_NOT_EXIST);
        } else {
            tx.setStatus(TxStatusEnum.CONFIRMED);
            TransactionDto txDto = null;
            CoinData coinData = tx.getCoinData();
            String fromAddress = null;
            if (tx.getTransactionSignature() != null) {
                TransactionSignature signature = new TransactionSignature();
                signature.parse(new NulsByteBuffer(tx.getTransactionSignature()));
                if (signature.getP2PHKSignatures() != null && signature.getP2PHKSignatures().size() == 1) {
                    byte[] addressBytes = AddressTool.getAddress(signature.getP2PHKSignatures().get(0).getPublicKey());
                    fromAddress = AddressTool.getStringAddressByBytes(addressBytes);
                }
            }
            if (coinData != null) {
                // 组装from数据
                List<Coin> froms = coinData.getFrom();
                if (froms != null && froms.size() > 0) {
                    byte[] fromHash, owner;
                    int fromIndex;
                    NulsDigestData fromHashObj;
                    Transaction fromTx;
                    Coin fromUtxo;
                    for (Coin from : froms) {
                        if (fromAddress != null) {
                            from.setFromAddress(fromAddress);
                        } else {
                            owner = from.getOwner();
                            // owner拆分出txHash和index
                            fromHash = LedgerUtil.getTxHashBytes(owner);
                            fromIndex = LedgerUtil.getIndex(owner);
                            // 查询from UTXO
                            fromHashObj = new NulsDigestData();
                            fromHashObj.parse(fromHash, 0);
                            fromTx = ledgerService.getTx(fromHashObj);
                            fromUtxo = fromTx.getCoinData().getTo().get(fromIndex);
                            from.setFrom(fromUtxo);
                        }
                    }
                }
                txDto = new TransactionDto(tx);
                List<OutputDto> outputDtoList = new ArrayList<>();
                // 组装to数据
                List<Coin> tos = coinData.getTo();
                if (tos != null && tos.size() > 0) {
                    byte[] txHashBytes = tx.getHash().serialize();
                    String txHash = hash;
                    OutputDto outputDto = null;
                    Coin to, temp;
                    long bestHeight = NulsContext.getInstance().getBestHeight();
                    long currentTime = TimeService.currentTimeMillis();
                    long lockTime;
                    for (int i = 0, length = tos.size(); i < length; i++) {
                        to = tos.get(i);
                        outputDto = new OutputDto(to);
                        outputDto.setTxHash(txHash);
                        outputDto.setIndex(i);
                        temp = utxoLedgerUtxoStorageService.getUtxo(Arrays.concatenate(txHashBytes, new VarInt(i).encode()));
                        if (temp == null) {
                            // 已花费
                            outputDto.setStatus(3);
                        } else {
                            lockTime = temp.getLockTime();
                            if (lockTime < 0) {
                                // 共识锁定
                                outputDto.setStatus(2);
                            } else if (lockTime == 0) {
                                // 正常未花费
                                outputDto.setStatus(0);
                            } else if (lockTime > NulsConstant.BlOCKHEIGHT_TIME_DIVIDE) {
                                // 判定是否时间高度锁定
                                if (lockTime > currentTime) {
                                    // 时间高度锁定
                                    outputDto.setStatus(1);
                                } else {
                                    // 正常未花费
                                    outputDto.setStatus(0);
                                }
                            } else {
                                // 判定是否区块高度锁定
                                if (lockTime > bestHeight) {
                                    // 区块高度锁定
                                    outputDto.setStatus(1);
                                } else {
                                    // 正常未花费
                                    outputDto.setStatus(0);
                                }
                            }
                        }
                        outputDtoList.add(outputDto);
                    }
                }
                txDto.setOutputs(outputDtoList);
                // 计算交易实际发生的金额
                calTransactionValue(txDto);
            }
            result = Result.getSuccess();
            result.setData(txDto);
        }
    } catch (NulsRuntimeException e) {
        Log.error(e);
        result = Result.getFailed(e.getErrorCode());
    } catch (Exception e) {
        Log.error(e);
        result = Result.getFailed(LedgerErrorCode.SYS_UNKOWN_EXCEPTION);
    }
    return result.toRpcClientResult();
}
Also used : OutputDto(io.nuls.ledger.rpc.model.OutputDto) TransactionDto(io.nuls.ledger.rpc.model.TransactionDto) VarInt(io.nuls.kernel.utils.VarInt) NulsRuntimeException(io.nuls.kernel.exception.NulsRuntimeException) TransactionSignature(io.nuls.kernel.script.TransactionSignature) NulsRuntimeException(io.nuls.kernel.exception.NulsRuntimeException) IOException(java.io.IOException) NulsException(io.nuls.kernel.exception.NulsException) NulsByteBuffer(io.nuls.kernel.utils.NulsByteBuffer)

Example 3 with NulsByteBuffer

use of io.nuls.kernel.utils.NulsByteBuffer in project nuls by nuls-io.

the class AccountServiceImpl method getMultiSigAccountList.

/**
 * 获取所有账户集合
 * Query all account collections.
 *
 * @return account list of all accounts.
 */
@Override
public Result<List<MultiSigAccount>> getMultiSigAccountList() {
    List<byte[]> list = this.multiSigAccountStorageService.getAccountList().getData();
    if (null == list) {
        return Result.getFailed(KernelErrorCode.DATA_NOT_FOUND);
    }
    List<MultiSigAccount> accountList = new ArrayList<>();
    for (byte[] bytes : list) {
        MultiSigAccount account = new MultiSigAccount();
        try {
            account.parse(new NulsByteBuffer(bytes, 0));
        } catch (NulsException e) {
            Log.error(e);
        }
        accountList.add(account);
    }
    List<AliasPo> aliasList = aliasStorageService.getAliasList().getData();
    for (AliasPo aliasPo : aliasList) {
        if (aliasPo.getAddress()[2] != NulsContext.P2SH_ADDRESS_TYPE) {
            continue;
        }
        for (MultiSigAccount multiSigAccount : accountList) {
            if (Arrays.equals(aliasPo.getAddress(), multiSigAccount.getAddress().getAddressBytes())) {
                multiSigAccount.setAlias(aliasPo.getAlias());
                break;
            }
        }
    }
    return new Result<List<MultiSigAccount>>().setData(accountList);
}
Also used : NulsException(io.nuls.kernel.exception.NulsException) AliasPo(io.nuls.account.storage.po.AliasPo) NulsByteBuffer(io.nuls.kernel.utils.NulsByteBuffer)

Example 4 with NulsByteBuffer

use of io.nuls.kernel.utils.NulsByteBuffer in project nuls by nuls-io.

the class AccountServiceImpl method getMultiSigAccount.

/**
 * 根据地址获取本地存储的多签账户的详细信息
 * Get the details of the locally stored multi-sign account based on the address
 *
 * @param address 多签地址
 * @return 多签账户的详细信息
 */
@Override
public Result<MultiSigAccount> getMultiSigAccount(String address) throws Exception {
    byte[] bytes = this.multiSigAccountStorageService.getAccount(Address.fromHashs(address)).getData();
    if (null == bytes) {
        return Result.getFailed(KernelErrorCode.DATA_NOT_FOUND);
    }
    MultiSigAccount account = new MultiSigAccount();
    account.parse(new NulsByteBuffer(bytes, 0));
    List<AliasPo> list = aliasStorageService.getAliasList().getData();
    for (AliasPo aliasPo : list) {
        if (aliasPo.getAddress()[2] != NulsContext.P2SH_ADDRESS_TYPE) {
            continue;
        }
        if (Arrays.equals(aliasPo.getAddress(), account.getAddress().getAddressBytes())) {
            account.setAlias(aliasPo.getAlias());
            break;
        }
    }
    return Result.getSuccess().setData(account);
}
Also used : AliasPo(io.nuls.account.storage.po.AliasPo) NulsByteBuffer(io.nuls.kernel.utils.NulsByteBuffer)

Example 5 with NulsByteBuffer

use of io.nuls.kernel.utils.NulsByteBuffer in project nuls by nuls-io.

the class AliasService method signMultiAliasTransaction.

/**
 * A transfers NULS to B   多签交易
 *
 * @param signAddr 签名地址
 * @param password password of A
 * @param txdata   需要签名的数据
 * @return Result
 */
public Result signMultiAliasTransaction(String signAddr, String password, String txdata) {
    try {
        Result<Account> accountResult = accountService.getAccount(signAddr);
        if (accountResult.isFailed()) {
            return accountResult;
        }
        Account account = accountResult.getData();
        if (account.isEncrypted() && account.isLocked()) {
            AssertUtil.canNotEmpty(password, "the password can not be empty");
            if (!account.validatePassword(password)) {
                return Result.getFailed(AccountErrorCode.PASSWORD_IS_WRONG);
            }
        }
        AliasTransaction tx = new AliasTransaction();
        TransactionSignature transactionSignature = new TransactionSignature();
        byte[] txByte = Hex.decode(txdata);
        tx.parse(new NulsByteBuffer(txByte));
        transactionSignature.parse(new NulsByteBuffer(tx.getTransactionSignature()));
        return accountLedgerService.txMultiProcess(tx, transactionSignature, account, password);
    } catch (NulsException e) {
        Log.error(e);
        return Result.getFailed(e.getErrorCode());
    } catch (Exception e) {
        Log.error(e);
        return Result.getFailed(AccountErrorCode.ACCOUNT_NOT_EXIST);
    }
}
Also used : Account(io.nuls.account.model.Account) MultiSigAccount(io.nuls.account.model.MultiSigAccount) AliasTransaction(io.nuls.account.tx.AliasTransaction) NulsException(io.nuls.kernel.exception.NulsException) IOException(java.io.IOException) NulsException(io.nuls.kernel.exception.NulsException) NulsByteBuffer(io.nuls.kernel.utils.NulsByteBuffer)

Aggregations

NulsByteBuffer (io.nuls.kernel.utils.NulsByteBuffer)17 NulsException (io.nuls.kernel.exception.NulsException)14 IOException (java.io.IOException)9 NulsRuntimeException (io.nuls.kernel.exception.NulsRuntimeException)5 Account (io.nuls.account.model.Account)4 MultiSigAccount (io.nuls.account.model.MultiSigAccount)4 Transaction (io.nuls.kernel.model.Transaction)3 ValidateResult (io.nuls.kernel.validate.ValidateResult)3 CoinDataResult (io.nuls.account.ledger.model.CoinDataResult)2 AliasPo (io.nuls.account.storage.po.AliasPo)2 AliasTransaction (io.nuls.account.tx.AliasTransaction)2 ECKey (io.nuls.core.tools.crypto.ECKey)2 VarInt (io.nuls.kernel.utils.VarInt)2 TransferTransaction (io.nuls.protocol.model.tx.TransferTransaction)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ArrayList (java.util.ArrayList)2 MultipleAddressTransferModel (io.nuls.account.ledger.model.MultipleAddressTransferModel)1 TransactionDataResult (io.nuls.account.ledger.model.TransactionDataResult)1 UnconfirmedTxPo (io.nuls.account.ledger.storage.po.UnconfirmedTxPo)1 Alias (io.nuls.account.model.Alias)1