Search in sources :

Example 1 with NxtException

use of org.xel.NxtException in project elastic-core-maven by OrdinaryDude.

the class APIServlet method process.

private void process(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Set response values now in case we create an asynchronous context
    resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
    resp.setHeader("Pragma", "no-cache");
    resp.setDateHeader("Expires", 0);
    resp.setContentType("text/plain; charset=UTF-8");
    JSONStreamAware response = JSON.emptyJSON;
    long startTime = System.currentTimeMillis();
    try {
        if (!API.isAllowed(req.getRemoteHost())) {
            response = ERROR_NOT_ALLOWED;
            return;
        }
        String requestType = req.getParameter("requestType");
        if (requestType == null) {
            response = ERROR_INCORRECT_REQUEST;
            return;
        }
        APIRequestHandler apiRequestHandler = apiRequestHandlers.get(requestType);
        if (apiRequestHandler == null) {
            if (disabledRequestHandlers.containsKey(requestType)) {
                response = ERROR_DISABLED;
            } else {
                response = ERROR_INCORRECT_REQUEST;
            }
            return;
        }
        if (Constants.isLightClient && apiRequestHandler.requireFullClient()) {
            response = LIGHT_CLIENT_DISABLED_API;
            return;
        }
        if (enforcePost && apiRequestHandler.requirePost() && !"POST".equals(req.getMethod())) {
            response = POST_REQUIRED;
            return;
        }
        if (apiRequestHandler.requirePassword()) {
            API.verifyPassword(req);
        }
        final long requireBlockId = apiRequestHandler.allowRequiredBlockParameters() ? ParameterParser.getUnsignedLong(req, "requireBlock", false) : 0;
        final long requireLastBlockId = apiRequestHandler.allowRequiredBlockParameters() ? ParameterParser.getUnsignedLong(req, "requireLastBlock", false) : 0;
        if (requireBlockId != 0 || requireLastBlockId != 0) {
            Nxt.getBlockchain().readLock();
        }
        try {
            try {
                if (apiRequestHandler.startDbTransaction()) {
                    Db.db.beginTransaction();
                }
                if (requireBlockId != 0 && !Nxt.getBlockchain().hasBlock(requireBlockId)) {
                    response = REQUIRED_BLOCK_NOT_FOUND;
                    return;
                }
                if (requireLastBlockId != 0 && requireLastBlockId != Nxt.getBlockchain().getLastBlock().getId()) {
                    response = REQUIRED_LAST_BLOCK_NOT_FOUND;
                    return;
                }
                response = apiRequestHandler.processRequest(req, resp);
                if (requireLastBlockId == 0 && requireBlockId != 0 && response instanceof JSONObject) {
                    ((JSONObject) response).put("lastBlock", Nxt.getBlockchain().getLastBlock().getStringId());
                }
            } finally {
                if (apiRequestHandler.startDbTransaction()) {
                    Db.db.endTransaction();
                }
            }
        } finally {
            if (requireBlockId != 0 || requireLastBlockId != 0) {
                Nxt.getBlockchain().readUnlock();
            }
        }
    } catch (ParameterException e) {
        response = e.getErrorResponse();
    } catch (NxtException | RuntimeException e) {
        Logger.logDebugMessage("Error processing API request", e);
        JSONObject json = new JSONObject();
        JSONData.putException(json, e);
        response = JSON.prepare(json);
    } catch (ExceptionInInitializerError err) {
        Logger.logErrorMessage("Initialization Error", err.getCause());
        response = ERROR_INCORRECT_REQUEST;
    } catch (Exception e) {
        Logger.logErrorMessage("Error processing request", e);
        response = ERROR_INCORRECT_REQUEST;
    } finally {
        // The response will be null if we created an asynchronous context
        if (response != null) {
            if (response instanceof JSONObject) {
                ((JSONObject) response).put("requestProcessingTime", System.currentTimeMillis() - startTime);
            }
            try (Writer writer = resp.getWriter()) {
                JSON.writeJSONString(response, writer);
            }
        }
    }
}
Also used : JSONObject(org.json.simple.JSONObject) NxtException(org.xel.NxtException) JSONStreamAware(org.json.simple.JSONStreamAware) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) NxtException(org.xel.NxtException) Writer(java.io.Writer)

Example 2 with NxtException

use of org.xel.NxtException in project elastic-core-maven by OrdinaryDude.

the class GetTaggedDataExtendTransactions method processRequest.

@Override
protected JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {
    long taggedDataId = ParameterParser.getUnsignedLong(req, "transaction", true);
    List<Long> extendTransactions = TaggedData.getExtendTransactionIds(taggedDataId);
    JSONObject response = new JSONObject();
    JSONArray jsonArray = new JSONArray();
    Blockchain blockchain = Nxt.getBlockchain();
    Filter<Appendix> filter = (appendix) -> !(appendix instanceof Attachment.TaggedDataExtend);
    extendTransactions.forEach(transactionId -> jsonArray.add(JSONData.transaction(blockchain.getTransaction(transactionId), filter)));
    response.put("extendTransactions", jsonArray);
    return response;
}
Also used : Filter(org.xel.util.Filter) Attachment(org.xel.Attachment) HttpServletRequest(javax.servlet.http.HttpServletRequest) List(java.util.List) NxtException(org.xel.NxtException) JSONObject(org.json.simple.JSONObject) Blockchain(org.xel.Blockchain) JSONStreamAware(org.json.simple.JSONStreamAware) Nxt(org.xel.Nxt) Appendix(org.xel.Appendix) TaggedData(org.xel.TaggedData) JSONArray(org.json.simple.JSONArray) JSONObject(org.json.simple.JSONObject) Blockchain(org.xel.Blockchain) JSONArray(org.json.simple.JSONArray) Appendix(org.xel.Appendix)

Example 3 with NxtException

use of org.xel.NxtException in project elastic-core-maven by OrdinaryDude.

the class UserServlet method process.

private void process(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
    resp.setHeader("Pragma", "no-cache");
    resp.setDateHeader("Expires", 0);
    User user = null;
    try {
        String userPasscode = req.getParameter("user");
        if (userPasscode == null) {
            return;
        }
        user = Users.getUser(userPasscode);
        if (Users.allowedUserHosts != null && !Users.allowedUserHosts.contains(req.getRemoteHost())) {
            user.enqueue(DENY_ACCESS);
            return;
        }
        String requestType = req.getParameter("requestType");
        if (requestType == null) {
            user.enqueue(INCORRECT_REQUEST);
            return;
        }
        UserRequestHandler userRequestHandler = userRequestHandlers.get(requestType);
        if (userRequestHandler == null) {
            user.enqueue(INCORRECT_REQUEST);
            return;
        }
        if (enforcePost && userRequestHandler.requirePost() && !"POST".equals(req.getMethod())) {
            user.enqueue(POST_REQUIRED);
            return;
        }
        JSONStreamAware response = userRequestHandler.processRequest(req, user);
        if (response != null) {
            user.enqueue(response);
        }
    } catch (RuntimeException | NxtException e) {
        Logger.logMessage("Error processing GET request", e);
        if (user != null) {
            JSONObject response = new JSONObject();
            response.put("response", "showMessage");
            response.put("message", e.toString());
            user.enqueue(response);
        }
    } finally {
        if (user != null) {
            user.processPendingResponses(req, resp);
        }
    }
}
Also used : JSONObject(org.json.simple.JSONObject) NxtException(org.xel.NxtException) JSONStreamAware(org.json.simple.JSONStreamAware)

Example 4 with NxtException

use of org.xel.NxtException in project elastic-core-maven by OrdinaryDude.

the class SubmitSolution method processRequest.

@Override
protected JSONStreamAware processRequest(final HttpServletRequest req) throws NxtException {
    final long workId = ParameterParser.getUnsignedLong(req, "work_id", true);
    byte[] data = ParameterParser.getBytes(req, "data", false);
    final byte[] multiplicator = ParameterParser.getBytes(req, "multiplicator", true);
    int storageId = ParameterParser.getInt(req, "storage_id", 0, Integer.MAX_VALUE, true);
    if (data == null || data.length == 0)
        storageId = -1;
    final boolean is_pow = ParameterParser.getBooleanByString(req, "is_pow", true);
    if (is_pow)
        data = new byte[0];
    byte[] hash = ParameterParser.getBytes(req, "hash", false);
    Work w = Work.getWork(workId);
    if (w == null || w.isClosed()) {
        return JSONResponses.ERROR_WORK_INCORRECT;
    }
    CommandPowBty work = new CommandPowBty(workId, is_pow, multiplicator, hash, data, storageId, w.getCurrentRound());
    try {
        MessageEncoder.push(work, ParameterParser.getSecretPhrase(req, true));
        return JSONResponses.EVERYTHING_ALRIGHT;
    } catch (IOException e) {
        Logger.logInfoMessage("Work " + String.valueOf(w.getId()) + " submission failed. IO Exception");
        return JSONResponses.ERROR_INCORRECT_REQUEST;
    } catch (NxtException.ValidationException e) {
        Logger.logInfoMessage("Work " + String.valueOf(w.getId()) + " submission failed: " + e.getMessage());
        JSONObject response = new JSONObject();
        response.put("errorCode", 6009);
        response.put("errorDescription", e.getMessage());
        return response;
    }
}
Also used : JSONObject(org.json.simple.JSONObject) CommandPowBty(org.xel.computation.CommandPowBty) CommandCancelWork(org.xel.computation.CommandCancelWork) Work(org.xel.Work) NxtException(org.xel.NxtException) IOException(java.io.IOException)

Example 5 with NxtException

use of org.xel.NxtException in project elastic-core-maven by OrdinaryDude.

the class ProcessBlock method processRequest.

@Override
JSONStreamAware processRequest(final JSONObject request, final Peer peer) {
    String previousBlockId = (String) request.get("previousBlock");
    Block lastBlock = Nxt.getBlockchain().getLastBlock();
    if (lastBlock.getStringId().equals(previousBlockId) || (Convert.parseUnsignedLong(previousBlockId) == lastBlock.getPreviousBlockId() && lastBlock.getTimestamp() > Convert.parseLong(request.get("timestamp")))) {
        Peers.peersService.submit(() -> {
            try {
                Nxt.getBlockchainProcessor().processPeerBlock(request);
            } catch (NxtException | RuntimeException e) {
                if (peer != null) {
                    peer.blacklist(e);
                }
            }
        });
    }
    return JSON.emptyJSON;
}
Also used : NxtException(org.xel.NxtException) Block(org.xel.Block)

Aggregations

NxtException (org.xel.NxtException)6 JSONObject (org.json.simple.JSONObject)5 JSONStreamAware (org.json.simple.JSONStreamAware)3 IOException (java.io.IOException)2 JSONArray (org.json.simple.JSONArray)2 Work (org.xel.Work)2 Writer (java.io.Writer)1 BigInteger (java.math.BigInteger)1 List (java.util.List)1 ServletException (javax.servlet.ServletException)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 Appendix (org.xel.Appendix)1 Attachment (org.xel.Attachment)1 Block (org.xel.Block)1 Blockchain (org.xel.Blockchain)1 Nxt (org.xel.Nxt)1 TaggedData (org.xel.TaggedData)1 CommandCancelWork (org.xel.computation.CommandCancelWork)1 CommandPowBty (org.xel.computation.CommandPowBty)1 Filter (org.xel.util.Filter)1