Search in sources :

Example 6 with ECKey

use of io.nuls.core.tools.crypto.ECKey in project nuls by nuls-io.

the class ContractTxServiceImpl method contractCreateTx.

/**
 * 创建生成智能合约的交易
 * 如果是创建合约的交易,交易仅仅用于创建合约,合约内部不执行复杂逻辑
 *
 * @param sender       交易创建者
 * @param gasLimit     最大gas消耗
 * @param price        执行合约单价
 * @param contractCode 合约代码
 * @param args         参数列表
 * @param password     账户密码
 * @param remark       备注
 * @return
 */
@Override
public Result contractCreateTx(String sender, Long gasLimit, Long price, byte[] contractCode, String[][] args, String password, String remark) {
    try {
        AssertUtil.canNotEmpty(sender, "the sender address can not be empty");
        AssertUtil.canNotEmpty(contractCode, "the contractCode can not be empty");
        Na value = Na.ZERO;
        Result<Account> accountResult = accountService.getAccount(sender);
        if (accountResult.isFailed()) {
            return accountResult;
        }
        if (!accountResult.getData().isOk()) {
            return Result.getFailed(AccountErrorCode.IMPORTING_ACCOUNT);
        }
        if (!ContractUtil.checkPrice(price.longValue())) {
            return Result.getFailed(ContractErrorCode.CONTRACT_MINIMUM_PRICE);
        }
        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);
            }
        }
        // 生成一个地址作为智能合约地址
        Address contractAddress = AccountTool.createContractAddress();
        byte[] contractAddressBytes = contractAddress.getAddressBytes();
        byte[] senderBytes = AddressTool.getAddress(sender);
        CreateContractTransaction tx = new CreateContractTransaction();
        if (StringUtils.isNotBlank(remark)) {
            try {
                tx.setRemark(remark.getBytes(NulsConfig.DEFAULT_ENCODING));
            } catch (UnsupportedEncodingException e) {
                Log.error(e);
                throw new RuntimeException(e);
            }
        }
        tx.setTime(TimeService.currentTimeMillis());
        // 计算CoinData
        /*
             * 智能合约计算手续费以消耗的Gas*Price为根据,然而创建交易时并不执行智能合约,
             * 所以此时交易的CoinData是不固定的,比实际要多,
             * 打包时执行智能合约,真实的手续费已算出,然而tx的手续费已扣除,
             * 多扣除的费用会以CoinBase交易还给Sender
             */
        CoinData coinData = new CoinData();
        BlockHeader blockHeader = NulsContext.getInstance().getBestBlock().getHeader();
        // 当前区块高度
        long blockHeight = blockHeader.getHeight();
        // 当前区块状态根
        byte[] prevStateRoot = ContractUtil.getStateRoot(blockHeader);
        AssertUtil.canNotEmpty(prevStateRoot, "All features of the smart contract are locked.");
        // 执行VM验证合法性
        ProgramCreate programCreate = new ProgramCreate();
        programCreate.setContractAddress(contractAddressBytes);
        programCreate.setSender(senderBytes);
        programCreate.setValue(BigInteger.valueOf(value.getValue()));
        programCreate.setPrice(price.longValue());
        programCreate.setGasLimit(gasLimit.longValue());
        programCreate.setNumber(blockHeight);
        programCreate.setContractCode(contractCode);
        if (args != null) {
            programCreate.setArgs(args);
        }
        ProgramExecutor track = programExecutor.begin(prevStateRoot);
        // 验证合约时跳过Gas验证
        long realGasLimit = programCreate.getGasLimit();
        programCreate.setGasLimit(MAX_GASLIMIT);
        ProgramResult programResult = track.create(programCreate);
        // 执行结果失败时,交易直接返回错误,不上链,不消耗Gas,
        if (!programResult.isSuccess()) {
            Log.error(programResult.getStackTrace());
            Result result = Result.getFailed(ContractErrorCode.DATA_ERROR);
            result.setMsg(ContractUtil.simplifyErrorMsg(programResult.getErrorMessage()));
            result = checkVmResultAndReturn(programResult.getErrorMessage(), result);
            return result;
        } else {
            // 其他合法性都通过后,再验证Gas
            track = programExecutor.begin(prevStateRoot);
            programCreate.setGasLimit(realGasLimit);
            programResult = track.create(programCreate);
            if (!programResult.isSuccess()) {
                Log.error(programResult.getStackTrace());
                Result result = Result.getFailed(ContractErrorCode.DATA_ERROR);
                result.setMsg(ContractUtil.simplifyErrorMsg(programResult.getErrorMessage()));
                return result;
            }
        }
        long gasUsed = gasLimit.longValue();
        Na imputedNa = Na.valueOf(LongUtils.mul(gasUsed, price));
        // 总花费
        Na totalNa = imputedNa.add(value);
        // 组装txData
        CreateContractData createContractData = new CreateContractData();
        createContractData.setSender(senderBytes);
        createContractData.setContractAddress(contractAddressBytes);
        createContractData.setValue(value.getValue());
        createContractData.setGasLimit(gasLimit);
        createContractData.setPrice(price);
        createContractData.setCodeLen(contractCode.length);
        createContractData.setCode(contractCode);
        if (args != null) {
            createContractData.setArgsCount((byte) args.length);
            if (args.length > 0) {
                createContractData.setArgs(args);
            }
        }
        tx.setTxData(createContractData);
        CoinDataResult coinDataResult = accountLedgerService.getCoinData(senderBytes, totalNa, tx.size() + coinData.size(), TransactionFeeCalculator.MIN_PRICE_PRE_1024_BYTES);
        if (!coinDataResult.isEnough()) {
            return Result.getFailed(TransactionErrorCode.INSUFFICIENT_BALANCE);
        }
        coinData.setFrom(coinDataResult.getCoinList());
        // 找零的UTXO
        if (coinDataResult.getChange() != null) {
            coinData.getTo().add(coinDataResult.getChange());
        }
        tx.setCoinData(coinData);
        tx.setHash(NulsDigestData.calcDigestData(tx.serializeForHash()));
        // 生成签名
        List<ECKey> signEckeys = new ArrayList<>();
        List<ECKey> scriptEckeys = new ArrayList<>();
        ECKey eckey = account.getEcKey(password);
        // 如果最后一位为1则表示该交易包含普通签名
        if ((coinDataResult.getSignType() & 0x01) == 0x01) {
            signEckeys.add(eckey);
        }
        // 如果倒数第二位位为1则表示该交易包含脚本签名
        if ((coinDataResult.getSignType() & 0x02) == 0x02) {
            scriptEckeys.add(eckey);
        }
        SignatureUtil.createTransactionSignture(tx, scriptEckeys, signEckeys);
        // 保存未确认交易到本地账本
        Result saveResult = accountLedgerService.verifyAndSaveUnconfirmedTransaction(tx);
        if (saveResult.isFailed()) {
            if (KernelErrorCode.DATA_SIZE_ERROR.getCode().equals(saveResult.getErrorCode().getCode())) {
                // 重新算一次交易(不超出最大交易数据大小下)的最大金额
                Result rs = accountLedgerService.getMaxAmountOfOnce(senderBytes, tx, TransactionFeeCalculator.MIN_PRICE_PRE_1024_BYTES);
                if (rs.isSuccess()) {
                    Na maxAmount = (Na) rs.getData();
                    rs = Result.getFailed(KernelErrorCode.DATA_SIZE_ERROR_EXTEND);
                    rs.setMsg(rs.getMsg() + maxAmount.toDouble());
                }
                return rs;
            }
            return saveResult;
        }
        // 广播交易
        Result sendResult = transactionService.broadcastTx(tx);
        if (sendResult.isFailed()) {
            accountLedgerService.deleteTransaction(tx);
            return sendResult;
        }
        Map<String, String> resultMap = MapUtil.createHashMap(2);
        String txHash = tx.getHash().getDigestHex();
        String contractAddressStr = AddressTool.getStringAddressByBytes(contractAddressBytes);
        resultMap.put("txHash", txHash);
        resultMap.put("contractAddress", contractAddressStr);
        // 保留未确认的创建合约交易到内存中
        this.saveLocalUnconfirmedCreateContractTransaction(sender, resultMap, tx.getTime());
        return Result.getSuccess().setData(resultMap);
    } catch (IOException e) {
        Log.error(e);
        Result result = Result.getFailed(ContractErrorCode.CONTRACT_TX_CREATE_ERROR);
        result.setMsg(e.getMessage());
        return result;
    } catch (NulsException e) {
        Log.error(e);
        return Result.getFailed(e.getErrorCode());
    } catch (Exception e) {
        Log.error(e);
        Result result = Result.getFailed(ContractErrorCode.CONTRACT_TX_CREATE_ERROR);
        result.setMsg(e.getMessage());
        return result;
    }
}
Also used : Account(io.nuls.account.model.Account) ECKey(io.nuls.core.tools.crypto.ECKey) ContractResult(io.nuls.contract.dto.ContractResult) CoinDataResult(io.nuls.account.ledger.model.CoinDataResult) NulsException(io.nuls.kernel.exception.NulsException) CoinDataResult(io.nuls.account.ledger.model.CoinDataResult) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) CreateContractTransaction(io.nuls.contract.entity.tx.CreateContractTransaction) NulsException(io.nuls.kernel.exception.NulsException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) CreateContractData(io.nuls.contract.entity.txdata.CreateContractData)

Example 7 with ECKey

use of io.nuls.core.tools.crypto.ECKey in project nuls by nuls-io.

the class TransactionServiceImplTest method initTxList.

private void initTxList() {
    List<Transaction> list = new ArrayList<>();
    ECKey ecKey1 = new ECKey();
    ECKey ecKey2 = new ECKey();
    ECKey ecKey3 = new ECKey();
    ECKey ecKey4 = new ECKey();
    ECKey ecKey5 = new ECKey();
    ECKey ecKey6 = new ECKey();
    Transaction tx = createCoinBaseTransaction(ecKey1, ecKey2, ecKey3, ecKey4, ecKey5, ecKey6);
    list.add(tx);
    Transaction yellowPunishTx = createYellowPunishTx(ecKey1, ecKey2, ecKey3, ecKey4, ecKey5, ecKey6);
    list.add(yellowPunishTx);
    // RedPunishTransaction redPunishTransaction = createRedPunishTx(ecKey1, ecKey4, ecKey5, ecKey6);
    // list.add(redPunishTransaction);
    TransferTransaction transferTransaction1 = createTransferTransaction(ecKey1, null, ecKey2, Na.ZERO);
    TransferTransaction transferTransaction2 = createTransferTransaction(ecKey1, null, ecKey3, Na.ZERO);
    list.add(transferTransaction1);
    list.add(transferTransaction2);
    createSetAliasTransaction(ecKey1, "alias");
    // createSetAliasTransaction(ecKey1, "alias1");
    // createSetAliasTransaction(ecKey2, "alias");
    CreateAgentTransaction tx1 = createRegisterAgentTransaction(ecKey1, ecKey2, "agentName");
    CreateAgentTransaction tx2 = createRegisterAgentTransaction(ecKey2, ecKey3, "agentName");
    CreateAgentTransaction tx3 = createRegisterAgentTransaction(ecKey4, ecKey5, "agentName2");
    CreateAgentTransaction tx4 = createRegisterAgentTransaction(ecKey1, ecKey3, "agentName3");
    list.add(tx1);
    list.add(tx2);
    list.add(tx3);
    list.add(tx4);
    DepositTransaction join1 = createDepositTransaction(ecKey1, tx1.getHash(), Na.parseNuls(200000));
    DepositTransaction join2 = createDepositTransaction(ecKey1, tx2.getHash(), Na.parseNuls(200000));
    DepositTransaction join3 = createDepositTransaction(ecKey1, tx3.getHash(), Na.parseNuls(200000));
    DepositTransaction join4 = createDepositTransaction(ecKey1, tx4.getHash(), Na.parseNuls(200000));
    DepositTransaction join5 = createDepositTransaction(ecKey1, tx3.getHash(), Na.parseNuls(200000));
    DepositTransaction join6 = createDepositTransaction(ecKey1, tx3.getHash(), Na.parseNuls(200000));
    DepositTransaction join7 = createDepositTransaction(ecKey1, tx3.getHash(), Na.parseNuls(200000));
    list.add(join1);
    list.add(join3);
    list.add(join2);
    list.add(join4);
    list.add(join5);
    list.add(join6);
    list.add(join7);
    try {
        createCancelDepositTransaction(ecKey1, NulsDigestData.fromDigestHex("txHash"));
    } catch (NulsException e) {
        Log.error(e);
    }
    StopAgentTransaction stop1 = createStopAgentTransaction(ecKey1, tx1.getHash());
    StopAgentTransaction stop2 = createStopAgentTransaction(ecKey1, tx2.getHash());
    StopAgentTransaction stop3 = createStopAgentTransaction(ecKey4, tx3.getHash());
    StopAgentTransaction stop4 = createStopAgentTransaction(ecKey1, tx4.getHash());
    list.add(stop1);
    list.add(stop2);
    list.add(stop3);
    list.add(stop4);
    this.allList = list;
}
Also used : TransferTransaction(io.nuls.protocol.model.tx.TransferTransaction) CoinBaseTransaction(io.nuls.protocol.model.tx.CoinBaseTransaction) NulsException(io.nuls.kernel.exception.NulsException) ArrayList(java.util.ArrayList) ECKey(io.nuls.core.tools.crypto.ECKey) TransferTransaction(io.nuls.protocol.model.tx.TransferTransaction)

Example 8 with ECKey

use of io.nuls.core.tools.crypto.ECKey in project nuls by nuls-io.

the class TransactionServiceImplTest method createYellowPunishTx.

// private RedPunishTransaction createRedPunishTx(ECKey ecKey, ECKey... ecKeys) {
// RedPunishTransaction tx = new RedPunishTransaction();
// setCommonFields(tx);
// RedPunishData data = new RedPunishData();
// data.setAddress(AddressTool.getAddress(ecKeys[0].getPubKey()));
// data.setEvidence("for test".getBytes());
// data.setReasonCode(PunishReasonEnum.BIFURCATION.getCode());
// tx.setTxData(data);
// return tx;
// }
private YellowPunishTransaction createYellowPunishTx(ECKey ecKey, ECKey... ecKeys) {
    YellowPunishTransaction tx = new YellowPunishTransaction();
    setCommonFields(tx);
    YellowPunishData data = new YellowPunishData();
    List<byte[]> addressList = new ArrayList<>();
    for (ECKey ecKey1 : ecKeys) {
        addressList.add(AddressTool.getAddress(ecKey1.getPubKey()));
    }
    data.setAddressList(addressList);
    tx.setTxData(data);
    return tx;
}
Also used : ArrayList(java.util.ArrayList) ECKey(io.nuls.core.tools.crypto.ECKey)

Example 9 with ECKey

use of io.nuls.core.tools.crypto.ECKey in project nuls by nuls-io.

the class Account method validatePassword.

/**
 * 验证账户密码是否正确
 * Verify that the account password is correct
 */
public boolean validatePassword(String password) {
    boolean result = StringUtils.validPassword(password);
    if (!result) {
        return result;
    }
    byte[] unencryptedPrivateKey;
    try {
        unencryptedPrivateKey = AESEncrypt.decrypt(this.getEncryptedPriKey(), password);
    } catch (CryptoException e) {
        return false;
    }
    BigInteger newPriv = new BigInteger(1, unencryptedPrivateKey);
    ECKey key = ECKey.fromPrivate(newPriv);
    if (!Arrays.equals(key.getPubKey(), getPubKey())) {
        return false;
    }
    return true;
}
Also used : BigInteger(java.math.BigInteger) ECKey(io.nuls.core.tools.crypto.ECKey) CryptoException(io.nuls.core.tools.crypto.Exception.CryptoException)

Example 10 with ECKey

use of io.nuls.core.tools.crypto.ECKey in project nuls by nuls-io.

the class Account method getPriKey.

public byte[] getPriKey(String password) throws NulsException {
    if (!StringUtils.validPassword(password)) {
        throw new NulsException(AccountErrorCode.PASSWORD_IS_WRONG);
    }
    byte[] unencryptedPrivateKey;
    try {
        unencryptedPrivateKey = AESEncrypt.decrypt(this.getEncryptedPriKey(), password);
    } catch (CryptoException e) {
        throw new NulsException(AccountErrorCode.PASSWORD_IS_WRONG);
    }
    BigInteger newPriv = new BigInteger(1, unencryptedPrivateKey);
    ECKey key = ECKey.fromPrivate(newPriv);
    if (!Arrays.equals(key.getPubKey(), getPubKey())) {
        throw new NulsException(AccountErrorCode.PASSWORD_IS_WRONG);
    }
    return unencryptedPrivateKey;
}
Also used : NulsException(io.nuls.kernel.exception.NulsException) BigInteger(java.math.BigInteger) ECKey(io.nuls.core.tools.crypto.ECKey) CryptoException(io.nuls.core.tools.crypto.Exception.CryptoException)

Aggregations

ECKey (io.nuls.core.tools.crypto.ECKey)43 NulsException (io.nuls.kernel.exception.NulsException)26 IOException (java.io.IOException)20 CoinDataResult (io.nuls.account.ledger.model.CoinDataResult)15 BigInteger (java.math.BigInteger)14 Account (io.nuls.account.model.Account)12 ArrayList (java.util.ArrayList)11 TransferTransaction (io.nuls.protocol.model.tx.TransferTransaction)10 MultiSigAccount (io.nuls.account.model.MultiSigAccount)8 ValidateResult (io.nuls.kernel.validate.ValidateResult)8 UnsupportedEncodingException (java.io.UnsupportedEncodingException)8 TransactionDataResult (io.nuls.account.ledger.model.TransactionDataResult)6 CryptoException (io.nuls.core.tools.crypto.Exception.CryptoException)6 NulsRuntimeException (io.nuls.kernel.exception.NulsRuntimeException)4 MultipleAddressTransferModel (io.nuls.account.ledger.model.MultipleAddressTransferModel)3 Alias (io.nuls.account.model.Alias)3 AliasTransaction (io.nuls.account.tx.AliasTransaction)3 Agent (io.nuls.consensus.poc.protocol.entity.Agent)3 ContractResult (io.nuls.contract.dto.ContractResult)3 Script (io.nuls.kernel.script.Script)3