Search in sources :

Example 46 with Result

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

the class TransactionCacheStorageServiceImpl method afterPropertiesSet.

@Override
public void afterPropertiesSet() throws NulsException {
    dbService.destroyArea(TRANSACTION_CACHE_KEY_NAME);
    Result result = this.dbService.createArea(TRANSACTION_CACHE_KEY_NAME);
    if (result.isFailed() && !DBErrorCode.DB_AREA_EXIST.equals(result.getErrorCode())) {
        throw new NulsRuntimeException(result.getErrorCode());
    }
    startIndex.set(1);
}
Also used : NulsRuntimeException(io.nuls.kernel.exception.NulsRuntimeException) Result(io.nuls.kernel.model.Result)

Example 47 with Result

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

the class LocalUtxoStorageServiceImpl method batchSaveAndDeleteUTXO.

@Override
public Result batchSaveAndDeleteUTXO(List<Entry<byte[], byte[]>> utxosToSave, List<byte[]> utxosToDelete) {
    BatchOperation batch = dbService.createWriteBatch(AccountLedgerStorageConstant.DB_NAME_ACCOUNT_LEDGER_COINDATA);
    for (byte[] key : utxosToDelete) {
        batch.delete(key);
    }
    for (Entry<byte[], byte[]> entry : utxosToSave) {
        batch.put(entry.getKey(), entry.getValue());
    }
    Result batchResult = batch.executeBatch();
    if (batchResult.isFailed()) {
        return batchResult;
    }
    Result result = Result.getSuccess().setData(new Integer(utxosToSave.size() + utxosToDelete.size()));
    if (result.isSuccess() && cacheMap != null) {
        for (Entry<byte[], byte[]> entry : utxosToSave) {
            cacheMap.put(new String(entry.getKey()), entry);
        }
        for (byte[] key : utxosToDelete) {
            cacheMap.remove(new String(key));
        }
    }
    return result;
}
Also used : BatchOperation(io.nuls.db.service.BatchOperation) Result(io.nuls.kernel.model.Result)

Example 48 with Result

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

the class ContractTokenTransferStorageServiceImpl method afterPropertiesSet.

@Override
public void afterPropertiesSet() {
    this.area = ContractStorageConstant.DB_NAME_CONTRACT_NRC20_TOKEN_TRANSFER;
    Result result = dbService.createArea(this.area);
    if (result.isFailed() && !DBErrorCode.DB_AREA_EXIST.equals(result.getErrorCode())) {
        throw new NulsRuntimeException(result.getErrorCode());
    }
}
Also used : NulsRuntimeException(io.nuls.kernel.exception.NulsRuntimeException) Result(io.nuls.kernel.model.Result)

Example 49 with Result

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

the class CallContractTxProcessor method onCommit.

@Override
public Result onCommit(CallContractTransaction tx, Object secondaryData) {
    try {
        ContractResult contractResult = tx.getContractResult();
        // 保存调用合约交易的UTXO
        Result utxoResult = contractUtxoService.saveUtxoForContractAddress(tx);
        if (utxoResult.isFailed()) {
            Log.error("save confirmed contract utxo error, reason is {}.", utxoResult.getMsg());
            return utxoResult;
        }
        long blockHeight = tx.getBlockHeight();
        /**
         * 保存子交易到全网账本、合约账本、本地账本
         */
        Collection<ContractTransferTransaction> contractTransferTxs = tx.getContractTransferTxs();
        if (contractTransferTxs != null && contractTransferTxs.size() > 0) {
            for (ContractTransferTransaction transferTx : contractTransferTxs) {
                try {
                    transferTx.setBlockHeight(blockHeight);
                    Result result = ledgerService.saveTx(transferTx);
                    if (result.isFailed()) {
                        Log.error("save contract transfer tx to ledger error. msg: {}", result.getMsg());
                        return result;
                    }
                    result = contractService.saveContractTransferTx(transferTx);
                    if (result.isFailed()) {
                        Log.error("save contract transfer tx to contract ledger error. msg: {}", result.getMsg());
                        return result;
                    }
                    result = accountLedgerService.saveConfirmedTransaction(transferTx);
                    if (result.isFailed()) {
                        Log.error("save contract transfer tx to account ledger error. msg: {}", result.getMsg());
                        return result;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.error("save contract transfer tx error. msg: {}", e.getMessage());
                    return Result.getFailed();
                }
            }
        }
        // 保存代币交易
        CallContractData callContractData = tx.getTxData();
        byte[] contractAddress = callContractData.getContractAddress();
        Result<ContractAddressInfoPo> contractAddressInfoPoResult = contractAddressStorageService.getContractAddressInfo(contractAddress);
        if (contractAddressInfoPoResult.isFailed()) {
            return contractAddressInfoPoResult;
        }
        ContractAddressInfoPo contractAddressInfoPo = contractAddressInfoPoResult.getData();
        if (contractAddressInfoPo == null) {
            return Result.getFailed(ContractErrorCode.CONTRACT_ADDRESS_NOT_EXIST);
        }
        contractResult.setNrc20(contractAddressInfoPo.isNrc20());
        BlockHeader blockHeader = tx.getBlockHeader();
        byte[] newestStateRoot = blockHeader.getStateRoot();
        // 获取合约当前状态
        ProgramStatus status = vmHelper.getContractStatus(newestStateRoot, contractAddress);
        boolean isTerminatedContract = ContractUtil.isTerminatedContract(status.ordinal());
        // 处理合约执行失败 - 没有transferEvent的情况, 直接从数据库中获取, 若是本地创建的交易,获取到修改为失败交易
        if (isTerminatedContract || !contractResult.isSuccess()) {
            if (contractAddressInfoPo != null && contractAddressInfoPo.isNrc20() && ContractUtil.isTransferMethod(callContractData.getMethodName())) {
                byte[] txHashBytes = tx.getHash().serialize();
                byte[] infoKey = ArraysTool.concatenate(callContractData.getSender(), txHashBytes, new VarInt(0).encode());
                Result<ContractTokenTransferInfoPo> infoResult = contractTokenTransferStorageService.getTokenTransferInfo(infoKey);
                ContractTokenTransferInfoPo po = infoResult.getData();
                if (po != null) {
                    po.setStatus((byte) 2);
                    contractTokenTransferStorageService.saveTokenTransferInfo(infoKey, po);
                    // 刷新token余额
                    if (isTerminatedContract) {
                        // 终止的合约,回滚token余额
                        this.rollbackContractToken(po);
                        contractResult.setError(true);
                        contractResult.setErrorMessage("this contract has been terminated");
                    } else {
                        if (po.getFrom() != null) {
                            vmHelper.refreshTokenBalance(newestStateRoot, contractAddressInfoPo, AddressTool.getStringAddressByBytes(po.getFrom()), po.getContractAddress());
                        }
                        if (po.getTo() != null) {
                            vmHelper.refreshTokenBalance(newestStateRoot, contractAddressInfoPo, AddressTool.getStringAddressByBytes(po.getTo()), po.getContractAddress());
                        }
                    }
                }
            }
        }
        if (!isTerminatedContract) {
            // 处理合约事件
            vmHelper.dealEvents(newestStateRoot, tx, contractResult, contractAddressInfoPo);
        }
        // 保存合约执行结果
        contractService.saveContractExecuteResult(tx.getHash(), contractResult);
    } catch (Exception e) {
        Log.error("save call contract tx error.", e);
        return Result.getFailed();
    }
    return Result.getSuccess();
}
Also used : ContractResult(io.nuls.contract.dto.ContractResult) VarInt(io.nuls.kernel.utils.VarInt) CallContractData(io.nuls.contract.entity.txdata.CallContractData) IOException(java.io.IOException) ContractResult(io.nuls.contract.dto.ContractResult) ValidateResult(io.nuls.kernel.validate.ValidateResult) Result(io.nuls.kernel.model.Result) ContractAddressInfoPo(io.nuls.contract.storage.po.ContractAddressInfoPo) ContractTransferTransaction(io.nuls.contract.entity.tx.ContractTransferTransaction) ContractTokenTransferInfoPo(io.nuls.contract.dto.ContractTokenTransferInfoPo) BlockHeader(io.nuls.kernel.model.BlockHeader) ProgramStatus(io.nuls.contract.vm.program.ProgramStatus)

Example 50 with Result

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

the class CreateContractTxProcessor method onCommit.

@Override
public Result onCommit(CreateContractTransaction tx, Object secondaryData) {
    ContractResult contractResult = tx.getContractResult();
    contractService.saveContractExecuteResult(tx.getHash(), contractResult);
    CreateContractData txData = tx.getTxData();
    byte[] contractAddress = txData.getContractAddress();
    byte[] sender = txData.getSender();
    String senderStr = AddressTool.getStringAddressByBytes(sender);
    String contractAddressStr = AddressTool.getStringAddressByBytes(contractAddress);
    // 移除未确认的创建合约交易
    contractTxService.removeLocalUnconfirmedCreateContractTransaction(senderStr, contractAddressStr, contractResult);
    // 执行失败的合约直接返回
    if (!contractResult.isSuccess()) {
        return Result.getSuccess();
    }
    NulsDigestData hash = tx.getHash();
    long blockHeight = tx.getBlockHeight();
    long bestBlockHeight = NulsContext.getInstance().getBestHeight();
    ContractAddressInfoPo info = new ContractAddressInfoPo();
    info.setContractAddress(contractAddress);
    info.setSender(sender);
    try {
        info.setCreateTxHash(hash.serialize());
    } catch (IOException e) {
        throw new NulsRuntimeException(e);
    }
    info.setCreateTime(tx.getTime());
    info.setBlockHeight(blockHeight);
    // byte[] stateRoot = contractResult.getStateRoot();
    boolean isNrc20Contract = contractResult.isNrc20();
    boolean acceptDirectTransfer = contractResult.isAcceptDirectTransfer();
    info.setAcceptDirectTransfer(acceptDirectTransfer);
    info.setNrc20(isNrc20Contract);
    // 获取 token tracker
    if (isNrc20Contract) {
        BlockHeader blockHeader = tx.getBlockHeader();
        byte[] newestStateRoot = blockHeader.getStateRoot();
        // NRC20 token 标准方法获取名称数据
        ProgramResult programResult = vmHelper.invokeViewMethod(newestStateRoot, bestBlockHeight, contractAddress, NRC20_METHOD_NAME, null, null);
        if (programResult.isSuccess()) {
            String tokenName = programResult.getResult();
            info.setNrc20TokenName(tokenName);
        }
        programResult = vmHelper.invokeViewMethod(newestStateRoot, bestBlockHeight, contractAddress, NRC20_METHOD_SYMBOL, null, null);
        if (programResult.isSuccess()) {
            String symbol = programResult.getResult();
            info.setNrc20TokenSymbol(symbol);
        }
        programResult = vmHelper.invokeViewMethod(newestStateRoot, bestBlockHeight, contractAddress, NRC20_METHOD_DECIMALS, null, null);
        if (programResult.isSuccess()) {
            String decimals = programResult.getResult();
            if (StringUtils.isNotBlank(decimals)) {
                try {
                    info.setDecimals(new BigInteger(decimals).longValue());
                } catch (Exception e) {
                    Log.error("Get nrc20 decimals error.", e);
                // skip it
                }
            }
        }
        programResult = vmHelper.invokeViewMethod(newestStateRoot, bestBlockHeight, contractAddress, NRC20_METHOD_TOTAL_SUPPLY, null, null);
        if (programResult.isSuccess()) {
            String totalSupply = programResult.getResult();
            if (StringUtils.isNotBlank(totalSupply)) {
                try {
                    info.setTotalSupply(new BigInteger(totalSupply));
                } catch (Exception e) {
                    Log.error("Get nrc20 totalSupply error.", e);
                // skip it
                }
            }
        }
        // 刷新创建者的token余额
        vmHelper.refreshTokenBalance(newestStateRoot, info, senderStr, contractAddressStr);
        // 处理合约事件
        vmHelper.dealEvents(newestStateRoot, tx, contractResult, info);
    }
    Result result = contractAddressStorageService.saveContractAddress(contractAddress, info);
    return result;
}
Also used : ContractResult(io.nuls.contract.dto.ContractResult) ProgramResult(io.nuls.contract.vm.program.ProgramResult) NulsRuntimeException(io.nuls.kernel.exception.NulsRuntimeException) IOException(java.io.IOException) NulsRuntimeException(io.nuls.kernel.exception.NulsRuntimeException) IOException(java.io.IOException) NulsException(io.nuls.kernel.exception.NulsException) ContractResult(io.nuls.contract.dto.ContractResult) ValidateResult(io.nuls.kernel.validate.ValidateResult) ProgramResult(io.nuls.contract.vm.program.ProgramResult) Result(io.nuls.kernel.model.Result) ContractAddressInfoPo(io.nuls.contract.storage.po.ContractAddressInfoPo) CreateContractData(io.nuls.contract.entity.txdata.CreateContractData) NulsDigestData(io.nuls.kernel.model.NulsDigestData) BigInteger(java.math.BigInteger) BlockHeader(io.nuls.kernel.model.BlockHeader)

Aggregations

Result (io.nuls.kernel.model.Result)70 NulsException (io.nuls.kernel.exception.NulsException)16 IOException (java.io.IOException)15 NulsRuntimeException (io.nuls.kernel.exception.NulsRuntimeException)12 ValidateResult (io.nuls.kernel.validate.ValidateResult)11 AccountPo (io.nuls.account.storage.po.AccountPo)7 RpcClientResult (io.nuls.kernel.model.RpcClientResult)7 ArrayList (java.util.ArrayList)7 Account (io.nuls.account.model.Account)6 NulsDigestData (io.nuls.kernel.model.NulsDigestData)5 Test (org.junit.Test)5 CryptoException (io.nuls.core.tools.crypto.Exception.CryptoException)4 BatchOperation (io.nuls.db.service.BatchOperation)4 Address (io.nuls.kernel.model.Address)4 Block (io.nuls.kernel.model.Block)4 BlockHeader (io.nuls.kernel.model.BlockHeader)4 Transaction (io.nuls.kernel.model.Transaction)4 Node (io.nuls.network.model.Node)4 NotFound (io.nuls.protocol.model.NotFound)4 ApiOperation (io.swagger.annotations.ApiOperation)4