Java Code Examples for com.google.protobuf.InvalidProtocolBufferException#getMessage()

The following examples show how to use com.google.protobuf.InvalidProtocolBufferException#getMessage() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public boolean execute(TransactionResultWrapper ret) throws ContractExeException {
    long fee = calcFee();
    final BuyStorageBytesContract BuyStorageBytesContract;
    try {
        BuyStorageBytesContract = contract.unpack(BuyStorageBytesContract.class);
    } catch (InvalidProtocolBufferException e) {
        logger.debug(e.getMessage(), e);
        ret.setStatus(fee, code.FAILED);
        throw new ContractExeException(e.getMessage());
    }

    AccountWrapper accountWrapper = dbManager.getAccountStore()
            .get(BuyStorageBytesContract.getOwnerAddress().toByteArray());
    long bytes = BuyStorageBytesContract.getBytes();

    storageMarket.buyStorageBytes(accountWrapper, bytes);

    ret.setStatus(fee, code.SUCESS);

    return true;
}
 
Example 2
@Override
public boolean execute(TransactionResultWrapper ret) throws ContractExeException {
    long fee = calcFee();
    try {
        Contract.UpdateCpuLimitContract usContract = contract
                .unpack(Contract.UpdateCpuLimitContract.class);
        long newOriginCpuLimit = usContract.getOriginCpuLimit();
        byte[] contractAddress = usContract.getContractAddress().toByteArray();
        ContractWrapper deployedContract = dbManager.getContractStore().get(contractAddress);

        dbManager.getContractStore().put(contractAddress, new ContractWrapper(
                deployedContract.getInstance().toBuilder().setOriginCpuLimit(newOriginCpuLimit)
                        .build()));

        ret.setStatus(fee, code.SUCESS);
    } catch (InvalidProtocolBufferException e) {
        logger.debug(e.getMessage(), e);
        ret.setStatus(fee, code.FAILED);
        throw new ContractExeException(e.getMessage());
    }
    return true;
}
 
Example 3
@Override
public boolean execute(TransactionResultWrapper ret) throws ContractExeException {
    long fee = calcFee();
    final SellStorageContract sellStorageContract;
    try {
        sellStorageContract = contract.unpack(SellStorageContract.class);
    } catch (InvalidProtocolBufferException e) {
        logger.debug(e.getMessage(), e);
        ret.setStatus(fee, code.FAILED);
        throw new ContractExeException(e.getMessage());
    }

    AccountWrapper accountWrapper = dbManager.getAccountStore()
            .get(sellStorageContract.getOwnerAddress().toByteArray());

    long bytes = sellStorageContract.getStorageBytes();

    storageMarket.sellStorage(accountWrapper, bytes);

    ret.setStatus(fee, code.SUCESS);

    return true;
}
 
Example 4
@Override
public boolean execute(TransactionResultWrapper ret) throws ContractExeException {
    long fee = calcFee();
    try {
        ClearABIContract usContract = contract.unpack(ClearABIContract.class);

        byte[] contractAddress = usContract.getContractAddress().toByteArray();
        ContractWrapper deployedContract = dbManager.getContractStore().get(contractAddress);

        deployedContract.clearABI();
        dbManager.getContractStore().put(contractAddress, deployedContract);

        ret.setStatus(fee, code.SUCESS);
    } catch (InvalidProtocolBufferException e) {
        logger.debug(e.getMessage(), e);
        ret.setStatus(fee, code.FAILED);
        throw new ContractExeException(e.getMessage());
    }
    return true;
}
 
Example 5
@Override 
public Row expandRow (FDBStore store, Session session,
                        FDBStoreData storeData, Schema schema) {
    ensureRowConverter();
    DynamicMessage msg;
    try {
        msg = DynamicMessage.parseFrom(rowConverter.getMessageType(), storeData.rawValue);
    } catch (InvalidProtocolBufferException ex) {
        ProtobufReadException nex = new ProtobufReadException(rowDataConverter.getMessageType().getName(), ex.getMessage());
        nex.initCause(ex);
        throw nex;
    }
    Row row = rowConverter.decode(msg);
    row = overlayBlobData(row.rowType(), row, store, session);
    return row;
}
 
Example 6
/**
 * 身份的反序列化
 *
 * @param raw
 * @return
 * @throws MspException
 */
public Identities.SerializedIdentity deserialize(byte[] raw) throws MspException {
    Identities.SerializedIdentity sId = null;
    try {
        sId = Identities.SerializedIdentity.parseFrom(raw);
    } catch (InvalidProtocolBufferException e) {
        throw new MspException(e.getMessage());
    }
    return sId;
}
 
Example 7
protected void logFailedStatus(Digest actionDigest, com.google.rpc.Status status) {
  String message =
      format(
          "%s: %s: %s\n",
          DigestUtil.toString(actionDigest),
          Code.forNumber(status.getCode()),
          status.getMessage());
  for (Any detail : status.getDetailsList()) {
    if (detail.is(PreconditionFailure.class)) {
      message += "  PreconditionFailure:\n";
      PreconditionFailure preconditionFailure;
      try {
        preconditionFailure = detail.unpack(PreconditionFailure.class);
        for (Violation violation : preconditionFailure.getViolationsList()) {
          message +=
              format(
                  "    Violation: %s %s: %s\n",
                  violation.getType(), violation.getSubject(), violation.getDescription());
        }
      } catch (InvalidProtocolBufferException e) {
        message += "  " + e.getMessage();
      }
    } else {
      message += "  Unknown Detail\n";
    }
  }
  getLogger().info(message);
}
 
Example 8
Source Project: aion_api   File: Chain.java    License: MIT License 5 votes vote down vote up
public ApiMsg getBlockByHash(Hash256 blockHash) {
    if (!this.apiInst.isConnected()) {
        return new ApiMsg(-1003);
    }

    Message.req_getBlockByHash reqBody =
            Message.req_getBlockByHash
                    .newBuilder()
                    .setBlockHash(ByteString.copyFrom(blockHash.toBytes()))
                    .build();

    byte[] reqHead =
            ApiUtils.toReqHeader(
                    ApiUtils.PROTOCOL_VER,
                    Message.Servs.s_chain,
                    Message.Funcs.f_getBlockByHash);
    byte[] reqMsg = ByteUtil.merge(reqHead, reqBody.toByteArray());

    byte[] rsp = this.apiInst.nbProcess(reqMsg);

    int code = this.apiInst.validRspHeader(rsp);
    if (code != 1) {
        return new ApiMsg(code);
    }

    try {
        return new ApiMsg(
                toBlock(Message.rsp_getBlock.parseFrom(ApiUtils.parseBody(rsp).getData())),
                cast.OTHERS);
    } catch (InvalidProtocolBufferException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(
                    "[getBlkByHash] {} exception: [{}]",
                    ErrId.getErrString(-104L),
                    e.getMessage());
        }
        return new ApiMsg(-104, e.getMessage(), cast.OTHERS);
    }
}
 
Example 9
Source Project: aion_api   File: Tx.java    License: MIT License 5 votes vote down vote up
public ApiMsg getTxReceipt(Hash256 txHash) {
    if (!this.apiInst.isConnected()) {
        return new ApiMsg(-1003);
    }

    Message.req_getTransactionReceipt reqBody =
            Message.req_getTransactionReceipt
                    .newBuilder()
                    .setTxHash(ByteString.copyFrom(txHash.toBytes()))
                    .build();

    byte[] reqHead =
            ApiUtils.toReqHeader(
                    ApiUtils.PROTOCOL_VER,
                    Message.Servs.s_tx,
                    Message.Funcs.f_getTransactionReceipt);
    byte[] reqMsg = ByteUtil.merge(reqHead, reqBody.toByteArray());

    byte[] rsp = this.apiInst.nbProcess(reqMsg);
    int code = this.apiInst.validRspHeader(rsp);
    if (code != 1) {
        return new ApiMsg(code);
    }

    try {
        Message.rsp_getTransactionReceipt mrsp =
                Message.rsp_getTransactionReceipt.parseFrom(ApiUtils.parseBody(rsp).getData());
        return new ApiMsg(ApiUtils.toTransactionReceipt(mrsp), ApiMsg.cast.OTHERS);
    } catch (InvalidProtocolBufferException e) {
        // Todo : kernel return message change
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(
                    "[getTxReceipt] {} exception: [{}]",
                    ErrId.getErrString(-104L),
                    e.getMessage());
        }
        return new ApiMsg(-104, e.getMessage(), ApiMsg.cast.OTHERS);
    }
}
 
Example 10
Source Project: aion_api   File: Tx.java    License: MIT License 5 votes vote down vote up
public ApiMsg getSolcVersion() {
    if (!this.apiInst.isConnected()) {
        return new ApiMsg(-1003);
    }

    byte[] reqHead =
            ApiUtils.toReqHeader(
                    ApiUtils.PROTOCOL_VER, Message.Servs.s_tx, Message.Funcs.f_getSolcVersion);

    byte[] rsp = this.apiInst.nbProcess(reqHead);
    int code = this.apiInst.validRspHeader(rsp);
    if (code != 1) {
        return new ApiMsg(code);
    }

    try {
        return new ApiMsg(
                Message.rsp_getSolcVersion
                        .parseFrom(ApiUtils.parseBody(rsp).getData())
                        .getVer(),
                ApiMsg.cast.OTHERS);
    } catch (InvalidProtocolBufferException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(
                    "[getSolcVersion] {} exception: [{}]",
                    ErrId.getErrString(-104L),
                    e.getMessage());
        }
        return new ApiMsg(-104, e.getMessage(), ApiMsg.cast.OTHERS);
    }
}
 
Example 11
/**
 * Process the raftClientReply and return OMResponse.
 * @param omRequest
 * @param reply
 * @return OMResponse - response which is returned to client.
 * @throws ServiceException
 */
private OMResponse processReply(OMRequest omRequest, RaftClientReply reply)
    throws ServiceException {
  // NotLeader exception is thrown only when the raft server to which the
  // request is submitted is not the leader. This can happen first time
  // when client is submitting request to OM.

  if (!reply.isSuccess()) {
    NotLeaderException notLeaderException = reply.getNotLeaderException();
    if (notLeaderException != null) {
      throw new ServiceException(
          OMNotLeaderException.convertToOMNotLeaderException(
                notLeaderException, getRaftPeerId()));
    }

    LeaderNotReadyException leaderNotReadyException =
        reply.getLeaderNotReadyException();
    if (leaderNotReadyException != null) {
      throw new ServiceException(new OMLeaderNotReadyException(
          leaderNotReadyException.getMessage()));
    }

    StateMachineException stateMachineException =
        reply.getStateMachineException();
    if (stateMachineException != null) {
      OMResponse.Builder omResponse = OMResponse.newBuilder()
          .setCmdType(omRequest.getCmdType())
          .setSuccess(false)
          .setTraceID(omRequest.getTraceID());
      if (stateMachineException.getCause() != null) {
        omResponse.setMessage(stateMachineException.getCause().getMessage());
        omResponse.setStatus(
            exceptionToResponseStatus(stateMachineException.getCause()));
      } else {
        // Current Ratis is setting cause, this is an safer side check.
        LOG.error("StateMachine exception cause is not set");
        omResponse.setStatus(
            OzoneManagerProtocolProtos.Status.INTERNAL_ERROR);
        omResponse.setMessage(
            StringUtils.stringifyException(stateMachineException));
      }

      if (LOG.isDebugEnabled()) {
        LOG.debug("Error while executing ratis request. " +
            "stateMachineException: ", stateMachineException);
      }
      return omResponse.build();
    }
  }

  try {
    return OMRatisHelper.getOMResponseFromRaftClientReply(reply);
  } catch (InvalidProtocolBufferException ex) {
    if (ex.getMessage() != null) {
      throw new ServiceException(ex.getMessage(), ex);
    } else {
      throw new ServiceException(ex);
    }
  }

  // TODO: Still need to handle RaftRetry failure exception and
  //  NotReplicated exception.
}
 
Example 12
Source Project: aion_api   File: Chain.java    License: MIT License 4 votes vote down vote up
public ApiMsg getTransactionByBlockHashAndIndex(Hash256 blockHash, int index) {
    if (!apiInst.isInitialized.get()) {
        return new ApiMsg(-1003);
    }

    if (index < -1) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("[getTxByBlkHash&TxIdx] {}", ErrId.getErrString(-311L));
        }
        return new ApiMsg(-311);
    }

    Message.req_getTransactionByBlockHashAndIndex reqBody =
            Message.req_getTransactionByBlockHashAndIndex
                    .newBuilder()
                    .setBlockHash(ByteString.copyFrom(blockHash.toBytes()))
                    .setTxIndex(index)
                    .build();

    byte[] reqHead =
            ApiUtils.toReqHeader(
                    ApiUtils.PROTOCOL_VER,
                    Message.Servs.s_chain,
                    Message.Funcs.f_getTransactionByBlockHashAndIndex);
    byte[] reqMsg = ByteUtil.merge(reqHead, reqBody.toByteArray());

    byte[] rsp = this.apiInst.nbProcess(reqMsg);
    int code = this.apiInst.validRspHeader(rsp);

    if (code != 1) {
        return new ApiMsg(code);
    }

    try {
        return new ApiMsg(
                ApiUtils.toTransaction(
                        Message.rsp_getTransaction.parseFrom(
                                ApiUtils.parseBody(rsp).getData())),
                cast.OTHERS);
    } catch (InvalidProtocolBufferException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(
                    "[getTxByBlkHash&TxIdx] {} exception: [{}]",
                    ErrId.getErrString(-104L),
                    e.getMessage());
        }
        return new ApiMsg(-104, e.getMessage(), cast.OTHERS);
    }
}
 
Example 13
Source Project: aion_api   File: Admin.java    License: MIT License 4 votes vote down vote up
@Override
public ApiMsg getBlockDetailsByHash(Hash256 blockHash) {
    if (!this.apiInst.isConnected()) {
        return new ApiMsg(-1003);
    }

    if (blockHash == null) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("[getBlockDetailsByHash]" + ErrId.getErrString(-17L));
        }
        return new ApiMsg(-17);
    }

    Message.req_getBlockDetailsByHash reqBody =
            Message.req_getBlockDetailsByHash
                    .newBuilder()
                    .setBlockHash(ByteString.copyFrom(blockHash.toBytes()))
                    .build();

    byte[] reqHead =
            ApiUtils.toReqHeader(
                    ApiUtils.PROTOCOL_VER,
                    Message.Servs.s_admin,
                    Funcs.f_getBlockDetailsByHash);
    byte[] reqMsg = ByteUtil.merge(reqHead, reqBody.toByteArray());

    byte[] rsp = this.apiInst.nbProcess(reqMsg);
    int code = this.apiInst.validRspHeader(rsp);
    if (code != 1) {
        return new ApiMsg(code);
    }

    try {
        List<BlockDetails> k =
                ApiUtils.toBlockDetails(
                        Collections.singletonList(
                                rsp_getBlockDetailsByHash
                                        .parseFrom(ApiUtils.parseBody(rsp).getData())
                                        .getBlkDetails()));
        return new ApiMsg(k.get(0), org.aion.api.type.ApiMsg.cast.OTHERS);
    } catch (InvalidProtocolBufferException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(
                    "[getBlockDetailsByHash]" + ErrId.getErrString(-104L) + e.getMessage());
        }
        return new ApiMsg(-104, e.getMessage(), org.aion.api.type.ApiMsg.cast.OTHERS);
    }
}
 
Example 14
Source Project: aion_api   File: Admin.java    License: MIT License 4 votes vote down vote up
@SuppressWarnings("Duplicates")
@Override
public ApiMsg getBlockSqlByRange(Long blkStart, Long blkEnd) {
    if (!this.apiInst.isConnected()) {
        return new ApiMsg(-1003);
    }

    if (blkStart == null || blkEnd == null || blkStart < 0 || blkEnd < 0 || blkEnd < blkStart) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("[getBlockSqlByNumber]" + ErrId.getErrString(-17L));
        }
        return new ApiMsg(-17);
    }

    Message.req_getBlockSqlByRange reqBody =
            Message.req_getBlockSqlByRange
                    .newBuilder()
                    .setBlkNumberStart(blkStart)
                    .setBlkNumberEnd(blkEnd)
                    .build();

    byte[] reqHead =
            ApiUtils.toReqHeader(
                    ApiUtils.PROTOCOL_VER,
                    Message.Servs.s_admin,
                    Message.Funcs.f_getBlockSqlByRange);
    byte[] reqMsg = ByteUtil.merge(reqHead, reqBody.toByteArray());

    byte[] rsp = this.apiInst.nbProcess(reqMsg);
    int code = this.apiInst.validRspHeader(rsp);
    if (code != 1) {
        return new ApiMsg(code);
    }

    try {
        List<BlockSql> k =
                ApiUtils.toBlockSql(
                        Message.rsp_getBlockSqlByRange
                                .parseFrom(ApiUtils.parseBody(rsp).getData())
                                .getBlkSqlList());
        return new ApiMsg(k, org.aion.api.type.ApiMsg.cast.OTHERS);
    } catch (InvalidProtocolBufferException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("[getBlockSqlByRange]" + ErrId.getErrString(-104L) + e.getMessage());
        }
        return new ApiMsg(-104, e.getMessage(), org.aion.api.type.ApiMsg.cast.OTHERS);
    }
}
 
Example 15
@Override
public boolean validate() throws ContractValidateException {
    if (this.contract == null) {
        throw new ContractValidateException("No contract!");
    }
    if (this.dbManager == null) {
        throw new ContractValidateException("No dbManager!");
    }
    if (!this.contract.is(AccountUpdateContract.class)) {
        throw new ContractValidateException(
                "contract type error,expected type [AccountUpdateContract],real type[" + contract
                        .getClass() + "]");
    }
    final AccountUpdateContract accountUpdateContract;
    try {
        accountUpdateContract = contract.unpack(AccountUpdateContract.class);
    } catch (InvalidProtocolBufferException e) {
        logger.debug(e.getMessage(), e);
        throw new ContractValidateException(e.getMessage());
    }
    byte[] ownerAddress = accountUpdateContract.getOwnerAddress().toByteArray();
    byte[] accountName = accountUpdateContract.getAccountName().toByteArray();
    if (!TransactionUtil.validAccountName(accountName)) {
        throw new ContractValidateException("Invalid accountName");
    }
    if (!Wallet.addressValid(ownerAddress)) {
        throw new ContractValidateException("Invalid ownerAddress");
    }

    AccountWrapper account = dbManager.getAccountStore().get(ownerAddress);
    if (account == null) {
        throw new ContractValidateException("Account has not existed");
    }

    if (account.getAccountName() != null && !account.getAccountName().isEmpty()
            && dbManager.getDynamicPropertiesStore().getAllowUpdateAccountName() == 0) {
        throw new ContractValidateException("This account name already exist");
    }

    if (dbManager.getAccountIndexStore().has(accountName)
            && dbManager.getDynamicPropertiesStore().getAllowUpdateAccountName() == 0) {
        throw new ContractValidateException("This name has existed");
    }

    return true;
}
 
Example 16
Source Project: aion_api   File: Tx.java    License: MIT License 4 votes vote down vote up
public ApiMsg estimateNrg(TxArgs args) {
    if (!this.apiInst.isConnected()) {
        return new ApiMsg(-1003);
    }

    byte[] reqMsg;
    byte[] hash = ApiUtils.genHash(ApiUtils.MSG_HASH_LEN);
    if (this.fastbuild) {
        if (args == null) {
            if (fmsg == null) {
                throw new IllegalArgumentException("Null fmsg");
            }

            int msglen = fmsg.getData().length;
            reqMsg = new byte[msglen];

            System.arraycopy(fmsg.getData(), 0, reqMsg, 0, msglen);
            System.arraycopy(
                    hash, 0, reqMsg, ApiUtils.REQ_HEADER_NOHASH_LEN, ApiUtils.MSG_HASH_LEN);
        } else {
            throw new IllegalArgumentException();
        }
    } else {
        if (args == null) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("[sendTransaction] {}", ErrId.getErrString(-303L));
            }
            return new ApiMsg(-303);
        }

        byte[] reqHead =
                ApiUtils.toReqHeader(
                        ApiUtils.PROTOCOL_VER, Message.Servs.s_tx, Message.Funcs.f_estimateNrg);

        Message.req_estimateNrg reqBody =
                Message.req_estimateNrg
                        .newBuilder()
                        .setFrom(
                                ByteString.copyFrom(
                                        args.getFrom() == null
                                                ? apiInst.defaultAccount.toBytes()
                                                : args.getFrom().toBytes()))
                        .setTo(ByteString.copyFrom(args.getTo().toBytes()))
                        .setData(ByteString.copyFrom(args.getData().toBytes()))
                        .setValue(ByteString.copyFrom(args.getValue().toByteArray()))
                        .setNrg(args.getNrgLimit())
                        .setNrgPrice(args.getNrgPrice())
                        .build();

        reqMsg = ByteUtil.merge(reqHead, reqBody.toByteArray());
    }

    byte[] rsp = this.apiInst.nbProcess(reqMsg);
    int code = this.apiInst.validRspHeader(rsp);
    if (code != 1) {
        return new ApiMsg(code);
    }

    try {
        return new ApiMsg(
                Message.rsp_estimateNrg.parseFrom(ApiUtils.parseBody(rsp).getData()).getNrg(),
                ApiMsg.cast.LONG);
    } catch (InvalidProtocolBufferException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(
                    "[getCode] {} exception: [{}]", ErrId.getErrString(-104L), e.getMessage());
        }
        return new ApiMsg(-104, e.getMessage(), ApiMsg.cast.OTHERS);
    }
}
 
Example 17
@Override
public boolean validate() throws ContractValidateException {
    if (this.contract == null) {
        throw new ContractValidateException("No contract!");
    }
    if (this.dbManager == null) {
        throw new ContractValidateException("No dbManager!");
    }
    if (!this.contract.is(SetAccountIdContract.class)) {
        throw new ContractValidateException(
                "contract type error,expected type [SetAccountIdContract],real type[" + contract
                        .getClass() + "]");
    }
    final SetAccountIdContract setAccountIdContract;
    try {
        setAccountIdContract = contract.unpack(SetAccountIdContract.class);
    } catch (InvalidProtocolBufferException e) {
        logger.debug(e.getMessage(), e);
        throw new ContractValidateException(e.getMessage());
    }
    byte[] ownerAddress = setAccountIdContract.getOwnerAddress().toByteArray();
    byte[] accountId = setAccountIdContract.getAccountId().toByteArray();
    if (!TransactionUtil.validAccountId(accountId)) {
        throw new ContractValidateException("Invalid accountId");
    }
    if (!Wallet.addressValid(ownerAddress)) {
        throw new ContractValidateException("Invalid ownerAddress");
    }

    AccountWrapper account = dbManager.getAccountStore().get(ownerAddress);
    if (account == null) {
        throw new ContractValidateException("Account has not existed");
    }
    if (account.getAccountId() != null && !account.getAccountId().isEmpty()) {
        throw new ContractValidateException("This account id already set");
    }
    if (dbManager.getAccountIdIndexStore().has(accountId)) {
        throw new ContractValidateException("This id has existed");
    }

    return true;
}
 
Example 18
Source Project: aion_api   File: Chain.java    License: MIT License 4 votes vote down vote up
/**
 * GetNonce returns a BigInteger representing the nonce of the account address at the latest
 * block number.
 *
 * @param address the class {@link Address Address} of the desired account to get the nonce of.
 * @return the account's nonce.
 */
public ApiMsg getNonce(Address address) {
    if (!apiInst.isInitialized.get()) {
        return new ApiMsg(-1003);
    }

    Message.req_getNonce reqBody =
            Message.req_getNonce
                    .newBuilder()
                    .setAddress(ByteString.copyFrom(address.toBytes()))
                    .build();

    byte[] reqHead =
            ApiUtils.toReqHeader(
                    ApiUtils.PROTOCOL_VER, Message.Servs.s_chain, Message.Funcs.f_getNonce);
    byte[] reqMsg = ByteUtil.merge(reqHead, reqBody.toByteArray());

    byte[] rsp = this.apiInst.nbProcess(reqMsg);
    int code = this.apiInst.validRspHeader(rsp);
    if (code != 1) {
        return new ApiMsg(code);
    }

    try {
        Message.rsp_getNonce resp =
                Message.rsp_getNonce.parseFrom(ApiUtils.parseBody(rsp).getData());

        byte[] nonce = resp.getNonce().toByteArray();
        if (nonce == null) {
            return new ApiMsg(
                    Retcode.r_fail_null_rsp_VALUE,
                    "null nonce for address " + address,
                    cast.OTHERS);
        } else {
            return new ApiMsg(new BigInteger(1, nonce), cast.OTHERS);
        }

    } catch (InvalidProtocolBufferException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("[getNonce] {}", ErrId.getErrString(-104L) + e.getMessage());
        }
        return new ApiMsg(-104, e.getMessage(), cast.OTHERS);
    }
}
 
Example 19
@Override
public boolean validate() throws ContractValidateException {
    if (this.contract == null) {
        throw new ContractValidateException("No contract!");
    }
    if (this.dbManager == null) {
        throw new ContractValidateException("No dbManager!");
    }
    if (this.dbManager.getDynamicPropertiesStore().getAllowMultiSign() != 1) {
        throw new ContractValidateException("multi sign is not allowed, "
                + "need to be opened by the committee");
    }
    if (!this.contract.is(AccountPermissionUpdateContract.class)) {
        throw new ContractValidateException(
                "contract type error,expected type [AccountPermissionUpdateContract],real type["
                        + contract
                        .getClass() + "]");
    }
    final AccountPermissionUpdateContract accountPermissionUpdateContract;
    try {
        accountPermissionUpdateContract = contract.unpack(AccountPermissionUpdateContract.class);
    } catch (InvalidProtocolBufferException e) {
        logger.debug(e.getMessage(), e);
        throw new ContractValidateException(e.getMessage());
    }
    byte[] ownerAddress = accountPermissionUpdateContract.getOwnerAddress().toByteArray();
    if (!Wallet.addressValid(ownerAddress)) {
        throw new ContractValidateException("invalidate ownerAddress");
    }
    AccountWrapper accountWrapper = dbManager.getAccountStore().get(ownerAddress);
    if (accountWrapper == null) {
        throw new ContractValidateException("ownerAddress account does not exist");
    }

    if (!accountPermissionUpdateContract.hasOwner()) {
        throw new ContractValidateException("owner permission is missed");
    }

    if (accountWrapper.getIsWitness()) {
        if (!accountPermissionUpdateContract.hasWitness()) {
            throw new ContractValidateException("witness permission is missed");
        }
    } else {
        if (accountPermissionUpdateContract.hasWitness()) {
            throw new ContractValidateException("account isn't witness can't set witness permission");
        }
    }

    if (accountPermissionUpdateContract.getActivesCount() == 0) {
        throw new ContractValidateException("active permission is missed");
    }
    if (accountPermissionUpdateContract.getActivesCount() > 8) {
        throw new ContractValidateException("active permission is too many");
    }

    Permission owner = accountPermissionUpdateContract.getOwner();
    Permission witness = accountPermissionUpdateContract.getWitness();
    List<Permission> actives = accountPermissionUpdateContract.getActivesList();

    if (owner.getType() != PermissionType.Owner) {
        throw new ContractValidateException("owner permission type is error");
    }
    if (!checkPermission(owner)) {
        return false;
    }
    if (accountWrapper.getIsWitness()) {
        if (witness.getType() != PermissionType.Witness) {
            throw new ContractValidateException("witness permission type is error");
        }
        if (!checkPermission(witness)) {
            return false;
        }
    }
    for (Permission permission : actives) {
        if (permission.getType() != PermissionType.Active) {
            throw new ContractValidateException("active permission type is error");
        }
        if (!checkPermission(permission)) {
            return false;
        }
    }
    return true;
}
 
Example 20
Source Project: aion_api   File: Chain.java    License: MIT License 4 votes vote down vote up
public ApiMsg getBalance(Address address, long blockNumber) {

        if (!apiInst.isInitialized.get()) {
            return new ApiMsg(-1003);
        }

        if (blockNumber < -1L) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("[getBalance] {}", ErrId.getErrString(-129L));
            }
            return new ApiMsg(-129);
        }

        Message.req_getBalance reqBody =
                Message.req_getBalance
                        .newBuilder()
                        .setAddress(ByteString.copyFrom(address.toBytes()))
                        .setBlockNumber(blockNumber)
                        .build();

        byte[] reqHead =
                ApiUtils.toReqHeader(
                        ApiUtils.PROTOCOL_VER, Message.Servs.s_chain, Message.Funcs.f_getBalance);
        byte[] reqMsg = ByteUtil.merge(reqHead, reqBody.toByteArray());

        byte[] rsp = this.apiInst.nbProcess(reqMsg);
        int code = this.apiInst.validRspHeader(rsp);
        if (code != 1) {
            return new ApiMsg(code);
        }

        try {
            Message.rsp_getBalance resp =
                    Message.rsp_getBalance.parseFrom(ApiUtils.parseBody(rsp).getData());

            byte[] balance = resp.getBalance().toByteArray();
            if (balance == null) {
                return new ApiMsg(
                        Retcode.r_fail_null_rsp_VALUE,
                        "null balance for address " + address + " and blockNumber " + blockNumber,
                        cast.OTHERS);
            } else {
                return new ApiMsg(new BigInteger(1, balance), cast.OTHERS);
            }

        } catch (InvalidProtocolBufferException e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("[getBalance] {}", ErrId.getErrString(-104L) + e.getMessage());
            }
            return new ApiMsg(-104, e.getMessage(), cast.OTHERS);
        }
    }