Search in sources :

Example 16 with Account

use of io.nuls.account.model.Account in project nuls by nuls-io.

the class AccountBaseServiceTest method setPassword.

@Test
public void setPassword() {
    List<Account> accounts = this.accountService.createAccount(1, "").getData();
    Account account = accounts.get(0);
    accountBaseService.setPassword(account.getAddress().toString(), "nuls123456");
    Account acc = accountService.getAccount(account.getAddress()).getData();
    try {
        assertTrue(acc.unlock("nuls123456"));
        assertArrayEquals(acc.getPriKey(), account.getPriKey());
    } catch (NulsException e) {
        e.printStackTrace();
    }
}
Also used : Account(io.nuls.account.model.Account) NulsException(io.nuls.kernel.exception.NulsException) Test(org.junit.Test)

Example 17 with Account

use of io.nuls.account.model.Account in project nuls by nuls-io.

the class AccountTest method decrypTest.

/**
 * 获得一个,用错误的密码,解密加密后的私钥,得到一个错误的地址
 * 测试用错误的密码keystore导入keystore的问题
 */
@Test
public void decrypTest() {
    String acc = "NsdvWJqEtRcekQVf88UoKH4Y789ka9YD";
    String encryptedPrivateKey = "3254fad53298a1fbf1fcda27acdb4bcd1c895001a8443233d4d9ce9ca803c7e6dcd9bd32813668a9ad2687eb4e1173b0";
    while (true) {
        String pwd = getPwd();
        try {
            byte[] priKey = AESEncrypt.decrypt(Hex.decode(encryptedPrivateKey), pwd);
            Account account = AccountTool.createAccount(Hex.encode(priKey));
            if (!acc.equals(account.getAddress().getBase58())) {
                System.out.println("======= 结果 ======");
                System.out.println("加密的私钥:3254fad53298a1fbf1fcda27acdb4bcd1c895001a8443233d4d9ce9ca803c7e6dcd9bd32813668a9ad2687eb4e1173b0");
                System.out.println("错误的密码:" + pwd);
                System.out.println("解出错误的私钥:" + Hex.encode(priKey));
                System.out.println();
                System.out.println("正确的密码:nuls123456");
                System.out.println("解出正确的私钥:" + Hex.encode(AESEncrypt.decrypt(Hex.decode(encryptedPrivateKey), "nuls123456")));
            // break;
            }
        } catch (Exception e) {
            System.out.println("没解出来:" + pwd);
        }
    }
}
Also used : Account(io.nuls.account.model.Account) Test(org.junit.Test)

Example 18 with Account

use of io.nuls.account.model.Account 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 19 with Account

use of io.nuls.account.model.Account in project nuls by nuls-io.

the class PocConsensusResource method createMutilAgent.

@POST
@Path("/multiAccount/createMultiAgent")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create an agent for consensus! 创建共识(代理)节点 [3.6.3]", notes = "返回创建的节点成功的交易hash")
@ApiResponses(value = { @ApiResponse(code = 200, message = "success", response = String.class) })
public RpcClientResult createMutilAgent(@ApiParam(name = "form", value = "多签地址创建节点表单数据", required = true) CreateMultiAgentForm form) throws Exception {
    if (NulsContext.MAIN_NET_VERSION <= 1) {
        return Result.getFailed(KernelErrorCode.VERSION_TOO_LOW).toRpcClientResult();
    }
    AssertUtil.canNotEmpty(form);
    AssertUtil.canNotEmpty(form.getAgentAddress(), "agent address can not be null");
    AssertUtil.canNotEmpty(form.getSignAddress(), "agent address can not be null");
    AssertUtil.canNotEmpty(form.getCommissionRate(), "commission rate can not be null");
    AssertUtil.canNotEmpty(form.getDeposit(), "deposit can not be null");
    AssertUtil.canNotEmpty(form.getPackingAddress(), "packing address can not be null");
    if (!AddressTool.isPackingAddress(form.getPackingAddress()) || !AddressTool.validAddress(form.getAgentAddress()) || !AddressTool.validAddress(form.getSignAddress())) {
        throw new NulsRuntimeException(AccountErrorCode.ADDRESS_ERROR);
    }
    Account account = accountService.getAccount(form.getSignAddress()).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();
        }
    }
    Result<MultiSigAccount> sigAccountResult = accountService.getMultiSigAccount(form.getAgentAddress());
    MultiSigAccount multiSigAccount = sigAccountResult.getData();
    // 验证签名账户是否属于多签账户,如果不是多签账户下的地址则提示错误
    if (!AddressTool.validSignAddress(multiSigAccount.getPubKeyList(), account.getPubKey())) {
        return Result.getFailed(AccountErrorCode.SIGN_ADDRESS_NOT_MATCH).toRpcClientResult();
    }
    Script redeemScript = accountLedgerService.getRedeemScript(multiSigAccount);
    if (redeemScript == null) {
        return Result.getFailed(AccountErrorCode.ACCOUNT_NOT_EXIST).toRpcClientResult();
    }
    CreateAgentTransaction tx = new CreateAgentTransaction();
    tx.setTime(TimeService.currentTimeMillis());
    Agent agent = new Agent();
    agent.setAgentAddress(AddressTool.getAddress(form.getAgentAddress()));
    agent.setPackingAddress(AddressTool.getAddress(form.getPackingAddress()));
    if (StringUtils.isBlank(form.getRewardAddress())) {
        agent.setRewardAddress(agent.getAgentAddress());
    } else {
        agent.setRewardAddress(AddressTool.getAddress(form.getRewardAddress()));
    }
    TransactionSignature transactionSignature = new TransactionSignature();
    List<Script> scripts = new ArrayList<>();
    agent.setDeposit(Na.valueOf(form.getDeposit()));
    agent.setCommissionRate(form.getCommissionRate());
    tx.setTxData(agent);
    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(), PocConsensusConstant.CONSENSUS_LOCK_TIME));
    } else {
        toList.add(new Coin(agent.getAgentAddress(), agent.getDeposit(), PocConsensusConstant.CONSENSUS_LOCK_TIME));
    }
    coinData.setTo(toList);
    tx.setCoinData(coinData);
    // 交易签名的长度为m*单个签名长度+赎回脚本长度
    int scriptSignLenth = redeemScript.getProgram().length + ((int) multiSigAccount.getM()) * 72;
    CoinDataResult result = accountLedgerService.getMutilCoinData(agent.getAgentAddress(), agent.getDeposit(), tx.size() + scriptSignLenth, TransactionFeeCalculator.OTHER_PRICE_PRE_1024_BYTES);
    if (null != result) {
        if (result.isEnough()) {
            tx.getCoinData().setFrom(result.getCoinList());
            if (null != result.getChange()) {
                tx.getCoinData().getTo().add(result.getChange());
            }
        } else {
            return Result.getFailed(TransactionErrorCode.INSUFFICIENT_BALANCE).toRpcClientResult();
        }
    }
    tx.setHash(NulsDigestData.calcDigestData(tx.serializeForHash()));
    // 将赎回脚本先存储在签名脚本中
    scripts.add(redeemScript);
    transactionSignature.setScripts(scripts);
    Result finalResult = accountLedgerService.txMultiProcess(tx, transactionSignature, account, form.getPassword());
    if (finalResult.isSuccess()) {
        Map<String, String> valueMap = new HashMap<>();
        valueMap.put("txData", (String) finalResult.getData());
        return Result.getSuccess().setData(valueMap).toRpcClientResult();
    }
    return finalResult.toRpcClientResult();
}
Also used : MultiSigAccount(io.nuls.account.model.MultiSigAccount) Account(io.nuls.account.model.Account) MultiSigAccount(io.nuls.account.model.MultiSigAccount) StopAgent(io.nuls.consensus.poc.protocol.entity.StopAgent) Agent(io.nuls.consensus.poc.protocol.entity.Agent) NulsRuntimeException(io.nuls.kernel.exception.NulsRuntimeException) CoinDataResult(io.nuls.account.ledger.model.CoinDataResult) CreateAgentTransaction(io.nuls.consensus.poc.protocol.tx.CreateAgentTransaction) CoinDataResult(io.nuls.account.ledger.model.CoinDataResult)

Example 20 with Account

use of io.nuls.account.model.Account in project nuls by nuls-io.

the class PocConsensusResource method getCreateAgentFee.

@GET
@Path("/agent/fee")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "get the fee of create agent! 获取创建共识(代理)节点的手续费", notes = "返回创建的节点成功的交易手续费")
@ApiResponses(value = { @ApiResponse(code = 200, message = "success", response = String.class) })
public RpcClientResult getCreateAgentFee(@BeanParam() GetCreateAgentFeeForm form) throws NulsException {
    AssertUtil.canNotEmpty(form);
    AssertUtil.canNotEmpty(form.getAgentAddress(), "agent address can not be null");
    AssertUtil.canNotEmpty(form.getCommissionRate(), "commission rate can not be null");
    AssertUtil.canNotEmpty(form.getDeposit(), "deposit can not be null");
    AssertUtil.canNotEmpty(form.getPackingAddress(), "packing address can not be null");
    if (StringUtils.isBlank(form.getRewardAddress())) {
        form.setRewardAddress(form.getAgentAddress());
    }
    Account account = accountService.getAccount(form.getAgentAddress()).getData();
    if (null == account) {
        return Result.getFailed(AccountErrorCode.ACCOUNT_NOT_EXIST).toRpcClientResult();
    }
    if (!account.isOk()) {
        return Result.getFailed(AccountErrorCode.IMPORTING_ACCOUNT).toRpcClientResult();
    }
    CreateAgentTransaction tx = new CreateAgentTransaction();
    tx.setTime(TimeService.currentTimeMillis());
    Agent agent = new Agent();
    agent.setAgentAddress(AddressTool.getAddress(form.getAgentAddress()));
    agent.setPackingAddress(AddressTool.getAddress(form.getPackingAddress()));
    if (StringUtils.isBlank(form.getRewardAddress())) {
        agent.setRewardAddress(agent.getAgentAddress());
    } else {
        agent.setRewardAddress(AddressTool.getAddress(form.getRewardAddress()));
    }
    agent.setDeposit(Na.valueOf(form.getDeposit()));
    agent.setCommissionRate(form.getCommissionRate());
    tx.setTxData(agent);
    CoinData coinData = new CoinData();
    List<Coin> toList = new ArrayList<>();
    if (agent.getAgentAddress()[2] == 3) {
        Script scriptPubkey = SignatureUtil.createOutputScript(agent.getAgentAddress());
        toList.add(new Coin(scriptPubkey.getProgram(), agent.getDeposit(), -1));
    } else {
        toList.add(new Coin(agent.getAgentAddress(), agent.getDeposit(), -1));
    }
    coinData.setTo(toList);
    tx.setCoinData(coinData);
    CoinDataResult result = accountLedgerService.getCoinData(agent.getAgentAddress(), agent.getDeposit(), tx.size() - P2PHKSignature.SERIALIZE_LENGTH, TransactionFeeCalculator.OTHER_PRICE_PRE_1024_BYTES);
    tx.getCoinData().setFrom(result.getCoinList());
    if (null != result.getChange()) {
        tx.getCoinData().getTo().add(result.getChange());
    }
    Na fee = TransactionFeeCalculator.getMaxFee(108 + tx.size());
    Map<String, Long> map = new HashMap<>();
    map.put("fee", fee.getValue());
    map.put("maxAmount", getMaxAmount(fee, form.getAgentAddress(), tx));
    return Result.getSuccess().setData(map).toRpcClientResult();
}
Also used : Account(io.nuls.account.model.Account) MultiSigAccount(io.nuls.account.model.MultiSigAccount) StopAgent(io.nuls.consensus.poc.protocol.entity.StopAgent) Agent(io.nuls.consensus.poc.protocol.entity.Agent) CreateAgentTransaction(io.nuls.consensus.poc.protocol.tx.CreateAgentTransaction) CoinDataResult(io.nuls.account.ledger.model.CoinDataResult)

Aggregations

Account (io.nuls.account.model.Account)65 NulsException (io.nuls.kernel.exception.NulsException)38 MultiSigAccount (io.nuls.account.model.MultiSigAccount)30 CoinDataResult (io.nuls.account.ledger.model.CoinDataResult)28 IOException (java.io.IOException)28 NulsRuntimeException (io.nuls.kernel.exception.NulsRuntimeException)16 UnsupportedEncodingException (java.io.UnsupportedEncodingException)13 ECKey (io.nuls.core.tools.crypto.ECKey)12 ContractResult (io.nuls.contract.dto.ContractResult)11 Test (org.junit.Test)11 TransferTransaction (io.nuls.protocol.model.tx.TransferTransaction)9 TransactionDataResult (io.nuls.account.ledger.model.TransactionDataResult)7 ValidateResult (io.nuls.kernel.validate.ValidateResult)7 Agent (io.nuls.consensus.poc.protocol.entity.Agent)6 CancelDeposit (io.nuls.consensus.poc.protocol.entity.CancelDeposit)6 StopAgent (io.nuls.consensus.poc.protocol.entity.StopAgent)6 CancelDepositTransaction (io.nuls.consensus.poc.protocol.tx.CancelDepositTransaction)6 DepositTransaction (io.nuls.consensus.poc.protocol.tx.DepositTransaction)6 Result (io.nuls.kernel.model.Result)6 ArrayList (java.util.ArrayList)6