org.hyperledger.fabric.sdk.SDKUtils Java Examples

The following examples show how to use org.hyperledger.fabric.sdk.SDKUtils. 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: QueryBlockTest.java    From fabric-jdbc-connector with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testInstallChainCode() throws ClassNotFoundException, SQLException, InvalidArgumentException{

    PowerMockito.mockStatic(SDKUtils.class);

    PowerMockito.mockStatic(HFClient.class);
    when(HFClient.createNewInstance()).thenReturn(mockClient);

    Channel mockChannel = mock(Channel.class);
    when(mockClient.newChannel(anyString())).thenReturn(mockChannel);

    InstallProposalRequest mockInstallProposalRequest = mock(InstallProposalRequest.class);
    when(mockClient.newInstallProposalRequest()).thenReturn(mockInstallProposalRequest);


    String configPath = "src/test/resources/blockchain-query";
    Class.forName("com.impetus.fabric.jdbc.FabricDriver");
    QueryBlock qb = new QueryBlock(configPath,"mychannel", null, null);
 qb.setChannel();
    String chaincodeName ="chncodefunc";
    String version = "1.0";
    String chaincodePath = "hyperledger/fabric/examples/chaincode/go/chaincode_example02";


    when(SDKUtils.getProposalConsistencySets(anyCollection())).thenReturn(new ArrayList<>());
    String result = qb.installChaincode(chaincodeName, version, qb.getConf().getConfigPath(), chaincodePath);
    assert(result.equals("Chaincode installed successfully"));

}
 
Example #2
Source File: ChaincodeManager.java    From fabric-net-server with Apache License 2.0 4 votes vote down vote up
/**
	 * 执行智能合约
	 * 
	 * @param fcn
	 *            方法名
	 * @param args
	 *            参数数组
	 * @return
	 * @throws InvalidArgumentException
	 * @throws ProposalException
	 * @throws InterruptedException
	 * @throws ExecutionException
	 * @throws TimeoutException
	 * @throws IOException 
	 * @throws TransactionException 
	 * @throws CryptoException 
	 * @throws InvalidKeySpecException 
	 * @throws NoSuchProviderException 
	 * @throws NoSuchAlgorithmException 
	 */
	public Map<String, String> invoke(String fcn, String[] args)
			throws InvalidArgumentException, ProposalException, InterruptedException, ExecutionException, TimeoutException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, CryptoException, TransactionException, IOException {
		Map<String, String> resultMap = new HashMap<>();

		Collection<ProposalResponse> successful = new LinkedList<>();
		Collection<ProposalResponse> failed = new LinkedList<>();

		/// Send transaction proposal to all peers
		TransactionProposalRequest transactionProposalRequest = client.newTransactionProposalRequest();
		transactionProposalRequest.setChaincodeID(chaincodeID);
		transactionProposalRequest.setFcn(fcn);
		transactionProposalRequest.setArgs(args);

		Map<String, byte[]> tm2 = new HashMap<>();
		tm2.put("HyperLedgerFabric", "TransactionProposalRequest:JavaSDK".getBytes(UTF_8));
		tm2.put("method", "TransactionProposalRequest".getBytes(UTF_8));
		tm2.put("result", ":)".getBytes(UTF_8));
		transactionProposalRequest.setTransientMap(tm2);

		long currentStart = System.currentTimeMillis();
		Collection<ProposalResponse> transactionPropResp = channel.sendTransactionProposal(transactionProposalRequest, channel.getPeers());
		for (ProposalResponse response : transactionPropResp) {
			if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
				successful.add(response);
			} else {
				failed.add(response);
			}
		}
		log.info("channel send transaction proposal time = " + ( System.currentTimeMillis() - currentStart));

		Collection<Set<ProposalResponse>> proposalConsistencySets = SDKUtils.getProposalConsistencySets(transactionPropResp);
		if (proposalConsistencySets.size() != 1) {
			log.error("Expected only one set of consistent proposal responses but got " + proposalConsistencySets.size());
		}

		if (failed.size() > 0) {
			ProposalResponse firstTransactionProposalResponse = failed.iterator().next();
			log.error("Not enough endorsers for inspect:" + failed.size() + " endorser error: " + firstTransactionProposalResponse.getMessage() + ". Was verified: "
					+ firstTransactionProposalResponse.isVerified());
			resultMap.put("code", "error");
			resultMap.put("data", firstTransactionProposalResponse.getMessage());
			return resultMap;
		} else {
			log.info("Successfully received transaction proposal responses.");
			ProposalResponse resp = transactionPropResp.iterator().next();
			log.debug("TransactionID: " + resp.getTransactionID());
			byte[] x = resp.getChaincodeActionResponsePayload();
			String resultAsString = null;
			if (x != null) {
				resultAsString = new String(x, "UTF-8");
			}
			log.info("resultAsString = " + resultAsString);
			channel.sendTransaction(successful);
			resultMap.put("code", "success");
			resultMap.put("data", resultAsString);
			resultMap.put("txid", resp.getTransactionID());
			return resultMap;
		}

//		channel.sendTransaction(successful).thenApply(transactionEvent -> {
//			if (transactionEvent.isValid()) {
//				log.info("Successfully send transaction proposal to orderer. Transaction ID: " + transactionEvent.getTransactionID());
//			} else {
//				log.info("Failed to send transaction proposal to orderer");
//			}
//			// chain.shutdown(true);
//			return transactionEvent.getTransactionID();
//		}).get(chaincode.getInvokeWatiTime(), TimeUnit.SECONDS);
	}
 
Example #3
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 #4
Source File: QueryBlockTest.java    From fabric-jdbc-connector with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testInvokeChaincode() throws ClassNotFoundException, SQLException, InvalidArgumentException, ProposalException{

    PowerMockito.mockStatic(HFClient.class);
    when(HFClient.createNewInstance()).thenReturn(mockClient);

    Channel mockChannel = mock(Channel.class);
    when(mockClient.newChannel(anyString())).thenReturn(mockChannel);
    when(mockClient.newPeer(anyString(), anyString(), any())).thenCallRealMethod();


    InstantiateProposalRequest mockInstantiateProposalRequest = mock(InstantiateProposalRequest.class);
    when(mockClient.newInstantiationProposalRequest()).thenReturn(mockInstantiateProposalRequest);

    TransactionProposalRequest mockTransactionProposalRequest = mock(TransactionProposalRequest.class);
    when(mockClient.newTransactionProposalRequest()).thenReturn(mockTransactionProposalRequest);

    Collection<ProposalResponse> mockProposalResponsesList = new ArrayList<ProposalResponse>();
    ProposalResponse mockProposalResponses = mock(ProposalResponse.class);
    when(mockProposalResponses.getStatus()).thenReturn(ProposalResponse.Status.SUCCESS);
    Peer mkpeer = mock(Peer.class);
    when(mockProposalResponses.getPeer()).thenReturn(mkpeer);
    mockProposalResponsesList.add(mockProposalResponses);
    mockProposalResponsesList.add(mockProposalResponses);

    when(mockChannel.sendTransactionProposal(any(TransactionProposalRequest.class),anyCollectionOf(Peer.class))).thenReturn(mockProposalResponsesList);


    PowerMockito.mockStatic(SDKUtils.class);

    String configPath = "src/test/resources/blockchain-query";
    Class.forName("com.impetus.fabric.jdbc.FabricDriver");
    QueryBlock qb = new QueryBlock(configPath,"mychannel", null, null);
    qb.setChannel();
    String chaincodeName ="chncodefunc";

    when(SDKUtils.getProposalConsistencySets(anyCollection())).thenReturn(new ArrayList<>());

    CompletableFuture<BlockEvent.TransactionEvent> mockCompletableFutureTEvent = new CompletableFuture<BlockEvent.TransactionEvent>();//{mockTranEvent};
    when(mockChannel.sendTransaction(any(ArrayList.class))).thenReturn(mockCompletableFutureTEvent);// .thenReturn(mockCompletableFutureTEvent);

    try {
        qb.invokeChaincode(chaincodeName, "testFunction", new String[]{"a", "b", "5", "10"});

    }catch(BlkchnException blkEx){
        //Do Nothing for Java concurrent Error
        if(!(blkEx.getMessage().contains("java.util.concurrent.TimeoutException"))) {
            assert(false);
        }
    }
    assert(true);

}
 
Example #5
Source File: QueryBlockTest.java    From fabric-jdbc-connector with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testInvokeNoPeerInfo() throws ClassNotFoundException, SQLException, InvalidArgumentException, ProposalException {
    PowerMockito.mockStatic(HFClient.class);
    when(HFClient.createNewInstance()).thenReturn(mockClient);

    Channel mockChannel = mock(Channel.class);
    when(mockClient.newChannel(anyString())).thenReturn(mockChannel);
    when(mockClient.newPeer(anyString(), anyString(), any())).thenCallRealMethod();


    InstantiateProposalRequest mockInstantiateProposalRequest = mock(InstantiateProposalRequest.class);
    when(mockClient.newInstantiationProposalRequest()).thenReturn(mockInstantiateProposalRequest);

    TransactionProposalRequest mockTransactionProposalRequest = mock(TransactionProposalRequest.class);
    when(mockClient.newTransactionProposalRequest()).thenReturn(mockTransactionProposalRequest);

    Collection<ProposalResponse> mockProposalResponsesList = new ArrayList<ProposalResponse>();
    ProposalResponse mockProposalResponses = mock(ProposalResponse.class);
    when(mockProposalResponses.getStatus()).thenReturn(ProposalResponse.Status.SUCCESS);
    Peer mkpeer = mock(Peer.class);
    when(mockProposalResponses.getPeer()).thenReturn(mkpeer);
    mockProposalResponsesList.add(mockProposalResponses);
    mockProposalResponsesList.add(mockProposalResponses);

    when(mockChannel.sendTransactionProposal(any(TransactionProposalRequest.class),anyCollectionOf(Peer.class))).thenReturn(mockProposalResponsesList);


    PowerMockito.mockStatic(SDKUtils.class);

    String configPath = "src/test/resources/blockchain-query";
    Class.forName("com.impetus.fabric.jdbc.FabricDriver");
    QueryBlock qb = new QueryBlock(configPath,"mychannel", null, null);
    qb.setChannel();
    String chaincodeName ="chncodefuncNoPeerInfo";

    when(SDKUtils.getProposalConsistencySets(anyCollection())).thenReturn(new ArrayList<>());

    CompletableFuture<BlockEvent.TransactionEvent> mockCompletableFutureTEvent = new CompletableFuture<BlockEvent.TransactionEvent>();//{mockTranEvent};
    when(mockChannel.sendTransaction(any(ArrayList.class))).thenReturn(mockCompletableFutureTEvent);// .thenReturn(mockCompletableFutureTEvent);

    DataFrame df = qb.invokeChaincode(chaincodeName, "testFunction", new String[]{"a", "b", "5", "10"});
    assertEquals(df.getData().size(), 1);
    List<Object> row = df.getData().get(0);
    assertEquals(false, Boolean.parseBoolean(row.get(1).toString()));
    assertEquals("Endorsing peer information not provided for chaincode chncodefuncNoPeerInfo", row.get(3).toString());
}
 
Example #6
Source File: ChaincodeServiceImpl.java    From balance-transfer-java with Apache License 2.0 4 votes vote down vote up
/**
 * installs the chaincode takes as input chaincode name returns status as
 * string
 */
public String installChaincode(String chaincodeName) {

	try {
		checkConfig();

		chaincodeID = getChaincodeId(chaincodeName);
		Org sampleOrg = Conf.getSampleOrg("peerOrg1");
		Channel channel = reconstructChannel();
		final String channelName = channel.getName();
		boolean isFooChain = channelName.equals(channelName);
		logger.info("Running channel %s", channelName);
		Collection<Peer> channelPeers = channel.getPeers();
		Collection<Orderer> orderers = channel.getOrderers();

		client.setUserContext(sampleOrg.getPeerAdmin());
		logger.info("Creating install proposal");
		InstallProposalRequest installProposalRequest = client.newInstallProposalRequest();
		installProposalRequest.setChaincodeID(chaincodeID);
		installProposalRequest.setChaincodeSourceLocation(new File(PATH + "/artifacts/"));
		installProposalRequest.setChaincodeVersion(chainCodeVersion);
		logger.info("Sending install proposal");
		int numInstallProposal = 0;

		Set<Peer> peersFromOrg = sampleOrg.getPeers();
		numInstallProposal = numInstallProposal + peersFromOrg.size();
		responses = client.sendInstallProposal(installProposalRequest, peersFromOrg);
		for (ProposalResponse response : responses) {
			if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
				out("Successful install proposal response Txid: %s from peer %s", response.getTransactionID(),
						response.getPeer().getName());
				successful.add(response);
			} else {
				failed.add(response);
			}
		}
		SDKUtils.getProposalConsistencySets(responses);
		// }
		logger.info("Received %d install proposal responses. Successful+verified: %d . Failed: %d",
				numInstallProposal, successful.size(), failed.size());

		if (failed.size() > 0) {
			ProposalResponse first = failed.iterator().next();
			fail("Not enough endorsers for install :" + successful.size() + ".  " + first.getMessage());
			return "Not enough endorsers for install :" + successful.size() + ".  " + first.getMessage();
		}

		return "Chaincode installed successfully";

	} catch (Exception e) {
		logger.error("ChaincodeServiceImpl | installChaincode | " +e.getMessage());
		return "Chaincode installation failed";
	}

}