Search in sources :

Example 6 with JSONRPC2SessionException

use of com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException in project starcoin-java by starcoinorg.

the class JsonRPCClient method getObject.

/**
 * 获取单个对象的接口
 *
 * @param session
 * @param method    rpc接口的方法名
 * @param params    rpc接口的参数列表
 * @param requestId 请求id
 * @param clazz     返回对象的封装类
 * @return
 * @throws JSONRPC2SessionException
 */
protected T getObject(JSONRPC2Session session, String method, List<Object> params, int requestId, Class<T> clazz) throws JSONRPC2SessionException {
    JSONRPC2Request request = new JSONRPC2Request(method, params, requestId);
    JSONRPC2Response response = session.send(request);
    if (response.indicatesSuccess()) {
        Object result = response.getResult();
        if (result != null) {
            return JSON.parseObject(result.toString(), clazz);
        }
    }
    return null;
}
Also used : JSONRPC2Response(com.thetransactioncompany.jsonrpc2.JSONRPC2Response) JSONObject(com.alibaba.fastjson.JSONObject) JSONRPC2Request(com.thetransactioncompany.jsonrpc2.JSONRPC2Request)

Example 7 with JSONRPC2SessionException

use of com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException in project starcoin-java by starcoinorg.

the class TokenContractRPCClient method getTokenMarketCap.

/**
 * 获取某个 token 的市场容量
 */
public BigInteger getTokenMarketCap(String tokenTypeTag) throws JSONRPC2SessionException {
    ContractCall call = new ContractCall();
    call.setFunctionId(TokenMarketCapTypeTag);
    List<String> typeTags = new ArrayList<>();
    typeTags.add(tokenTypeTag);
    call.setTypeArgs(typeTags);
    call.setArgs(new ArrayList<>());
    List result = this.call(call);
    if (result != null && result.size() > 0) {
        String capInString = String.valueOf(result.get(0));
        return new BigInteger(capInString);
    } else {
        throw new JSONRPC2SessionException("fetch token" + tokenTypeTag + " market cap failed");
    }
}
Also used : JSONRPC2SessionException(com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException) ArrayList(java.util.ArrayList) BigInteger(java.math.BigInteger) List(java.util.List) ArrayList(java.util.ArrayList) ContractCall(org.starcoin.bean.ContractCall)

Example 8 with JSONRPC2SessionException

use of com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException in project starcoin-java by starcoinorg.

the class ContractRPCClientTestCase method testCall.

public void testCall() {
    try {
        ContractCall call = new ContractCall();
        call.setFunctionId("0x00000000000000000000000000000001::Token::market_cap");
        List<java.lang.String> typeTags = new ArrayList<>();
        typeTags.add("0x00000000000000000000000000000001::STC::STC");
        call.setTypeArgs(typeTags);
        call.setArgs(new ArrayList<>());
        List result = client.call(call);
        System.out.println(result);
        if (result.size() > 0) {
            long cap = (Long) result.get(0);
            System.out.println(cap);
        }
    } catch (JSONRPC2SessionException e) {
        e.printStackTrace();
    }
}
Also used : JSONRPC2SessionException(com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) ContractCall(org.starcoin.bean.ContractCall)

Example 9 with JSONRPC2SessionException

use of com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException in project starcoin-search by starcoinorg.

the class ElasticSearchHandler method bulk.

public void bulk(List<Block> blockList) {
    if (blockList.isEmpty()) {
        logger.warn("block list is empty");
        return;
    }
    BulkRequest bulkRequest = new BulkRequest();
    long minTimestamp = Long.MAX_VALUE;
    for (Block block : blockList) {
        // transform difficulty
        BlockHeader header = block.getHeader();
        transferDifficulty(header);
        block.setHeader(header);
        // add block ids
        bulkRequest.add(buildBlockRequest(block, blockIdsIndex));
        // add block content
        IndexRequest blockContent = new IndexRequest(blockContentIndex);
        blockContent.id(block.getHeader().getBlockHash()).source(JSON.toJSONString(block), XContentType.JSON);
        bulkRequest.add(blockContent);
        Set<AddressHolder> holderAddress = new HashSet<>();
        // add transactions
        for (Transaction transaction : block.getTransactionList()) {
            IndexRequest transactionReq = new IndexRequest(transactionIndex);
            transactionReq.id(transaction.getTransactionHash()).source(JSON.toJSONString(transaction), XContentType.JSON);
            bulkRequest.add(transactionReq);
            // delete pending txn
            DeleteRequest deleteRequest = new DeleteRequest(pendingTxnIndex);
            deleteRequest.id(transaction.getTransactionHash());
            bulkRequest.add(deleteRequest);
            // add events
            List<Event> events = transaction.getEvents();
            if (events != null && events.size() > 0) {
                for (Event event : events) {
                    bulkRequest.add(buildEventRequest(event, header.getAuthor(), transaction.getTimestamp(), eventIndex, holderAddress));
                }
            }
            // add transfer
            List<IndexRequest> transferRequests = buildTransferRequest(transaction, transferIndex);
            if (!transferRequests.isEmpty()) {
                for (IndexRequest request : transferRequests) {
                    bulkRequest.add(request);
                }
            }
            if (minTimestamp > transaction.getTimestamp()) {
                minTimestamp = transaction.getTimestamp();
            }
        }
        // add holder
        if (!holderAddress.isEmpty()) {
            for (AddressHolder holder : holderAddress) {
                updateAddressHolder(bulkRequest, holder);
            }
        }
        // add uncles
        for (BlockHeader uncle : block.getUncles()) {
            bulkRequest.add(buildUncleRequest(uncle, header.getHeight(), uncleBlockIndex));
        }
    }
    try {
        BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        logger.info("bulk block result: {}", response.buildFailureMessage());
    } catch (IOException e) {
        logger.error("bulk block error:", e);
    }
    // flush token list
    if (!tokenCodeList.isEmpty()) {
        for (TokenCode token : tokenCodeList) {
            try {
                String codeStr = token.address + "::" + token.module + "::" + token.name;
                TokenInfo tokenInfo = stateRPCClient.getTokenInfo(token.address.toString(), codeStr);
                addTokenInfo(tokenInfo, codeStr);
                // add to cache
                tokenCache.put(codeStr, tokenInfo);
            } catch (JSONRPC2SessionException e) {
                logger.error("flush token error:", e);
            }
        }
        tokenCodeList.clear();
    }
}
Also used : JSONRPC2SessionException(com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) IOException(java.io.IOException) IndexRequest(org.elasticsearch.action.index.IndexRequest) SwapTransaction(org.starcoin.bean.SwapTransaction) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) DepositEvent(org.starcoin.types.event.DepositEvent) WithdrawEvent(org.starcoin.types.event.WithdrawEvent) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest) TokenCode(org.starcoin.types.TokenCode)

Example 10 with JSONRPC2SessionException

use of com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException in project starcoin-search by starcoinorg.

the class IndexerHandle method executeInternal.

@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) {
    // read current offset
    if (localBlockOffset == null || currentHandleHeader == null) {
        // logger.warn("local offset error, reset it: {}, {}", localOffset, currentHandleHeader);
        initOffset();
    }
    BlockOffset remoteBlockOffset = elasticSearchHandler.getRemoteOffset();
    logger.info("current remote offset: {}", remoteBlockOffset);
    if (remoteBlockOffset == null) {
        logger.warn("offset must not null, please check blocks.mapping!!");
        return;
    }
    if (remoteBlockOffset.getBlockHeight() > localBlockOffset.getBlockHeight()) {
        logger.info("indexer equalize chain blocks.");
        return;
    }
    // read head
    try {
        BlockHeader chainHeader = blockRPCClient.getChainHeader();
        // calculate bulk size
        long headHeight = chainHeader.getHeight();
        long bulkNumber = Math.min(headHeight - localBlockOffset.getBlockHeight(), bulkSize);
        int index = 1;
        List<Block> blockList = new ArrayList<>();
        while (index <= bulkNumber) {
            long readNumber = localBlockOffset.getBlockHeight() + index;
            Block block = blockRPCClient.getBlockByHeight(readNumber);
            if (!block.getHeader().getParentHash().equals(currentHandleHeader.getBlockHash())) {
                // fork handle until reach forked point block
                logger.warn("Fork detected, roll back: {}, {}, {}", readNumber, block.getHeader().getParentHash(), currentHandleHeader.getBlockHash());
                Block lastForkBlock, lastMasterBlock;
                BlockHeader forkHeader = currentHandleHeader;
                long lastMasterNumber = readNumber - 1;
                String forkHeaderParentHash = null;
                do {
                    // 获取分叉的block
                    if (forkHeaderParentHash == null) {
                        // 第一次先回滚当前最高的分叉块
                        forkHeaderParentHash = forkHeader.getBlockHash();
                    } else {
                        forkHeaderParentHash = forkHeader.getParentHash();
                    }
                    lastForkBlock = elasticSearchHandler.getBlockContent(forkHeaderParentHash);
                    if (lastForkBlock == null) {
                        logger.warn("get fork block null: {}", forkHeaderParentHash);
                        // read from node
                        lastForkBlock = blockRPCClient.getBlockByHash(forkHeaderParentHash);
                    }
                    if (lastForkBlock != null) {
                        elasticSearchHandler.bulkForkedUpdate(lastForkBlock);
                        logger.info("rollback forked block ok: {}, {}", lastForkBlock.getHeader().getHeight(), forkHeaderParentHash);
                    } else {
                        // 如果块取不到,先退出当前任务,下一个轮询周期再执行
                        logger.warn("get forked block is null: {}", forkHeaderParentHash);
                        return;
                    }
                    // 获取上一个高度主块
                    lastMasterBlock = blockRPCClient.getBlockByHeight(lastMasterNumber);
                    if (lastMasterBlock != null) {
                        long forkNumber = forkHeader.getHeight();
                        logger.info("fork number: {}", forkNumber);
                        forkHeader = lastForkBlock.getHeader();
                        // reset offset to handled fork block
                        currentHandleHeader = forkHeader;
                        localBlockOffset.setBlockHeight(currentHandleHeader.getHeight());
                        localBlockOffset.setBlockHash(currentHandleHeader.getBlockHash());
                        elasticSearchHandler.setRemoteOffset(localBlockOffset);
                        if (lastMasterNumber == forkNumber && lastMasterBlock.getHeader().getBlockHash().equals(forkHeaderParentHash)) {
                            // find fork point
                            logger.info("find fork height: {}", lastMasterNumber);
                            break;
                        }
                        // 继续找下一个分叉
                        lastMasterNumber--;
                        logger.info("continue last forked block: {}", lastMasterNumber);
                    } else {
                        logger.warn("get last master Block null: {}", lastMasterNumber);
                    }
                } while (true);
                logger.info("rollback handle ok: {}", localBlockOffset);
                // 退出当前任务,重新添加从分叉点之后的block
                return;
            }
            // set event
            ServiceUtils.addBlockToList(transactionRPCClient, blockList, block);
            // update current header
            currentHandleHeader = block.getHeader();
            index++;
            logger.debug("add block: {}", block.getHeader());
        }
        // bulk execute
        elasticSearchHandler.bulk(blockList);
        // update offset
        localBlockOffset.setBlockHeight(currentHandleHeader.getHeight());
        localBlockOffset.setBlockHash(currentHandleHeader.getBlockHash());
        elasticSearchHandler.setRemoteOffset(localBlockOffset);
        logger.info("indexer update success: {}", localBlockOffset);
    } catch (JSONRPC2SessionException e) {
        logger.error("chain header error:", e);
    }
}
Also used : JSONRPC2SessionException(com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException) ArrayList(java.util.ArrayList) BlockOffset(org.starcoin.bean.BlockOffset) Block(org.starcoin.bean.Block) BlockHeader(org.starcoin.bean.BlockHeader)

Aggregations

JSONRPC2SessionException (com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException)18 ArrayList (java.util.ArrayList)10 JSONRPC2Request (com.thetransactioncompany.jsonrpc2.JSONRPC2Request)7 Block (org.starcoin.bean.Block)5 ContractCall (org.starcoin.bean.ContractCall)5 JSONObject (com.alibaba.fastjson.JSONObject)4 JSONRPC2Response (com.thetransactioncompany.jsonrpc2.JSONRPC2Response)4 List (java.util.List)4 JSONRPC2Session (com.thetransactioncompany.jsonrpc2.client.JSONRPC2Session)3 IOException (java.io.IOException)2 BigInteger (java.math.BigInteger)2 MalformedURLException (java.net.MalformedURLException)2 URL (java.net.URL)2 HashMap (java.util.HashMap)2 BlockHeader (org.starcoin.bean.BlockHeader)2 BlockOffset (org.starcoin.bean.BlockOffset)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 DeserializationError (com.novi.serde.DeserializationError)1 BigDecimal (java.math.BigDecimal)1 ConnectException (java.net.ConnectException)1