Search in sources :

Example 1 with ChaincodeID

use of org.hyperledger.fabric.sdk.ChaincodeID in project fabric-sdk-java by hyperledger.

the class End2endIT method runChannel.

// CHECKSTYLE.OFF: Method length is 320 lines (max allowed is 150).
void runChannel(HFClient client, Channel channel, boolean installChaincode, SampleOrg sampleOrg, int delta) {
    class ChaincodeEventCapture {

        final String handle;

        final BlockEvent blockEvent;

        final ChaincodeEvent chaincodeEvent;

        ChaincodeEventCapture(String handle, BlockEvent blockEvent, ChaincodeEvent chaincodeEvent) {
            this.handle = handle;
            this.blockEvent = blockEvent;
            this.chaincodeEvent = chaincodeEvent;
        }
    }
    // Test list to capture chaincode events.
    Vector<ChaincodeEventCapture> chaincodeEvents = new Vector<>();
    try {
        final String channelName = channel.getName();
        boolean isFooChain = FOO_CHANNEL_NAME.equals(channelName);
        out("Running channel %s", channelName);
        Collection<Orderer> orderers = channel.getOrderers();
        final ChaincodeID chaincodeID;
        Collection<ProposalResponse> responses;
        Collection<ProposalResponse> successful = new LinkedList<>();
        Collection<ProposalResponse> failed = new LinkedList<>();
        // Register a chaincode event listener that will trigger for any chaincode id and only for EXPECTED_EVENT_NAME event.
        String chaincodeEventListenerHandle = channel.registerChaincodeEventListener(Pattern.compile(".*"), Pattern.compile(Pattern.quote(EXPECTED_EVENT_NAME)), (handle, blockEvent, chaincodeEvent) -> {
            chaincodeEvents.add(new ChaincodeEventCapture(handle, blockEvent, chaincodeEvent));
            String es = blockEvent.getPeer() != null ? blockEvent.getPeer().getName() : blockEvent.getEventHub().getName();
            out("RECEIVED Chaincode event with handle: %s, chaincode Id: %s, chaincode event name: %s, " + "transaction id: %s, event payload: \"%s\", from eventhub: %s", handle, chaincodeEvent.getChaincodeId(), chaincodeEvent.getEventName(), chaincodeEvent.getTxId(), new String(chaincodeEvent.getPayload()), es);
        });
        // For non foo channel unregister event listener to test events are not called.
        if (!isFooChain) {
            channel.unregisterChaincodeEventListener(chaincodeEventListenerHandle);
            chaincodeEventListenerHandle = null;
        }
        ChaincodeID.Builder chaincodeIDBuilder = ChaincodeID.newBuilder().setName(CHAIN_CODE_NAME).setVersion(CHAIN_CODE_VERSION);
        if (null != CHAIN_CODE_PATH) {
            chaincodeIDBuilder.setPath(CHAIN_CODE_PATH);
        }
        chaincodeID = chaincodeIDBuilder.build();
        if (installChaincode) {
            // //////////////////////////
            // Install Proposal Request
            // 
            client.setUserContext(sampleOrg.getPeerAdmin());
            out("Creating install proposal");
            InstallProposalRequest installProposalRequest = client.newInstallProposalRequest();
            installProposalRequest.setChaincodeID(chaincodeID);
            if (isFooChain) {
                // on foo chain install from directory.
                // //For GO language and serving just a single user, chaincodeSource is mostly likely the users GOPATH
                installProposalRequest.setChaincodeSourceLocation(Paths.get(TEST_FIXTURES_PATH, CHAIN_CODE_FILEPATH).toFile());
            } else {
                if (CHAIN_CODE_LANG.equals(Type.GO_LANG)) {
                    installProposalRequest.setChaincodeInputStream(Util.generateTarGzInputStream((Paths.get(TEST_FIXTURES_PATH, CHAIN_CODE_FILEPATH, "src", CHAIN_CODE_PATH).toFile()), Paths.get("src", CHAIN_CODE_PATH).toString()));
                } else {
                    installProposalRequest.setChaincodeInputStream(Util.generateTarGzInputStream((Paths.get(TEST_FIXTURES_PATH, CHAIN_CODE_FILEPATH).toFile()), "src"));
                }
            }
            installProposalRequest.setChaincodeVersion(CHAIN_CODE_VERSION);
            installProposalRequest.setChaincodeLanguage(CHAIN_CODE_LANG);
            out("Sending install proposal");
            // //////////////////////////
            // only a client from the same org as the peer can issue an install request
            int numInstallProposal = 0;
            // Set<String> orgs = orgPeers.keySet();
            // for (SampleOrg org : testSampleOrgs) {
            Collection<Peer> peers = channel.getPeers();
            numInstallProposal = numInstallProposal + peers.size();
            responses = client.sendInstallProposal(installProposalRequest, peers);
            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);
                }
            }
            // }
            out("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());
            }
        }
        // client.setUserContext(sampleOrg.getUser(TEST_ADMIN_NAME));
        // final ChaincodeID chaincodeID = firstInstallProposalResponse.getChaincodeID();
        // Note installing chaincode does not require transaction no need to
        // send to Orderers
        // /////////////
        // // Instantiate chaincode.
        InstantiateProposalRequest instantiateProposalRequest = client.newInstantiationProposalRequest();
        instantiateProposalRequest.setProposalWaitTime(testConfig.getProposalWaitTime());
        instantiateProposalRequest.setChaincodeID(chaincodeID);
        instantiateProposalRequest.setChaincodeLanguage(CHAIN_CODE_LANG);
        instantiateProposalRequest.setFcn("init");
        instantiateProposalRequest.setArgs(new String[] { "a", "500", "b", "" + (200 + delta) });
        Map<String, byte[]> tm = new HashMap<>();
        tm.put("HyperLedgerFabric", "InstantiateProposalRequest:JavaSDK".getBytes(UTF_8));
        tm.put("method", "InstantiateProposalRequest".getBytes(UTF_8));
        instantiateProposalRequest.setTransientMap(tm);
        /*
              policy OR(Org1MSP.member, Org2MSP.member) meaning 1 signature from someone in either Org1 or Org2
              See README.md Chaincode endorsement policies section for more details.
            */
        ChaincodeEndorsementPolicy chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy();
        chaincodeEndorsementPolicy.fromYamlFile(new File(TEST_FIXTURES_PATH + "/sdkintegration/chaincodeendorsementpolicy.yaml"));
        instantiateProposalRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);
        out("Sending instantiateProposalRequest to all peers with arguments: a and b set to 100 and %s respectively", "" + (200 + delta));
        successful.clear();
        failed.clear();
        if (isFooChain) {
            // Send responses both ways with specifying peers and by using those on the channel.
            responses = channel.sendInstantiationProposal(instantiateProposalRequest, channel.getPeers());
        } else {
            responses = channel.sendInstantiationProposal(instantiateProposalRequest);
        }
        for (ProposalResponse response : responses) {
            if (response.isVerified() && response.getStatus() == ProposalResponse.Status.SUCCESS) {
                successful.add(response);
                out("Succesful instantiate proposal response Txid: %s from peer %s", response.getTransactionID(), response.getPeer().getName());
            } else {
                failed.add(response);
            }
        }
        out("Received %d instantiate proposal responses. Successful+verified: %d . Failed: %d", responses.size(), successful.size(), failed.size());
        if (failed.size() > 0) {
            for (ProposalResponse fail : failed) {
                out("Not enough endorsers for instantiate :" + successful.size() + "endorser failed with " + fail.getMessage() + ", on peer" + fail.getPeer());
            }
            ProposalResponse first = failed.iterator().next();
            fail("Not enough endorsers for instantiate :" + successful.size() + "endorser failed with " + first.getMessage() + ". Was verified:" + first.isVerified());
        }
        // /////////////
        // / Send instantiate transaction to orderer
        out("Sending instantiateTransaction to orderer with a and b set to 100 and %s respectively", "" + (200 + delta));
        // Specify what events should complete the interest in this transaction. This is the default
        // for all to complete. It's possible to specify many different combinations like
        // any from a group, all from one group and just one from another or even None(NOfEvents.createNoEvents).
        // See. Channel.NOfEvents
        Channel.NOfEvents nOfEvents = createNofEvents();
        if (!channel.getPeers(EnumSet.of(PeerRole.EVENT_SOURCE)).isEmpty()) {
            nOfEvents.addPeers(channel.getPeers(EnumSet.of(PeerRole.EVENT_SOURCE)));
        }
        if (!channel.getEventHubs().isEmpty()) {
            nOfEvents.addEventHubs(channel.getEventHubs());
        }
        channel.sendTransaction(successful, // Basically the default options but shows it's usage.
        createTransactionOptions().userContext(// could be a different user context. this is the default.
        client.getUserContext()).shuffleOrders(// don't shuffle any orderers the default is true.
        false).orderers(// specify the orderers we want to try this transaction. Fails once all Orderers are tried.
        channel.getOrderers()).nOfEvents(// The events to signal the completion of the interest in the transaction
        nOfEvents)).thenApply(transactionEvent -> {
            waitOnFabric(0);
            // must be valid to be here.
            assertTrue(transactionEvent.isValid());
            // musth have a signature.
            assertNotNull(transactionEvent.getSignature());
            // This is the blockevent that has this transaction.
            BlockEvent blockEvent = transactionEvent.getBlockEvent();
            // Make sure the RAW Fabric block is returned.
            assertNotNull(blockEvent.getBlock());
            out("Finished instantiate transaction with transaction id %s", transactionEvent.getTransactionID());
            try {
                assertEquals(blockEvent.getChannelId(), channel.getName());
                successful.clear();
                failed.clear();
                client.setUserContext(sampleOrg.getUser(TESTUSER_1_NAME));
                // /////////////
                // / Send transaction proposal to all peers
                TransactionProposalRequest transactionProposalRequest = client.newTransactionProposalRequest();
                transactionProposalRequest.setChaincodeID(chaincodeID);
                transactionProposalRequest.setChaincodeLanguage(CHAIN_CODE_LANG);
                // transactionProposalRequest.setFcn("invoke");
                transactionProposalRequest.setFcn("move");
                transactionProposalRequest.setProposalWaitTime(testConfig.getProposalWaitTime());
                transactionProposalRequest.setArgs("a", "b", "100");
                Map<String, byte[]> tm2 = new HashMap<>();
                // Just some extra junk in transient map
                tm2.put("HyperLedgerFabric", "TransactionProposalRequest:JavaSDK".getBytes(UTF_8));
                // ditto
                tm2.put("method", "TransactionProposalRequest".getBytes(UTF_8));
                // This should be returned see chaincode why.
                tm2.put("result", ":)".getBytes(UTF_8));
                // This should trigger an event see chaincode why.
                tm2.put(EXPECTED_EVENT_NAME, EXPECTED_EVENT_DATA);
                transactionProposalRequest.setTransientMap(tm2);
                out("sending transactionProposal to all peers with arguments: move(a,b,100)");
                Collection<ProposalResponse> transactionPropResp = channel.sendTransactionProposal(transactionProposalRequest, channel.getPeers());
                for (ProposalResponse response : transactionPropResp) {
                    if (response.getStatus() == ProposalResponse.Status.SUCCESS) {
                        out("Successful transaction proposal response Txid: %s from peer %s", response.getTransactionID(), response.getPeer().getName());
                        successful.add(response);
                    } else {
                        failed.add(response);
                    }
                }
                // Check that all the proposals are consistent with each other. We should have only one set
                // where all the proposals above are consistent. Note the when sending to Orderer this is done automatically.
                // Shown here as an example that applications can invoke and select.
                // See org.hyperledger.fabric.sdk.proposal.consistency_validation config property.
                Collection<Set<ProposalResponse>> proposalConsistencySets = SDKUtils.getProposalConsistencySets(transactionPropResp);
                if (proposalConsistencySets.size() != 1) {
                    fail(format("Expected only one set of consistent proposal responses but got %d", proposalConsistencySets.size()));
                }
                out("Received %d transaction proposal responses. Successful+verified: %d . Failed: %d", transactionPropResp.size(), successful.size(), failed.size());
                if (failed.size() > 0) {
                    ProposalResponse firstTransactionProposalResponse = failed.iterator().next();
                    fail("Not enough endorsers for invoke(move a,b,100):" + failed.size() + " endorser error: " + firstTransactionProposalResponse.getMessage() + ". Was verified: " + firstTransactionProposalResponse.isVerified());
                }
                out("Successfully received transaction proposal responses.");
                ProposalResponse resp = successful.iterator().next();
                // This is the data returned by the chaincode.
                byte[] x = resp.getChaincodeActionResponsePayload();
                String resultAsString = null;
                if (x != null) {
                    resultAsString = new String(x, "UTF-8");
                }
                assertEquals(":)", resultAsString);
                // Chaincode's status.
                assertEquals(200, resp.getChaincodeActionResponseStatus());
                TxReadWriteSetInfo readWriteSetInfo = resp.getChaincodeActionResponseReadWriteSetInfo();
                // See blockwalker below how to transverse this
                assertNotNull(readWriteSetInfo);
                assertTrue(readWriteSetInfo.getNsRwsetCount() > 0);
                ChaincodeID cid = resp.getChaincodeID();
                assertNotNull(cid);
                final String path = cid.getPath();
                if (null == CHAIN_CODE_PATH) {
                    assertTrue(path == null || "".equals(path));
                } else {
                    assertEquals(CHAIN_CODE_PATH, path);
                }
                assertEquals(CHAIN_CODE_NAME, cid.getName());
                assertEquals(CHAIN_CODE_VERSION, cid.getVersion());
                // //////////////////////////
                // Send Transaction Transaction to orderer
                out("Sending chaincode transaction(move a,b,100) to orderer.");
                return channel.sendTransaction(successful).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS);
            } catch (Exception e) {
                out("Caught an exception while invoking chaincode");
                e.printStackTrace();
                fail("Failed invoking chaincode with error : " + e.getMessage());
            }
            return null;
        }).thenApply(transactionEvent -> {
            try {
                waitOnFabric(0);
                // must be valid to be here.
                assertTrue(transactionEvent.isValid());
                out("Finished transaction with transaction id %s", transactionEvent.getTransactionID());
                // used in the channel queries later
                testTxID = transactionEvent.getTransactionID();
                // //////////////////////////
                // Send Query Proposal to all peers
                // 
                String expect = "" + (300 + delta);
                out("Now query chaincode for the value of b.");
                QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
                queryByChaincodeRequest.setArgs(new String[] { "b" });
                queryByChaincodeRequest.setFcn("query");
                queryByChaincodeRequest.setChaincodeID(chaincodeID);
                Map<String, byte[]> tm2 = new HashMap<>();
                tm2.put("HyperLedgerFabric", "QueryByChaincodeRequest:JavaSDK".getBytes(UTF_8));
                tm2.put("method", "QueryByChaincodeRequest".getBytes(UTF_8));
                queryByChaincodeRequest.setTransientMap(tm2);
                Collection<ProposalResponse> queryProposals = channel.queryByChaincode(queryByChaincodeRequest, channel.getPeers());
                for (ProposalResponse proposalResponse : queryProposals) {
                    if (!proposalResponse.isVerified() || proposalResponse.getStatus() != ProposalResponse.Status.SUCCESS) {
                        fail("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() + ". Messages: " + proposalResponse.getMessage() + ". Was verified : " + proposalResponse.isVerified());
                    } else {
                        String payload = proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();
                        out("Query payload of b from peer %s returned %s", proposalResponse.getPeer().getName(), payload);
                        assertEquals(payload, expect);
                    }
                }
                return null;
            } catch (Exception e) {
                out("Caught exception while running query");
                e.printStackTrace();
                fail("Failed during chaincode query with error : " + e.getMessage());
            }
            return null;
        }).exceptionally(e -> {
            if (e instanceof TransactionEventException) {
                BlockEvent.TransactionEvent te = ((TransactionEventException) e).getTransactionEvent();
                if (te != null) {
                    throw new AssertionError(format("Transaction with txid %s failed. %s", te.getTransactionID(), e.getMessage()), e);
                }
            }
            throw new AssertionError(format("Test failed with %s exception %s", e.getClass().getName(), e.getMessage()), e);
        }).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS);
        // Channel queries
        // We can only send channel queries to peers that are in the same org as the SDK user context
        // Get the peers from the current org being used and pick one randomly to send the queries to.
        // Set<Peer> peerSet = sampleOrg.getPeers();
        // Peer queryPeer = peerSet.iterator().next();
        // out("Using peer %s for channel queries", queryPeer.getName());
        BlockchainInfo channelInfo = channel.queryBlockchainInfo();
        out("Channel info for : " + channelName);
        out("Channel height: " + channelInfo.getHeight());
        String chainCurrentHash = Hex.encodeHexString(channelInfo.getCurrentBlockHash());
        String chainPreviousHash = Hex.encodeHexString(channelInfo.getPreviousBlockHash());
        out("Chain current block hash: " + chainCurrentHash);
        out("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());
        out("queryBlockByNumber returned correct block with blockNumber " + returnedBlock.getBlockNumber() + " \n previous_hash " + previousHash);
        assertEquals(channelInfo.getHeight() - 1, returnedBlock.getBlockNumber());
        assertEquals(chainPreviousHash, 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);
        out("queryBlockByHash returned block with blockNumber " + returnedBlock.getBlockNumber());
        assertEquals(channelInfo.getHeight() - 2, returnedBlock.getBlockNumber());
        // Query block by TxID. Since it's the last TxID, should be block 2
        returnedBlock = channel.queryBlockByTransactionID(testTxID);
        out("queryBlockByTxID returned block with blockNumber " + returnedBlock.getBlockNumber());
        assertEquals(channelInfo.getHeight() - 1, returnedBlock.getBlockNumber());
        // query transaction by ID
        TransactionInfo txInfo = channel.queryTransactionByID(testTxID);
        out("QueryTransactionByID returned TransactionInfo: txID " + txInfo.getTransactionID() + "\n     validation code " + txInfo.getValidationCode().getNumber());
        if (chaincodeEventListenerHandle != null) {
            channel.unregisterChaincodeEventListener(chaincodeEventListenerHandle);
            // Should be two. One event in chaincode and two notification for each of the two event hubs
            final int numberEventsExpected = channel.getEventHubs().size() + channel.getPeers(EnumSet.of(PeerRole.EVENT_SOURCE)).size();
            // just make sure we get the notifications.
            for (int i = 15; i > 0; --i) {
                if (chaincodeEvents.size() == numberEventsExpected) {
                    break;
                } else {
                    // wait for the events.
                    Thread.sleep(90);
                }
            }
            assertEquals(numberEventsExpected, chaincodeEvents.size());
            for (ChaincodeEventCapture chaincodeEventCapture : chaincodeEvents) {
                assertEquals(chaincodeEventListenerHandle, chaincodeEventCapture.handle);
                assertEquals(testTxID, chaincodeEventCapture.chaincodeEvent.getTxId());
                assertEquals(EXPECTED_EVENT_NAME, chaincodeEventCapture.chaincodeEvent.getEventName());
                assertTrue(Arrays.equals(EXPECTED_EVENT_DATA, chaincodeEventCapture.chaincodeEvent.getPayload()));
                assertEquals(CHAIN_CODE_NAME, chaincodeEventCapture.chaincodeEvent.getChaincodeId());
                BlockEvent blockEvent = chaincodeEventCapture.blockEvent;
                assertEquals(channelName, blockEvent.getChannelId());
            // assertTrue(channel.getEventHubs().contains(blockEvent.getEventHub()));
            }
        } else {
            assertTrue(chaincodeEvents.isEmpty());
        }
        out("Running for Channel %s done", channelName);
    } catch (Exception e) {
        out("Caught an exception running channel %s", channel.getName());
        e.printStackTrace();
        fail("Test failed with error : " + e.getMessage());
    }
}
Also used : Arrays(java.util.Arrays) InvalidProtocolBufferRuntimeException(org.hyperledger.fabric.sdk.exception.InvalidProtocolBufferRuntimeException) InstantiateProposalRequest(org.hyperledger.fabric.sdk.InstantiateProposalRequest) TxReadWriteSetInfo(org.hyperledger.fabric.sdk.TxReadWriteSetInfo) Vector(java.util.Vector) BlockInfo(org.hyperledger.fabric.sdk.BlockInfo) Type(org.hyperledger.fabric.sdk.TransactionRequest.Type) Map(java.util.Map) TestConfigHelper(org.hyperledger.fabric.sdk.TestConfigHelper) Assert.fail(org.junit.Assert.fail) EnumSet(java.util.EnumSet) ChannelConfiguration(org.hyperledger.fabric.sdk.ChannelConfiguration) Orderer(org.hyperledger.fabric.sdk.Orderer) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) TestConfig(org.hyperledger.fabric.sdk.testutils.TestConfig) Collection(java.util.Collection) ProposalException(org.hyperledger.fabric.sdk.exception.ProposalException) Channel(org.hyperledger.fabric.sdk.Channel) Set(java.util.Set) String.format(java.lang.String.format) EnrollmentRequest(org.hyperledger.fabric_ca.sdk.EnrollmentRequest) PrivateKey(java.security.PrivateKey) Enrollment(org.hyperledger.fabric.sdk.Enrollment) Peer(org.hyperledger.fabric.sdk.Peer) Assert.assertFalse(org.junit.Assert.assertFalse) Pattern(java.util.regex.Pattern) ChaincodeEvent(org.hyperledger.fabric.sdk.ChaincodeEvent) ChaincodeID(org.hyperledger.fabric.sdk.ChaincodeID) EventHub(org.hyperledger.fabric.sdk.EventHub) HFClient(org.hyperledger.fabric.sdk.HFClient) PeerRole(org.hyperledger.fabric.sdk.Peer.PeerRole) NOfEvents.createNofEvents(org.hyperledger.fabric.sdk.Channel.NOfEvents.createNofEvents) HashMap(java.util.HashMap) Hex(org.apache.commons.codec.binary.Hex) QueryByChaincodeRequest(org.hyperledger.fabric.sdk.QueryByChaincodeRequest) TransactionOptions.createTransactionOptions(org.hyperledger.fabric.sdk.Channel.TransactionOptions.createTransactionOptions) TransactionEventException(org.hyperledger.fabric.sdk.exception.TransactionEventException) BlockchainInfo(org.hyperledger.fabric.sdk.BlockchainInfo) BlockEvent(org.hyperledger.fabric.sdk.BlockEvent) LinkedList(java.util.LinkedList) SDKUtils(org.hyperledger.fabric.sdk.SDKUtils) HFCAClient(org.hyperledger.fabric_ca.sdk.HFCAClient) Before(org.junit.Before) InstallProposalRequest(org.hyperledger.fabric.sdk.InstallProposalRequest) HFCAInfo(org.hyperledger.fabric_ca.sdk.HFCAInfo) Properties(java.util.Properties) ChaincodeEndorsementPolicy(org.hyperledger.fabric.sdk.ChaincodeEndorsementPolicy) ProposalResponse(org.hyperledger.fabric.sdk.ProposalResponse) MalformedURLException(java.net.MalformedURLException) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Assert.assertNotNull(org.junit.Assert.assertNotNull) StringWriter(java.io.StringWriter) TransactionInfo(org.hyperledger.fabric.sdk.TransactionInfo) RegistrationRequest(org.hyperledger.fabric_ca.sdk.RegistrationRequest) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) PeerOptions.createPeerOptions(org.hyperledger.fabric.sdk.Channel.PeerOptions.createPeerOptions) File(java.io.File) KvRwset(org.hyperledger.fabric.protos.ledger.rwset.kvrwset.KvRwset) TimeUnit(java.util.concurrent.TimeUnit) CryptoSuite(org.hyperledger.fabric.sdk.security.CryptoSuite) Assert.assertNull(org.junit.Assert.assertNull) PEMWriter(org.bouncycastle.openssl.PEMWriter) Paths(java.nio.file.Paths) TestUtils.resetConfig(org.hyperledger.fabric.sdk.testutils.TestUtils.resetConfig) TRANSACTION_ENVELOPE(org.hyperledger.fabric.sdk.BlockInfo.EnvelopeType.TRANSACTION_ENVELOPE) Assert.assertEquals(org.junit.Assert.assertEquals) TransactionProposalRequest(org.hyperledger.fabric.sdk.TransactionProposalRequest) HashMap(java.util.HashMap) ChaincodeID(org.hyperledger.fabric.sdk.ChaincodeID) InstantiateProposalRequest(org.hyperledger.fabric.sdk.InstantiateProposalRequest) BlockInfo(org.hyperledger.fabric.sdk.BlockInfo) TransactionInfo(org.hyperledger.fabric.sdk.TransactionInfo) Vector(java.util.Vector) Orderer(org.hyperledger.fabric.sdk.Orderer) ChaincodeEndorsementPolicy(org.hyperledger.fabric.sdk.ChaincodeEndorsementPolicy) TransactionEventException(org.hyperledger.fabric.sdk.exception.TransactionEventException) Peer(org.hyperledger.fabric.sdk.Peer) Channel(org.hyperledger.fabric.sdk.Channel) BlockchainInfo(org.hyperledger.fabric.sdk.BlockchainInfo) LinkedList(java.util.LinkedList) InvalidProtocolBufferRuntimeException(org.hyperledger.fabric.sdk.exception.InvalidProtocolBufferRuntimeException) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) ProposalException(org.hyperledger.fabric.sdk.exception.ProposalException) TransactionEventException(org.hyperledger.fabric.sdk.exception.TransactionEventException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) TransactionProposalRequest(org.hyperledger.fabric.sdk.TransactionProposalRequest) InstallProposalRequest(org.hyperledger.fabric.sdk.InstallProposalRequest) QueryByChaincodeRequest(org.hyperledger.fabric.sdk.QueryByChaincodeRequest) TxReadWriteSetInfo(org.hyperledger.fabric.sdk.TxReadWriteSetInfo) Collection(java.util.Collection) ChaincodeEvent(org.hyperledger.fabric.sdk.ChaincodeEvent) ProposalResponse(org.hyperledger.fabric.sdk.ProposalResponse) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) BlockEvent(org.hyperledger.fabric.sdk.BlockEvent)

Example 2 with ChaincodeID

use of org.hyperledger.fabric.sdk.ChaincodeID in project fabric-sdk-java by hyperledger.

the class NetworkConfigIT method deployChaincode.

private static ChaincodeID deployChaincode(HFClient client, Channel channel, String ccName, String ccPath, String ccVersion) throws Exception {
    out("deployChaincode - enter");
    ChaincodeID chaincodeID = null;
    try {
        final String channelName = channel.getName();
        out("deployChaincode - channelName = " + channelName);
        Collection<Orderer> orderers = channel.getOrderers();
        Collection<ProposalResponse> responses;
        Collection<ProposalResponse> successful = new LinkedList<>();
        Collection<ProposalResponse> failed = new LinkedList<>();
        chaincodeID = ChaincodeID.newBuilder().setName(ccName).setVersion(ccVersion).setPath(ccPath).build();
        // //////////////////////////
        // Install Proposal Request
        // 
        out("Creating install proposal");
        InstallProposalRequest installProposalRequest = client.newInstallProposalRequest();
        installProposalRequest.setChaincodeID(chaincodeID);
        // //For GO language and serving just a single user, chaincodeSource is mostly likely the users GOPATH
        installProposalRequest.setChaincodeSourceLocation(new File(TEST_FIXTURES_PATH + "/sdkintegration/gocc/sample1"));
        installProposalRequest.setChaincodeVersion(ccVersion);
        out("Sending install proposal");
        // //////////////////////////
        // only a client from the same org as the peer can issue an install request
        int numInstallProposal = 0;
        Collection<Peer> peersFromOrg = channel.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);
            }
        }
        out("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());
        }
        // /////////////
        // // Instantiate chaincode.
        // 
        // From the docs:
        // The instantiate transaction invokes the lifecycle System Chaincode (LSCC) to create and initialize a chaincode on a channel
        // After being successfully instantiated, the chaincode enters the active state on the channel and is ready to process any transaction proposals of type ENDORSER_TRANSACTION
        InstantiateProposalRequest instantiateProposalRequest = client.newInstantiationProposalRequest();
        instantiateProposalRequest.setProposalWaitTime(testConfig.getProposalWaitTime());
        instantiateProposalRequest.setChaincodeID(chaincodeID);
        instantiateProposalRequest.setFcn("init");
        instantiateProposalRequest.setArgs("a", "500", "b", "999");
        Map<String, byte[]> tm = new HashMap<>();
        tm.put("HyperLedgerFabric", "InstantiateProposalRequest:JavaSDK".getBytes(UTF_8));
        tm.put("method", "InstantiateProposalRequest".getBytes(UTF_8));
        instantiateProposalRequest.setTransientMap(tm);
        /*
              policy OR(Org1MSP.member, Org2MSP.member) meaning 1 signature from someone in either Org1 or Org2
              See README.md Chaincode endorsement policies section for more details.
            */
        ChaincodeEndorsementPolicy chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy();
        chaincodeEndorsementPolicy.fromYamlFile(new File(TEST_FIXTURES_PATH + "/sdkintegration/chaincodeendorsementpolicy.yaml"));
        instantiateProposalRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);
        out("Sending instantiateProposalRequest to all peers...");
        successful.clear();
        failed.clear();
        responses = channel.sendInstantiationProposal(instantiateProposalRequest);
        for (ProposalResponse response : responses) {
            if (response.isVerified() && response.getStatus() == ProposalResponse.Status.SUCCESS) {
                successful.add(response);
                out("Succesful instantiate proposal response Txid: %s from peer %s", response.getTransactionID(), response.getPeer().getName());
            } else {
                failed.add(response);
            }
        }
        out("Received %d instantiate proposal responses. Successful+verified: %d . Failed: %d", responses.size(), successful.size(), failed.size());
        if (failed.size() > 0) {
            ProposalResponse first = failed.iterator().next();
            fail("Not enough endorsers for instantiate :" + successful.size() + "endorser failed with " + first.getMessage() + ". Was verified:" + first.isVerified());
        }
        // /////////////
        // / Send instantiate transaction to orderer
        out("Sending instantiateTransaction to orderer...");
        CompletableFuture<TransactionEvent> future = channel.sendTransaction(successful, orderers);
        out("calling get...");
        TransactionEvent event = future.get(30, TimeUnit.SECONDS);
        out("get done...");
        // must be valid to be here.
        assertTrue(event.isValid());
        out("Finished instantiate transaction with transaction id %s", event.getTransactionID());
    } catch (Exception e) {
        e.printStackTrace();
        out("Caught an exception running channel %s", channel.getName());
        fail("Test failed with error : " + e.getMessage());
    }
    return chaincodeID;
}
Also used : ChaincodeEndorsementPolicy(org.hyperledger.fabric.sdk.ChaincodeEndorsementPolicy) HashMap(java.util.HashMap) Peer(org.hyperledger.fabric.sdk.Peer) ChaincodeID(org.hyperledger.fabric.sdk.ChaincodeID) LinkedList(java.util.LinkedList) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) ProposalException(org.hyperledger.fabric.sdk.exception.ProposalException) CompletionException(java.util.concurrent.CompletionException) TransactionEventException(org.hyperledger.fabric.sdk.exception.TransactionEventException) TransactionEvent(org.hyperledger.fabric.sdk.BlockEvent.TransactionEvent) InstallProposalRequest(org.hyperledger.fabric.sdk.InstallProposalRequest) InstantiateProposalRequest(org.hyperledger.fabric.sdk.InstantiateProposalRequest) ProposalResponse(org.hyperledger.fabric.sdk.ProposalResponse) File(java.io.File) Orderer(org.hyperledger.fabric.sdk.Orderer)

Example 3 with ChaincodeID

use of org.hyperledger.fabric.sdk.ChaincodeID in project fabric-sdk-java by hyperledger.

the class End2endAndBackAgainIT method runChannel.

// Disable MethodLength as this method is for instructional purposes and hence
// we don't want to split it into smaller pieces
// CHECKSTYLE:OFF: MethodLength
void runChannel(HFClient client, Channel channel, SampleOrg sampleOrg, final int delta) {
    final String channelName = channel.getName();
    try {
        client.setUserContext(sampleOrg.getUser(TESTUSER_1_NAME));
        // final boolean changeContext = false; // BAR_CHANNEL_NAME.equals(channel.getName()) ? true : false;
        final boolean changeContext = BAR_CHANNEL_NAME.equals(channel.getName());
        out("Running Channel %s with a delta %d", channelName, delta);
        out("ChaincodeID: ", chaincodeID);
        // //////////////////////////
        // Send Query Proposal to all peers see if it's what we expect from end of End2endIT
        // 
        queryChaincodeForExpectedValue(client, channel, "" + (300 + delta), chaincodeID);
        // Set user context on client but use explicit user contest on each call.
        if (changeContext) {
            client.setUserContext(sampleOrg.getUser(TESTUSER_1_NAME));
        }
        // exercise v1 of chaincode
        moveAmount(client, channel, chaincodeID, "25", changeContext ? sampleOrg.getPeerAdmin() : null).thenApply((BlockEvent.TransactionEvent transactionEvent) -> {
            try {
                waitOnFabric();
                client.setUserContext(sampleOrg.getUser(TESTUSER_1_NAME));
                queryChaincodeForExpectedValue(client, channel, "" + (325 + delta), chaincodeID);
                // ////////////////
                // Start of upgrade first must install it.
                client.setUserContext(sampleOrg.getPeerAdmin());
                // /////////////
                // //
                InstallProposalRequest installProposalRequest = client.newInstallProposalRequest();
                installProposalRequest.setChaincodeID(chaincodeID);
                // //For GO language and serving just a single user, chaincodeSource is mostly likely the users GOPATH
                installProposalRequest.setChaincodeSourceLocation(Paths.get(TEST_FIXTURES_PATH, CHAIN_CODE_FILEPATH).toFile());
                installProposalRequest.setChaincodeVersion(CHAIN_CODE_VERSION_11);
                installProposalRequest.setProposalWaitTime(testConfig.getProposalWaitTime());
                installProposalRequest.setChaincodeLanguage(CHAIN_CODE_LANG);
                if (changeContext) {
                    installProposalRequest.setUserContext(sampleOrg.getPeerAdmin());
                }
                out("Sending install proposal for channel: %s", channel.getName());
                // //////////////////////////
                // only a client from the same org as the peer can issue an install request
                int numInstallProposal = 0;
                Collection<ProposalResponse> responses;
                final Collection<ProposalResponse> successful = new LinkedList<>();
                final Collection<ProposalResponse> failed = new LinkedList<>();
                Collection<Peer> peersFromOrg = channel.getPeers();
                numInstallProposal = numInstallProposal + peersFromOrg.size();
                responses = client.sendInstallProposal(installProposalRequest, peersFromOrg);
                for (ProposalResponse response : responses) {
                    if (response.getStatus() == Status.SUCCESS) {
                        out("Successful install proposal response Txid: %s from peer %s", response.getTransactionID(), response.getPeer().getName());
                        successful.add(response);
                    } else {
                        failed.add(response);
                    }
                }
                out("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());
                }
                if (changeContext) {
                    installProposalRequest.setUserContext(sampleOrg.getPeerAdmin());
                }
                UpgradeProposalRequest upgradeProposalRequest = client.newUpgradeProposalRequest();
                upgradeProposalRequest.setChaincodeID(chaincodeID_11);
                upgradeProposalRequest.setProposalWaitTime(testConfig.getProposalWaitTime());
                upgradeProposalRequest.setFcn("init");
                // no arguments don't change the ledger see chaincode.
                upgradeProposalRequest.setArgs(new String[] {});
                ChaincodeEndorsementPolicy chaincodeEndorsementPolicy;
                chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy();
                chaincodeEndorsementPolicy.fromYamlFile(new File(TEST_FIXTURES_PATH + "/sdkintegration/chaincodeendorsementpolicy.yaml"));
                upgradeProposalRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);
                Map<String, byte[]> tmap = new HashMap<>();
                tmap.put("test", "data".getBytes());
                upgradeProposalRequest.setTransientMap(tmap);
                if (changeContext) {
                    upgradeProposalRequest.setUserContext(sampleOrg.getPeerAdmin());
                }
                out("Sending upgrade proposal");
                Collection<ProposalResponse> responses2;
                responses2 = channel.sendUpgradeProposal(upgradeProposalRequest);
                successful.clear();
                failed.clear();
                for (ProposalResponse response : responses2) {
                    if (response.getStatus() == Status.SUCCESS) {
                        out("Successful upgrade proposal response Txid: %s from peer %s", response.getTransactionID(), response.getPeer().getName());
                        successful.add(response);
                    } else {
                        failed.add(response);
                    }
                }
                out("Received %d upgrade proposal responses. Successful+verified: %d . Failed: %d", channel.getPeers().size(), successful.size(), failed.size());
                if (failed.size() > 0) {
                    ProposalResponse first = failed.iterator().next();
                    throw new AssertionError("Not enough endorsers for upgrade :" + successful.size() + ".  " + first.getMessage());
                }
                if (changeContext) {
                    return channel.sendTransaction(successful, sampleOrg.getPeerAdmin()).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS);
                } else {
                    return channel.sendTransaction(successful).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS);
                }
            } catch (CompletionException e) {
                throw e;
            } catch (Exception e) {
                throw new CompletionException(e);
            }
        }).thenApply(transactionEvent -> {
            try {
                waitOnFabric(10000);
                out("Chaincode has been upgraded to version %s", CHAIN_CODE_VERSION_11);
                // Check to see if peers have new chaincode and old chaincode is gone.
                client.setUserContext(sampleOrg.getPeerAdmin());
                for (Peer peer : channel.getPeers()) {
                    if (!checkInstalledChaincode(client, peer, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION_11)) {
                        throw new AssertionError(format("Peer %s is missing chaincode name:%s, path:%s, version: %s", peer.getName(), CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_PATH));
                    }
                    // should be instantiated too..
                    if (!checkInstantiatedChaincode(channel, peer, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION_11)) {
                        throw new AssertionError(format("Peer %s is missing instantiated chaincode name:%s, path:%s, version: %s", peer.getName(), CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_PATH));
                    }
                    if (checkInstantiatedChaincode(channel, peer, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION)) {
                        throw new AssertionError(format("Peer %s still has old instantiated chaincode name:%s, path:%s, version: %s", peer.getName(), CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_PATH));
                    }
                }
                client.setUserContext(sampleOrg.getUser(TESTUSER_1_NAME));
                // /Check if we still get the same value on the ledger
                out("delta is %s", delta);
                queryChaincodeForExpectedValue(client, channel, "" + (325 + delta), chaincodeID);
                // Now lets run the new chaincode which should *double* the results we asked to move.
                return moveAmount(client, channel, chaincodeID_11, "50", changeContext ? sampleOrg.getPeerAdmin() : null).get(testConfig.getTransactionWaitTime(), // really move 100
                TimeUnit.SECONDS);
            } catch (CompletionException e) {
                throw e;
            } catch (Exception e) {
                throw new CompletionException(e);
            }
        }).thenApply(transactionEvent -> {
            waitOnFabric(10000);
            queryChaincodeForExpectedValue(client, channel, "" + (425 + delta), chaincodeID_11);
            return null;
        }).exceptionally(e -> {
            if (e instanceof CompletionException && e.getCause() != null) {
                e = e.getCause();
            }
            if (e instanceof TransactionEventException) {
                BlockEvent.TransactionEvent te = ((TransactionEventException) e).getTransactionEvent();
                if (te != null) {
                    e.printStackTrace(System.err);
                    fail(format("Transaction with txid %s failed. %s", te.getTransactionID(), e.getMessage()));
                }
            }
            e.printStackTrace(System.err);
            fail(format("Test failed with %s exception %s", e.getClass().getName(), e.getMessage()));
            return null;
        }).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    out("Running for Channel %s done", channelName);
}
Also used : UpgradeProposalRequest(org.hyperledger.fabric.sdk.UpgradeProposalRequest) BlockInfo(org.hyperledger.fabric.sdk.BlockInfo) Map(java.util.Map) TestConfigHelper(org.hyperledger.fabric.sdk.TestConfigHelper) Assert.fail(org.junit.Assert.fail) PeerOptions(org.hyperledger.fabric.sdk.Channel.PeerOptions) EnumSet(java.util.EnumSet) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) TestConfig(org.hyperledger.fabric.sdk.testutils.TestConfig) TestUtils(org.hyperledger.fabric.sdk.testutils.TestUtils) Collection(java.util.Collection) ProposalException(org.hyperledger.fabric.sdk.exception.ProposalException) Channel(org.hyperledger.fabric.sdk.Channel) Set(java.util.Set) User(org.hyperledger.fabric.sdk.User) CompletionException(java.util.concurrent.CompletionException) ChaincodeInfo(org.hyperledger.fabric.protos.peer.Query.ChaincodeInfo) String.format(java.lang.String.format) List(java.util.List) Peer(org.hyperledger.fabric.sdk.Peer) Assert.assertFalse(org.junit.Assert.assertFalse) Status(org.hyperledger.fabric.sdk.ChaincodeResponse.Status) ChaincodeEvent(org.hyperledger.fabric.sdk.ChaincodeEvent) TransactionRequest(org.hyperledger.fabric.sdk.TransactionRequest) ChaincodeID(org.hyperledger.fabric.sdk.ChaincodeID) EventHub(org.hyperledger.fabric.sdk.EventHub) HFClient(org.hyperledger.fabric.sdk.HFClient) PeerRole(org.hyperledger.fabric.sdk.Peer.PeerRole) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) QueryByChaincodeRequest(org.hyperledger.fabric.sdk.QueryByChaincodeRequest) ArrayList(java.util.ArrayList) TransactionEventException(org.hyperledger.fabric.sdk.exception.TransactionEventException) BlockchainInfo(org.hyperledger.fabric.sdk.BlockchainInfo) BlockEvent(org.hyperledger.fabric.sdk.BlockEvent) LinkedList(java.util.LinkedList) HFCAClient(org.hyperledger.fabric_ca.sdk.HFCAClient) Before(org.junit.Before) InstallProposalRequest(org.hyperledger.fabric.sdk.InstallProposalRequest) Properties(java.util.Properties) ChaincodeEndorsementPolicy(org.hyperledger.fabric.sdk.ChaincodeEndorsementPolicy) ProposalResponse(org.hyperledger.fabric.sdk.ProposalResponse) MalformedURLException(java.net.MalformedURLException) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) PeerOptions.createPeerOptions(org.hyperledger.fabric.sdk.Channel.PeerOptions.createPeerOptions) Configtx(org.hyperledger.fabric.protos.common.Configtx) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) CryptoSuite(org.hyperledger.fabric.sdk.security.CryptoSuite) Assert.assertNull(org.junit.Assert.assertNull) Paths(java.nio.file.Paths) TestUtils.resetConfig(org.hyperledger.fabric.sdk.testutils.TestUtils.resetConfig) TRANSACTION_ENVELOPE(org.hyperledger.fabric.sdk.BlockInfo.EnvelopeType.TRANSACTION_ENVELOPE) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) TransactionProposalRequest(org.hyperledger.fabric.sdk.TransactionProposalRequest) ChaincodeEndorsementPolicy(org.hyperledger.fabric.sdk.ChaincodeEndorsementPolicy) HashMap(java.util.HashMap) TransactionEventException(org.hyperledger.fabric.sdk.exception.TransactionEventException) Peer(org.hyperledger.fabric.sdk.Peer) LinkedList(java.util.LinkedList) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) ProposalException(org.hyperledger.fabric.sdk.exception.ProposalException) CompletionException(java.util.concurrent.CompletionException) TransactionEventException(org.hyperledger.fabric.sdk.exception.TransactionEventException) MalformedURLException(java.net.MalformedURLException) InstallProposalRequest(org.hyperledger.fabric.sdk.InstallProposalRequest) UpgradeProposalRequest(org.hyperledger.fabric.sdk.UpgradeProposalRequest) CompletionException(java.util.concurrent.CompletionException) ProposalResponse(org.hyperledger.fabric.sdk.ProposalResponse) File(java.io.File)

Example 4 with ChaincodeID

use of org.hyperledger.fabric.sdk.ChaincodeID in project fabric-sdk-java by hyperledger.

the class NetworkConfigIT method testUpdate1.

@Test
public void testUpdate1() throws Exception {
    // Setup client and channel instances
    HFClient client = getTheClient();
    Channel channel = constructChannel(client, FOO_CHANNEL_NAME);
    final ChaincodeID chaincodeID = ChaincodeID.newBuilder().setName(CHAIN_CODE_NAME).setVersion(CHAIN_CODE_VERSION).setPath(CHAIN_CODE_PATH).build();
    final String channelName = channel.getName();
    out("Running testUpdate1 - Channel %s", channelName);
    int moveAmount = 5;
    String originalVal = queryChaincodeForCurrentValue(client, channel, chaincodeID);
    String newVal = "" + (Integer.parseInt(originalVal) + moveAmount);
    out("Original value = %s", originalVal);
    // Move some assets
    moveAmount(client, channel, chaincodeID, "a", "b", "" + moveAmount, null).thenApply(transactionEvent -> {
        // Check that they were moved
        queryChaincodeForExpectedValue(client, channel, newVal, chaincodeID);
        return null;
    }).thenApply(transactionEvent -> {
        // Move them back
        try {
            return moveAmount(client, channel, chaincodeID, "b", "a", "" + moveAmount, null).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }).thenApply(transactionEvent -> {
        // Check that they were moved back
        queryChaincodeForExpectedValue(client, channel, originalVal, chaincodeID);
        return null;
    }).exceptionally(e -> {
        if (e instanceof CompletionException && e.getCause() != null) {
            e = e.getCause();
        }
        if (e instanceof TransactionEventException) {
            BlockEvent.TransactionEvent te = ((TransactionEventException) e).getTransactionEvent();
            if (te != null) {
                e.printStackTrace(System.err);
                fail(format("Transaction with txid %s failed. %s", te.getTransactionID(), e.getMessage()));
            }
        }
        e.printStackTrace(System.err);
        fail(format("Test failed with %s exception %s", e.getClass().getName(), e.getMessage()));
        return null;
    }).get(testConfig.getTransactionWaitTime(), TimeUnit.SECONDS);
    // Force channel to shutdown clean up resources.
    channel.shutdown(true);
    out("testUpdate1 - done");
}
Also used : InstantiateProposalRequest(org.hyperledger.fabric.sdk.InstantiateProposalRequest) Map(java.util.Map) TestConfigHelper(org.hyperledger.fabric.sdk.TestConfigHelper) Assert.fail(org.junit.Assert.fail) Orderer(org.hyperledger.fabric.sdk.Orderer) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) MockUser(org.hyperledger.fabric.sdk.testutils.TestUtils.MockUser) TestConfig(org.hyperledger.fabric.sdk.testutils.TestConfig) TestUtils(org.hyperledger.fabric.sdk.testutils.TestUtils) Collection(java.util.Collection) ProposalException(org.hyperledger.fabric.sdk.exception.ProposalException) Channel(org.hyperledger.fabric.sdk.Channel) Set(java.util.Set) User(org.hyperledger.fabric.sdk.User) CompletionException(java.util.concurrent.CompletionException) ChaincodeInfo(org.hyperledger.fabric.protos.peer.Query.ChaincodeInfo) String.format(java.lang.String.format) List(java.util.List) PrivateKey(java.security.PrivateKey) Peer(org.hyperledger.fabric.sdk.Peer) Status(org.hyperledger.fabric.sdk.ChaincodeResponse.Status) BeforeClass(org.junit.BeforeClass) ChaincodeID(org.hyperledger.fabric.sdk.ChaincodeID) HFClient(org.hyperledger.fabric.sdk.HFClient) TransactionEvent(org.hyperledger.fabric.sdk.BlockEvent.TransactionEvent) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) QueryByChaincodeRequest(org.hyperledger.fabric.sdk.QueryByChaincodeRequest) TransactionEventException(org.hyperledger.fabric.sdk.exception.TransactionEventException) BlockEvent(org.hyperledger.fabric.sdk.BlockEvent) LinkedList(java.util.LinkedList) SDKUtils(org.hyperledger.fabric.sdk.SDKUtils) HFCAClient(org.hyperledger.fabric_ca.sdk.HFCAClient) NetworkConfig(org.hyperledger.fabric.sdk.NetworkConfig) InstallProposalRequest(org.hyperledger.fabric.sdk.InstallProposalRequest) HFCAInfo(org.hyperledger.fabric_ca.sdk.HFCAInfo) ChaincodeEndorsementPolicy(org.hyperledger.fabric.sdk.ChaincodeEndorsementPolicy) ProposalResponse(org.hyperledger.fabric.sdk.ProposalResponse) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) CAInfo(org.hyperledger.fabric.sdk.NetworkConfig.CAInfo) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) CryptoSuite(org.hyperledger.fabric.sdk.security.CryptoSuite) Assert.assertNull(org.junit.Assert.assertNull) TestUtils.resetConfig(org.hyperledger.fabric.sdk.testutils.TestUtils.resetConfig) Assert.assertEquals(org.junit.Assert.assertEquals) TransactionProposalRequest(org.hyperledger.fabric.sdk.TransactionProposalRequest) TransactionEvent(org.hyperledger.fabric.sdk.BlockEvent.TransactionEvent) TransactionEventException(org.hyperledger.fabric.sdk.exception.TransactionEventException) Channel(org.hyperledger.fabric.sdk.Channel) CompletionException(java.util.concurrent.CompletionException) HFClient(org.hyperledger.fabric.sdk.HFClient) ChaincodeID(org.hyperledger.fabric.sdk.ChaincodeID) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) ProposalException(org.hyperledger.fabric.sdk.exception.ProposalException) CompletionException(java.util.concurrent.CompletionException) TransactionEventException(org.hyperledger.fabric.sdk.exception.TransactionEventException) Test(org.junit.Test)

Aggregations

File (java.io.File)4 HashMap (java.util.HashMap)4 LinkedList (java.util.LinkedList)4 ChaincodeEndorsementPolicy (org.hyperledger.fabric.sdk.ChaincodeEndorsementPolicy)4 ChaincodeID (org.hyperledger.fabric.sdk.ChaincodeID)4 InstallProposalRequest (org.hyperledger.fabric.sdk.InstallProposalRequest)4 Peer (org.hyperledger.fabric.sdk.Peer)4 ProposalResponse (org.hyperledger.fabric.sdk.ProposalResponse)4 InvalidArgumentException (org.hyperledger.fabric.sdk.exception.InvalidArgumentException)4 ProposalException (org.hyperledger.fabric.sdk.exception.ProposalException)4 TransactionEventException (org.hyperledger.fabric.sdk.exception.TransactionEventException)4 String.format (java.lang.String.format)3 UTF_8 (java.nio.charset.StandardCharsets.UTF_8)3 Collection (java.util.Collection)3 Map (java.util.Map)3 Set (java.util.Set)3 CompletionException (java.util.concurrent.CompletionException)3 TimeUnit (java.util.concurrent.TimeUnit)3 BlockEvent (org.hyperledger.fabric.sdk.BlockEvent)3 Channel (org.hyperledger.fabric.sdk.Channel)3