org.hyperledger.fabric.sdk.BlockInfo Java Examples

The following examples show how to use org.hyperledger.fabric.sdk.BlockInfo. 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
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public static ListPage<TbTransHash> queryTransList(FabricConfig fabricConfig,
                                                   Channel channel,
                                                   BigInteger blockNumber,
                                                   String blockHash, Integer pageIndex,
                                                   Integer pageSize) throws ProposalException, InvalidArgumentException, BrokerException, DecoderException {
    ListPage<TbTransHash> tbTransHashListPage = new ListPage<>();
    List<TbTransHash> tbTransHashes = new ArrayList<>();

    BlockInfo blockInfo;
    if (!StringUtils.isBlank(blockHash)) {
        blockInfo = channel.queryBlockByHash(Hex.decodeHex(blockHash.toCharArray()));
    } else {
        blockInfo = getBlockInfo(fabricConfig, channel, blockNumber);
    }

    if (blockInfo == null) {
        log.error("query block by blockHash failed, block is empty.");
        throw new BrokerException("query block by blockHash failed, block is empty.");
    }
    generateTbTransHashListPage(pageIndex, pageSize, tbTransHashListPage, tbTransHashes, blockInfo);

    tbTransHashListPage.setPageData(tbTransHashes);
    return tbTransHashListPage;
}
 
Example #2
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public static List<WeEvent> getBlockChainInfo(Channel channel, Long blockNumber) throws ProposalException, InvalidArgumentException, BrokerException {
    List<WeEvent> weEventList = new ArrayList<>();
    BlockInfo returnedBlock = channel.queryBlockByNumber(blockNumber);
    for (BlockInfo.EnvelopeInfo envelopeInfo : returnedBlock.getEnvelopeInfos()) {
        if (envelopeInfo.getType() == TRANSACTION_ENVELOPE) {
            BlockInfo.TransactionEnvelopeInfo transactionEnvelopeInfo = (BlockInfo.TransactionEnvelopeInfo) envelopeInfo;
            for (BlockInfo.TransactionEnvelopeInfo.TransactionActionInfo transactionActionInfo : transactionEnvelopeInfo.getTransactionActionInfos()) {
                log.debug("chaincode input arguments count:{}", transactionActionInfo.getChaincodeInputArgsCount());
                if (transactionActionInfo.getChaincodeInputArgsCount() == WeEventConstants.DEFAULT_CHAINCODE_PARAM_COUNT && "publish".equals(new String(transactionActionInfo.getChaincodeInputArgs(0)))) {
                    WeEvent weEvent = new WeEvent();
                    weEvent.setTopic(new String(transactionActionInfo.getChaincodeInputArgs(1), UTF_8));
                    weEvent.setContent(transactionActionInfo.getChaincodeInputArgs(2));
                    weEvent.setExtensions(JsonHelper.json2Object(new String(transactionActionInfo.getChaincodeInputArgs(3)), new TypeReference<Map<String, String>>() {
                    }));
                    weEvent.setEventId(DataTypeUtils.encodeEventId(weEvent.getTopic(),
                            blockNumber.intValue(),
                            Integer.parseInt(new String(transactionActionInfo.getProposalResponsePayload()))));
                    weEventList.add(weEvent);
                    log.debug("weevent:{}", weEvent);
                }
            }
        }
    }
    return weEventList;
}
 
Example #3
Source File: FabricBlock.java    From spring-fabric-gateway with MIT License 6 votes vote down vote up
public static FabricBlock create(BlockInfo blockInfo) {
	if (blockInfo == null) {
		return null;
	}
	FabricBlock block = new FabricBlock();
	block.setBlockNumber(blockInfo.getBlockNumber());
	try {
		block.setChannel(blockInfo.getChannelId());
	} catch (InvalidProtocolBufferException e) {
		e.printStackTrace();
	}
	block.setDataHash(FabricUtil.hashToString(blockInfo.getDataHash()));
	block.setTransactionCount(blockInfo.getTransactionCount());

	block.setPreviousHash(FabricUtil.hashToString(blockInfo.getPreviousHash()));

	return block;
}
 
Example #4
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public static ListPage<TbNode> queryNodeList(FabricConfig fabricConfig,
                                             Channel channel,
                                             Integer pageIndex,
                                             Integer pageSize) throws ProposalException, InvalidArgumentException {
    ListPage<TbNode> tbNodeListPage = new ListPage<>();
    List<TbNode> tbNodes = new ArrayList<>();
    BlockInfo blockInfo = getBlockInfo(fabricConfig, channel, null);

    Collection<Peer> peers = channel.getPeers();
    peers.forEach(peer -> {
        TbNode tbNode = new TbNode();
        tbNode.setBlockNumber(BigInteger.valueOf(blockInfo.getBlockNumber()));
        tbNode.setNodeId(peer.getUrl());
        tbNode.setNodeActive(1);
        tbNode.setNodeType(WeEventConstants.NODE_TYPE_SEALER);
        tbNodes.add(tbNode);
    });

    tbNodeListPage.setPageIndex(pageIndex);
    tbNodeListPage.setPageSize(pageSize);
    tbNodeListPage.setTotal(peers.size());
    tbNodeListPage.setPageData(tbNodes);
    return tbNodeListPage;
}
 
Example #5
Source File: FabricContext.java    From spring-fabric-gateway with MIT License 5 votes vote down vote up
public FabricQueryResponse<FabricBlock> queryBlockByNumber(long blockNumber) {
	try {
		if (network == null) {
			getContract();
		}
		Channel channel = network.getChannel();

		BlockInfo block = channel.queryBlockByNumber(blockNumber);
		return FabricQueryResponse.success(FabricBlock.create(block));

	} catch (Exception e) {
		return FabricQueryResponse.failure(e.getLocalizedMessage());
	}
}
 
Example #6
Source File: QueryExecutor.java    From fabric-jdbc-connector with Apache License 2.0 5 votes vote down vote up
protected boolean filterField(String fieldName, Object obj, String value, Comparator comparator) {
    boolean retValue = false;
    if (obj instanceof BlockInfo) {
        retValue = filterFieldBlock(fieldName, obj, value, comparator);
    } else if(obj instanceof TransactionObject) {
        retValue = filterFieldTransaction(fieldName, obj, value, comparator);
    } else if(obj instanceof TransactionActionObject) {
        retValue = filterFieldTransactionAction(fieldName, obj, value, comparator);
    } else if(obj instanceof ReadWriteSetObject) {
        retValue = filterFieldReadWriteSet(fieldName, obj, value, comparator);
    }
    return retValue;
}
 
Example #7
Source File: FabricHistory.java    From spring-fabric-gateway with MIT License 5 votes vote down vote up
public void setBlockInfo(BlockInfo blockInfo) {
	if (blockInfo == null) {
		return;
	}
	block = FabricBlock.create(blockInfo);

	block.setCurrentTxId(txId);
	block.setCurrentTxTimestamp(timestamp);
}
 
Example #8
Source File: ChaincodeServiceImpl.java    From balance-transfer-java with Apache License 2.0 5 votes vote down vote up
/**
 * gives blockchain info
 * 
 */
public void blockchainInfo(Org sampleOrg, Channel channel) {

	try {
		checkConfig();

		String channelName = channel.getName();
		Set<Peer> peerSet = sampleOrg.getPeers();
		// Peer queryPeer = peerSet.iterator().next();
		// out("Using peer %s for channel queries", queryPeer.getName());

		BlockchainInfo channelInfo = channel.queryBlockchainInfo();
		logger.info("Channel info for : " + channelName);
		logger.info("Channel height: " + channelInfo.getHeight());

		String chainCurrentHash = Hex.encodeHexString(channelInfo.getCurrentBlockHash());
		String chainPreviousHash = Hex.encodeHexString(channelInfo.getPreviousBlockHash());
		logger.info("Chain current block hash: " + chainCurrentHash);
		logger.info("Chainl previous block hash: " + chainPreviousHash);

		// Query by block number. Should return latest block, i.e. block
		// number 2
		BlockInfo returnedBlock = channel.queryBlockByNumber(channelInfo.getHeight() - 1);
		String previousHash = Hex.encodeHexString(returnedBlock.getPreviousHash());
		logger.info("queryBlockByNumber returned correct block with blockNumber " + returnedBlock.getBlockNumber()
		+ " \n previous_hash " + previousHash);

		// Query by block hash. Using latest block's previous hash so should
		// return block number 1
		byte[] hashQuery = returnedBlock.getPreviousHash();
		returnedBlock = channel.queryBlockByHash(hashQuery);
		logger.info("queryBlockByHash returned block with blockNumber " + returnedBlock.getBlockNumber());

	} catch (Exception e) {
		logger.error("ChaincodeServiceImpl | blockchainInfo | "+ e.getMessage());
	}
}
 
Example #9
Source File: FabricContext.java    From spring-fabric-gateway with MIT License 5 votes vote down vote up
public FabricQueryResponse<FabricBlock> queryBlockByHash(byte[] blockHash) {
	try {
		if (network == null) {
			getContract();
		}
		Channel channel = network.getChannel();

		BlockInfo block = channel.queryBlockByHash(blockHash);

		return FabricQueryResponse.success(FabricBlock.create(block));
	} catch (Exception e) {
		return FabricQueryResponse.failure(e.getLocalizedMessage());
	}
}
 
Example #10
Source File: FabricContext.java    From spring-fabric-gateway with MIT License 5 votes vote down vote up
public FabricQueryResponse<FabricBlock> queryBlockByTransactionID(String txId) {
	try {
		if (network == null) {
			getContract();
		}
		Channel channel = network.getChannel();

		BlockInfo block = channel.queryBlockByTransactionID(txId);
		return FabricQueryResponse.success(FabricBlock.create(block));
	} catch (Exception e) {
		return FabricQueryResponse.failure(e.getLocalizedMessage());
	}
}
 
Example #11
Source File: FabricContext.java    From spring-fabric-gateway with MIT License 5 votes vote down vote up
private BlockInfo queryBlockInfo(String txid) {
	if (txid == null) {
		return null;
	}
	try {
		if (network == null) {
			getContract();
		}
		Channel channel = network.getChannel();
		return channel.queryBlockByTransactionID(txid);
	} catch (Exception e) {
		return null;
	}
}
 
Example #12
Source File: FabricContext.java    From spring-fabric-gateway with MIT License 5 votes vote down vote up
public <T> FabricQueryResponse<List<T>> queryMany(FabricQueryRequest<T> queryRequest) {
	if (queryRequest == null) {
		return FabricQueryResponse.failure("Query request can not be null.");
	}

	Contract contract = null;

	try {
		queryRequest.checkValidate();

		contract = getContract();

		byte[] payloads = contract.evaluateTransaction(queryRequest.function, queryRequest.arguments);
		FabricQueryResponse<List<T>> results = FabricQueryResponse.many(payloads, queryRequest.type);

		if (results.isOk(true) && FabricHistory.class == queryRequest.type) {
			results.data.stream().forEach(t -> {
				String txid = ((FabricHistory) t).getTxId();
				BlockInfo block = queryBlockInfo(txid);
				((FabricHistory) t).setBlockInfo(block);
			});
		}

		return results;
	} catch (Exception e) {
		return FabricQueryResponse.failure(e.getMessage());
	}
}
 
Example #13
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private static BlockInfo getBlockInfo(FabricConfig fabricConfig, Channel channel, BigInteger blockNumber) throws ProposalException, InvalidArgumentException {
    BlockInfo blockInfo;
    if (blockNumber == null) {
        long currentBlockNum = channel.queryBlockchainInfo(new FabricUser(fabricConfig)).getHeight() - 1;
        blockInfo = channel.queryBlockByNumber(currentBlockNum);
    } else {
        blockInfo = channel.queryBlockByNumber(blockNumber.longValue());
    }
    return blockInfo;
}
 
Example #14
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private static List<TbBlock> getTbBlocKList(Channel channel, List<Long> blockNums, BlockchainInfo blockchainInfo) throws ExecutionException, InterruptedException {
    List<CompletableFuture<TbBlock>> futureList = new ArrayList<>();
    blockNums.forEach(blockNumber -> {
        CompletableFuture<TbBlock> future = CompletableFuture.supplyAsync(() -> {
            TbBlock tbBlock = new TbBlock();
            try {
                BlockInfo blockInfo = channel.queryBlockByNumber(blockNumber);
                if (blockNumber != (blockchainInfo.getHeight() - 1)) {
                    BlockInfo nextBlockInfo = channel.queryBlockByNumber(blockNumber + 1);
                    tbBlock.setPkHash(Hex.encodeHexString(nextBlockInfo.getPreviousHash()));
                } else {
                    tbBlock.setPkHash(Hex.encodeHexString(blockchainInfo.getCurrentBlockHash()));
                }
                if (blockInfo.getEnvelopeCount() > 0) {
                    tbBlock.setBlockTimestamp(DataTypeUtils.getTimestamp(blockInfo.getEnvelopeInfo(0).getTimestamp()));
                }
                tbBlock.setBlockNumber(new BigInteger(String.valueOf(blockNumber)));
                tbBlock.setTransCount(blockInfo.getTransactionCount());
            } catch (InvalidArgumentException | ProposalException | InvalidProtocolBufferException e) {
                log.error("query block by blockNumber failed, e:", e);
                return null;
            }

            return tbBlock;
        });

        futureList.add(future);
    });

    return CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0]))
            .thenApply(v -> futureList.stream().map(CompletableFuture::join).collect(Collectors.toList())).get();
}
 
Example #15
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private static void generateTbBlock(Channel channel, BigInteger blockNumber, BlockInfo lastestblockInfo, BlockInfo blockInfo, TbBlock tbBlock) throws InvalidArgumentException, ProposalException, InvalidProtocolBufferException {
    if (blockNumber.longValue() != lastestblockInfo.getBlockNumber()) {
        BlockInfo nextBlockInfo = channel.queryBlockByNumber(blockNumber.longValue() + 1);
        tbBlock.setPkHash(Hex.encodeHexString(nextBlockInfo.getPreviousHash()));
    } else {
        BlockchainInfo blockchainInfo = channel.queryBlockchainInfo();
        tbBlock.setPkHash(Hex.encodeHexString(blockchainInfo.getCurrentBlockHash()));
    }
    if (blockInfo.getEnvelopeCount() > 0) {
        tbBlock.setBlockTimestamp(DataTypeUtils.getTimestamp(blockInfo.getEnvelopeInfo(0).getTimestamp()));
    }
    tbBlock.setTransCount(blockInfo.getEnvelopeCount());
    tbBlock.setBlockNumber(blockNumber);
}
 
Example #16
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private static void generateTbTransHashListPage(Integer pageIndex,
                                                Integer pageSize,
                                                ListPage<TbTransHash> tbTransHashListPage,
                                                List<TbTransHash> tbTransHashes,
                                                BlockInfo blockInfo) throws BrokerException {
    Integer transCount = blockInfo.getTransactionCount();

    if (pageIndex < 1 || (pageIndex - 1) * pageSize > transCount) {
        log.error("pageIndex error.");
        throw new BrokerException("pageIndex error.");
    }
    Integer transSize = (transCount <= pageIndex * pageSize) ? (transCount - ((pageIndex - 1) * pageSize)) : pageSize;
    Integer transIndexStart = (pageIndex - 1) * pageSize;


    Iterable<BlockInfo.EnvelopeInfo> envelopeInfos = blockInfo.getEnvelopeInfos();
    envelopeInfos.forEach(envelopeInfo -> {
        TbTransHash tbTransHash = new TbTransHash();
        tbTransHash.setCreateTime(DataTypeUtils.getTimestamp(envelopeInfo.getTimestamp()));
        tbTransHash.setBlockTimestamp(DataTypeUtils.getTimestamp(envelopeInfo.getTimestamp()));
        tbTransHash.setTransHash(envelopeInfo.getTransactionID());
        tbTransHash.setBlockNumber(BigInteger.valueOf(blockInfo.getBlockNumber()));
        tbTransHashes.add(tbTransHash);
    });

    if (tbTransHashes != null && !tbTransHashes.isEmpty()) {
        tbTransHashes.subList(transIndexStart, transSize + transIndexStart);
    }

    tbTransHashListPage.setPageSize(transSize);
    tbTransHashListPage.setTotal(transCount);
    tbTransHashListPage.setPageData(tbTransHashes);
}
 
Example #17
Source File: UpdateChannelIT.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
private Channel reconstructChannel(final boolean isSystemChannel, String name, HFClient client, SampleOrg sampleOrg) throws Exception {

        client.setUserContext(isSystemChannel ? ordererAdmin : sampleOrg.getPeerAdmin());
        Channel newChannel = client.newChannel(name);

        for (String orderName : sampleOrg.getOrdererNames()) {
            newChannel.addOrderer(client.newOrderer(orderName, sampleOrg.getOrdererLocation(orderName),
                    testConfig.getOrdererProperties(orderName)));
        }

        if (isSystemChannel) { // done
            newChannel.initialize();
            return newChannel;

        }

        assertTrue(sampleOrg.getPeerNames().size() > 1); // need at least two for testing.

        int i = 0;
        for (String peerName : sampleOrg.getPeerNames()) {
            String peerLocation = sampleOrg.getPeerLocation(peerName);
            Peer peer = client.newPeer(peerName, peerLocation, testConfig.getPeerProperties(peerName));

            //Query the actual peer for which channels it belongs to and check it belongs to this channel
            Set<String> channels = client.queryChannels(peer);
            if (!channels.contains(name)) {
                throw new AssertionError(format("Peer %s does not appear to belong to channel %s", peerName, name));
            }
            Channel.PeerOptions peerOptions = createPeerOptions().setPeerRoles(EnumSet.of(Peer.PeerRole.CHAINCODE_QUERY,
                    Peer.PeerRole.ENDORSING_PEER, Peer.PeerRole.LEDGER_QUERY, Peer.PeerRole.EVENT_SOURCE));

            if (i % 2 == 0) {
                peerOptions.registerEventsForFilteredBlocks(); // we need a mix of each type for testing.
            } else {
                peerOptions.registerEventsForBlocks();
            }
            ++i;

            newChannel.addPeer(peer, peerOptions);
        }

        //For testing of blocks which are not transactions.
        newChannel.registerBlockListener(blockEvent -> {
            eventQueueCaputure.add(blockEvent); // used with the other queued to make sure same.
            // Note peer eventing will always start with sending the last block so this will get the last endorser block
            int transactions = 0;
            int nonTransactions = 0;
            for (BlockInfo.EnvelopeInfo envelopeInfo : blockEvent.getEnvelopeInfos()) {

                if (BlockInfo.EnvelopeType.TRANSACTION_ENVELOPE == envelopeInfo.getType()) {
                    ++transactions;
                } else {
                    assertEquals(BlockInfo.EnvelopeType.ENVELOPE, envelopeInfo.getType());
                    ++nonTransactions;
                }

            }
            assertTrue(format("nontransactions %d, transactions %d", nonTransactions, transactions), nonTransactions < 2); // non transaction blocks only have one envelope
            assertTrue(format("nontransactions %d, transactions %d", nonTransactions, transactions), nonTransactions + transactions > 0); // has to be one.
            assertFalse(format("nontransactions %d, transactions %d", nonTransactions, transactions), nonTransactions > 0 && transactions > 0); // can't have both.

            if (nonTransactions > 0) { // this is an update block -- don't care about others here.

                if (blockEvent.isFiltered()) {
                    ++eventCountFilteredBlock; // make sure we're seeing non transaction events.
                } else {
                    ++eventCountBlock;
                }
                assertEquals(0, blockEvent.getTransactionCount());
                assertEquals(1, blockEvent.getEnvelopeCount());
                for (TransactionEvent transactionEvent : blockEvent.getTransactionEvents()) {
                    fail("Got transaction event in a block update"); // only events for update should not have transactions.
                }
            }
        });

        // Register Queued block listeners just for testing use both ways.
        // Ideally an application would have it's own independent thread to monitor and take off elements as fast as they can.
        // This would wait forever however if event could not be put in the queue like if the capacity is at a maximum. For LinkedBlockingQueue so unlikely
        listenerHandler1 = newChannel.registerBlockListener(blockingQueue1);
        assertNotNull(listenerHandler1);
        // This is the same but put a timeout on it.  If its not queued in time like if the queue is full it would generate a log warning and ignore the event.
        listenerHandler2 = newChannel.registerBlockListener(blockingQueue2, 1L, TimeUnit.SECONDS);
        assertNotNull(listenerHandler2);

        newChannel.initialize();

        return newChannel;
    }
 
Example #18
Source File: QueryExecutor.java    From fabric-jdbc-connector with Apache License 2.0 4 votes vote down vote up
private boolean filterFieldBlock(String fieldName, Object obj, String value, Comparator comparator) {
    BlockInfo blockInfo = (BlockInfo) obj;
    boolean retValue;
    switch (fieldName) {
        case FabricColumns.BLOCK_DATA_HASH:
            if (!comparator.isEQ() && !comparator.isNEQ()) {
                throw new BlkchnException(String.format(
                        "String values in %s field can only be compared for equivalence and non-equivalence", fieldName));
            }
            if(comparator.isEQ()) {
                retValue = Hex.encodeHexString(blockInfo.getDataHash()).equals(value.replaceAll("'", ""));
            } else {
                retValue = !Hex.encodeHexString(blockInfo.getDataHash()).equals(value.replaceAll("'", ""));
            }
            break;

        case FabricColumns.TRANS_ACTIONS_META_DATA:
            if (!comparator.isEQ() && !comparator.isNEQ()) {
                throw new BlkchnException(String.format(
                        "String values in %s field can only be compared for equivalence and non-equivalence", fieldName));
            }
            if(comparator.isEQ()) {
                retValue = Hex.encodeHexString(blockInfo.getTransActionsMetaData()).equals(value.replaceAll("'", ""));
            } else {
                retValue = !Hex.encodeHexString(blockInfo.getTransActionsMetaData()).equals(value.replaceAll("'", ""));
            }
            break;

        case FabricColumns.TRANSACTION_COUNT:
            Number transactionCount = blockInfo.getEnvelopeCount();
            retValue = compareNumbers(transactionCount, Integer.parseInt(value), comparator);
            break;

        case FabricColumns.CHANNEL_ID:
            try {
                if (!comparator.isEQ() && !comparator.isNEQ()) {
                    throw new BlkchnException(String.format(
                            "String values in %s field can only be compared for equivalence and non-equivalence", fieldName));
                }
                if(comparator.isEQ()) {
                    retValue = blockInfo.getChannelId().equals(value.replaceAll("'", ""));
                } else {
                    retValue = !blockInfo.getChannelId().equals(value.replaceAll("'", ""));
                }
            } catch (InvalidProtocolBufferException e) {
                throw new BlkchnException("Error fetching channel id", e);
            }
            break;
            
        case FabricColumns.PREVIOUS_HASH:
            if (!comparator.isEQ() && !comparator.isNEQ()) {
                throw new BlkchnException(String.format(
                        "String values in %s field can only be compared for equivalence and non-equivalence", fieldName));
            }
            if(comparator.isEQ()) {
                retValue = Hex.encodeHexString(blockInfo.getPreviousHash()).equals(value.replaceAll("'", ""));
            } else {
                retValue = !Hex.encodeHexString(blockInfo.getPreviousHash()).equals(value.replaceAll("'", ""));
            }
            break;

        default:
            retValue = false;
    }
    return retValue;
}
 
Example #19
Source File: QueryExecutor.java    From fabric-jdbc-connector with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T extends Number & Comparable<T>> TreeNode combineRangeAndDataNodes(RangeNode<T> rangeNode,
        DataNode<?> dataNode, LogicalOperation oper) {
    String tableName = dataNode.getTable();
    List<String> keys = dataNode.getKeys().stream().map(x -> x.toString()).collect(Collectors.toList());
    String rangeCol = rangeNode.getColumn();
    RangeOperations<T> rangeOps = (RangeOperations<T>) physicalPlan.getRangeOperations(tableName, rangeCol);
    if (FabricTables.BLOCK.equals(tableName)) {
        if (FabricColumns.BLOCK_NO.equals(rangeCol)) {
            List<RangeNode<T>> dataRanges = keys.stream().map(key -> {
                BlockInfo blockInfo = (BlockInfo) dataMap.get(key);
                if (auxillaryDataMap.containsKey(FabricColumns.BLOCK_NO)) {
                    auxillaryDataMap.get(FabricColumns.BLOCK_NO).put(key, blockInfo);
                } else {
                    auxillaryDataMap.put(FabricColumns.BLOCK_NO, new HashMap<>());
                    auxillaryDataMap.get(FabricColumns.BLOCK_NO).put(key, blockInfo);
                }
                T blockNo = (T) new Long(blockInfo.getBlockNumber());
                RangeNode<T> node = new RangeNode<>(rangeNode.getTable(), rangeCol);
                node.getRangeList().addRange(new Range<T>(blockNo, blockNo));
                return node;
            }).collect(Collectors.toList());
            if(dataRanges.isEmpty()) {
                if(oper.isOr()) {
                    return rangeNode;
                }
                else {
                    //return empty data;
                    return new DataNode<T>(dataNode.getTable(),new ArrayList<>());
                }
            }
            RangeNode<T> dataRangeNodes = dataRanges.get(0);
            if (dataRanges.size() > 1) {
                for (int i = 1; i < dataRanges.size(); i++) {
                    dataRangeNodes = rangeOps.rangeNodeOr(dataRangeNodes, dataRanges.get(i));
                }
            }
            if (oper.isAnd()) {
                return rangeOps.rangeNodeAnd(dataRangeNodes, rangeNode);
            } else {
                return rangeOps.rangeNodeOr(dataRangeNodes, rangeNode);
            }
        }
    } else if(FabricColumns.BLOCK_NO.equals(rangeCol)) {
        if(oper.isOr()) {
            LogicalOperation newOper = new LogicalOperation(Operator.OR);
            newOper.addChildNode(dataNode);
            newOper.addChildNode(rangeNode);
            return newOper;
        } else {
            return filterRangeNodeWithValue(rangeNode, dataNode);
        }
    }
    RangeNode<T> emptyRangeNode = new RangeNode<>(rangeNode.getTable(), rangeNode.getColumn());
    emptyRangeNode.getRangeList().addRange(new Range<T>(rangeOps.getMinValue(), rangeOps.getMinValue()));
    return emptyRangeNode;
}
 
Example #20
Source File: ChaincodeManager.java    From fabric-net-server with Apache License 2.0 4 votes vote down vote up
private void execBlockInfo(BlockInfo blockInfo) throws InvalidArgumentException, IOException {
	final long blockNumber = blockInfo.getBlockNumber();
	log.debug("blockNumber = " + blockNumber);
	log.debug("data hash: " + Hex.encodeHexString(blockInfo.getDataHash()));
	log.debug("previous hash id: " + Hex.encodeHexString(blockInfo.getPreviousHash()));
	log.debug("calculated block hash is " + Hex.encodeHexString(SDKUtils.calculateBlockHash(blockNumber, blockInfo.getPreviousHash(), blockInfo.getDataHash())));
	
	final int envelopeCount = blockInfo.getEnvelopeCount();
	log.debug("block number " + blockNumber + " has " + envelopeCount + " envelope count:");
	
	for(EnvelopeInfo info: blockInfo.getEnvelopeInfos()) {
		final String channelId = info.getChannelId();
		log.debug("ChannelId = " + channelId);
		log.debug("Epoch = " + info.getEpoch());
		log.debug("TransactionID = " + info.getTransactionID());
		log.debug("ValidationCode = " + info.getValidationCode());
		log.debug("Timestamp = " + DateUtil.obtain().parseDateFormat(new Date(info.getTimestamp().getTime()), "yyyy年MM月dd日 HH时mm分ss秒"));
		log.debug("Type = " + info.getType());
		
		if (info.getType() == EnvelopeType.TRANSACTION_ENVELOPE) {
			BlockInfo.TransactionEnvelopeInfo txeInfo = (TransactionEnvelopeInfo) info;
			int txCount = txeInfo.getTransactionActionInfoCount();
			log.debug("Transaction number " + blockNumber + " has actions count = " + txCount);
			log.debug("Transaction number " + blockNumber + " isValid = " + txeInfo.isValid());
			log.debug("Transaction number " + blockNumber + " validation code = " + txeInfo.getValidationCode());
			
			for (int i = 0; i < txCount; i++) {
				BlockInfo.TransactionEnvelopeInfo.TransactionActionInfo txInfo = txeInfo.getTransactionActionInfo(i);
				log.debug("Transaction action " + i + " has response status " + txInfo.getResponseStatus());
                   log.debug("Transaction action " + i + " has response message bytes as string: " + printableString(new String(txInfo.getResponseMessageBytes(), "UTF-8")));
				log.debug("Transaction action " + i + " has endorsements " + txInfo.getEndorsementsCount());
				
				for (int n = 0; n < txInfo.getEndorsementsCount(); ++n) {
                       BlockInfo.EndorserInfo endorserInfo = txInfo.getEndorsementInfo(n);
                       log.debug("Endorser " + n + " signature: " + Hex.encodeHexString(endorserInfo.getSignature()));
                       log.debug("Endorser " + n + " endorser: " + new String(endorserInfo.getEndorser(), "UTF-8"));
                   }
				
                   log.debug("Transaction action " + i + " has " + txInfo.getChaincodeInputArgsCount() + " chaincode input arguments");
                   for (int z = 0; z < txInfo.getChaincodeInputArgsCount(); ++z) {
                       log.debug("Transaction action " + i + " has chaincode input argument " + z + "is: " + printableString(new String(txInfo.getChaincodeInputArgs(z), "UTF-8")));
                   }

                   log.debug("Transaction action " + i + " proposal response status: " + txInfo.getProposalResponseStatus());
                   log.debug("Transaction action " + i + " proposal response payload: " + printableString(new String(txInfo.getProposalResponsePayload())));

                   TxReadWriteSetInfo rwsetInfo = txInfo.getTxReadWriteSet();
                   if (null != rwsetInfo) {
                       log.debug("Transaction action " + i + " has " + rwsetInfo.getNsRwsetCount() +" name space read write sets");

                       for (TxReadWriteSetInfo.NsRwsetInfo nsRwsetInfo : rwsetInfo.getNsRwsetInfos()) {
                       	final String namespace = nsRwsetInfo.getNamespace();
                           KvRwset.KVRWSet rws = nsRwsetInfo.getRwset();

                           int rs = -1;
                           for (KvRwset.KVRead readList : rws.getReadsList()) {
                               rs++;

                               log.debug("Namespace " + namespace + " read set " + rs + " key " + readList.getKey() + " version [" + readList.getVersion().getBlockNum() + " : " + readList.getVersion().getTxNum() + "]");
                           }

                           rs = -1;
                           for (KvRwset.KVWrite writeList : rws.getWritesList()) {
                               rs++;
                               String valAsString = printableString(new String(writeList.getValue().toByteArray(), "UTF-8"));
                               log.debug("Namespace " + namespace + " write set " + rs + " key " + writeList.getKey() + " has value " + valAsString);
                           }
                       }
                   }
			}
		}
	}
}
 
Example #21
Source File: ChaincodeManager.java    From fabric-net-server with Apache License 2.0 4 votes vote down vote up
public Map<String, String> queryBlockByNumber(long blockNumber) throws InvalidArgumentException, ProposalException, IOException {
	BlockInfo blockInfo = channel.queryBlockByNumber(blockNumber);
	execBlockInfo(blockInfo);
	return null;
}
 
Example #22
Source File: ChaincodeManager.java    From fabric-net-server with Apache License 2.0 4 votes vote down vote up
public Map<String, String> queryBlockByHash(byte[] blockHash) throws InvalidArgumentException, ProposalException, IOException {
	BlockInfo blockInfo = channel.queryBlockByHash(blockHash);
	execBlockInfo(blockInfo);
	return null;
}
 
Example #23
Source File: ChaincodeManager.java    From fabric-net-server with Apache License 2.0 4 votes vote down vote up
public Map<String, String> queryBlockByTransactionID(String txID) throws InvalidArgumentException, ProposalException, CertificateException, IOException {
	BlockInfo blockInfo = channel.queryBlockByTransactionID(txID);
	execBlockInfo(blockInfo);
	return null;
}
 
Example #24
Source File: FabricContext.java    From spring-fabric-gateway with MIT License 4 votes vote down vote up
public FabricQueryResponse<FabricTransaction> queryTransactionInfo(String txId) {
	try {
		if (network == null) {
			getContract();
		}
		Channel channel = network.getChannel();

		BlockInfo block = channel.queryBlockByTransactionID(txId);

		if (block == null) {
			return FabricQueryResponse.failure("Unable to query block from txId=" + txId);
		}
		TransactionEnvelopeInfo envelopeInfo = null;
		Iterator<EnvelopeInfo> iterator = block.getEnvelopeInfos().iterator();
		while (iterator.hasNext()) {
			BlockInfo.EnvelopeInfo info = iterator.next();
			if (info.getTransactionID().equals(txId) && info instanceof TransactionEnvelopeInfo) {
				envelopeInfo = (TransactionEnvelopeInfo) info;
				break;
			}
		}
		FabricTransaction tx = new FabricTransaction();
		tx.setTxId(txId);
		tx.setChannel(envelopeInfo.getChannelId());
		IdentitiesInfo creator = envelopeInfo.getCreator();
		if (creator != null) {
			String mspid = creator.getMspid();
			tx.setCreator(mspid);
		}
		tx.setDate(envelopeInfo.getTimestamp());
		EnvelopeType type = envelopeInfo.getType();
		if (type != null) {
			tx.setType(type.name());
		}
		tx.setValidationCode(envelopeInfo.getValidationCode());

		TransactionInfo transaction = channel.queryTransactionByID(txId);
		TxValidationCode validationCode = transaction.getValidationCode();
		if (validationCode != null) {
			tx.setValidationCode(validationCode.getNumber());
		}
		return FabricQueryResponse.success(tx);
	} catch (Exception e) {
		return FabricQueryResponse.failure(e.getLocalizedMessage());
	}
}
 
Example #25
Source File: FabricContext.java    From spring-fabric-gateway with MIT License 4 votes vote down vote up
public FabricQueryResponse<List<FabricTransaction>> queryTransactions(long blockNumber) {
	try {
		if (network == null) {
			getContract();
		}
		Channel channel = network.getChannel();

		BlockInfo block = channel.queryBlockByNumber(blockNumber);
		List<FabricTransaction> transactions = new ArrayList<>();
		if (block != null) {
			int envelopeCount = block.getEnvelopeCount();
			for (int i = 0; i < envelopeCount; i++) {
				EnvelopeInfo envelope = block.getEnvelopeInfo(i);
				String txId = envelope.getTransactionID();
				FabricTransaction tx = new FabricTransaction();
				tx.setIndex(i);
				tx.setTxId(txId);
				tx.setChannel(envelope.getChannelId());
				IdentitiesInfo creator = envelope.getCreator();
				if (creator != null) {
					tx.setCreator(creator.getMspid());
				}
				tx.setDate(envelope.getTimestamp());
				EnvelopeType type = envelope.getType();
				if (type != null) {
					tx.setType(type.name());
				}
				tx.setValidationCode(envelope.getValidationCode());

				TransactionInfo transaction = channel.queryTransactionByID(txId);
				TxValidationCode validationCode = transaction.getValidationCode();
				if (validationCode != null) {
					tx.setValidationCode(validationCode.getNumber());
				}

				transactions.add(tx);
			}
		}
		return FabricQueryResponse.success(transactions);

	} catch (Exception e) {
		return FabricQueryResponse.failure(e.getLocalizedMessage());
	}
}
 
Example #26
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 4 votes vote down vote up
public static ListPage<TbBlock> queryBlockList(FabricConfig fabricConfig,
                                               Channel channel,
                                               BigInteger blockNumber,
                                               String blockHash,
                                               Integer pageIndex,
                                               Integer pageSize) throws ProposalException, InvalidArgumentException, ExecutionException, InterruptedException, DecoderException, InvalidProtocolBufferException {
    ListPage<TbBlock> tbBlockListPage = new ListPage<>();
    List<TbBlock> tbBlocks = new CopyOnWriteArrayList<>();
    int blockTotalCount;

    BlockInfo lastestblockInfo = getBlockInfo(fabricConfig, channel, null);
    BlockInfo blockInfo;

    TbBlock tbBlock = new TbBlock();
    if (!StringUtils.isBlank(blockHash)) {
        blockInfo = channel.queryBlockByHash(Hex.decodeHex(blockHash.toCharArray()));
        generateTbBlock(channel, BigInteger.valueOf(blockInfo.getBlockNumber()), lastestblockInfo, blockInfo, tbBlock);
        tbBlocks.add(tbBlock);
        blockTotalCount = 1;
    } else if (blockNumber != null) {
        blockInfo = getBlockInfo(fabricConfig, channel, blockNumber);
        generateTbBlock(channel, blockNumber, lastestblockInfo, blockInfo, tbBlock);
        tbBlocks.add(tbBlock);
        blockTotalCount = 1;
    } else {
        BlockchainInfo blockchainInfo = channel.queryBlockchainInfo();
        blockInfo = getBlockInfo(fabricConfig, channel, null);
        long lastestblcokNum = blockInfo.getBlockNumber();

        int blockSize = ((int) lastestblcokNum <= pageIndex * pageSize) ? ((int) lastestblcokNum - ((pageIndex - 1) * pageSize)) : pageSize;
        long blockNumberIndex = (long) pageSize * (pageIndex - 1) + 1;

        List<Long> blockNums = new ArrayList<>();
        for (int i = 0; i < blockSize; i++) {
            blockNums.add(blockNumberIndex);
            blockNumberIndex++;
        }

        tbBlocks = getTbBlocKList(channel, blockNums, blockchainInfo);
        blockTotalCount = Integer.parseInt(String.valueOf(lastestblockInfo.getBlockNumber()));
        tbBlocks.sort((arg0, arg1) -> arg1.getBlockNumber().compareTo(arg0.getBlockNumber()));
    }

    tbBlockListPage.setPageSize(pageSize);
    tbBlockListPage.setPageIndex(pageIndex);
    tbBlockListPage.setTotal(blockTotalCount);
    tbBlockListPage.setPageData(tbBlocks);
    return tbBlockListPage;
}