Search in sources :

Example 11 with Channel

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

the class End2endAndBackAgainIT method testPeerServiceEventingReplay.

/**
 * This code test the replay feature of the new peer event services.
 * Instead of the default of starting the eventing peer to retrieve the newest block it sets it
 * retrieve starting from the start parameter. Also checks with block and filterblock replays.
 * Depends on end2end and end2endAndBackagain of have fully run to have the blocks need to work with.
 *
 * @param client
 * @param replayTestChannel
 * @param start
 * @param stop
 * @param useFilteredBlocks
 * @throws InvalidArgumentException
 */
private void testPeerServiceEventingReplay(HFClient client, Channel replayTestChannel, final long start, final long stop, final boolean useFilteredBlocks) throws InvalidArgumentException {
    if (testConfig.isRunningAgainstFabric10()) {
        // not supported for v1.0
        return;
    }
    // not yet initialized
    assertFalse(replayTestChannel.isInitialized());
    // not yet shutdown.
    assertFalse(replayTestChannel.isShutdown());
    // Remove all peers just have one ledger peer and one eventing peer.
    List<Peer> savedPeers = new ArrayList<>(replayTestChannel.getPeers());
    for (Peer peer : savedPeers) {
        replayTestChannel.removePeer(peer);
    }
    // need at least two
    assertTrue(savedPeers.size() > 1);
    final Peer eventingPeer = savedPeers.remove(0);
    Peer ledgerPeer = savedPeers.remove(0);
    // no more peers.
    assertTrue(replayTestChannel.getPeers().isEmpty());
    // just checking :)
    assertTrue(replayTestChannel.getPeers(EnumSet.of(PeerRole.CHAINCODE_QUERY, PeerRole.ENDORSING_PEER)).isEmpty());
    // just checking
    assertTrue(replayTestChannel.getPeers(EnumSet.of(PeerRole.LEDGER_QUERY)).isEmpty());
    // should be known by client.
    assertNotNull(client.getChannel(replayTestChannel.getName()));
    final PeerOptions eventingPeerOptions = createPeerOptions().setPeerRoles(EnumSet.of(PeerRole.EVENT_SOURCE));
    if (useFilteredBlocks) {
        eventingPeerOptions.registerEventsForFilteredBlocks();
    }
    if (-1L == stop) {
        // the height of the blockchain
        // Eventing peer start getting blocks from block 0
        replayTestChannel.addPeer(eventingPeer, eventingPeerOptions.startEvents(start));
    } else {
        replayTestChannel.addPeer(eventingPeer, eventingPeerOptions.startEvents(start).stopEvents(// Eventing peer start getting blocks from block 0
        stop));
    }
    // add a ledger peer
    replayTestChannel.addPeer(ledgerPeer, createPeerOptions().setPeerRoles(EnumSet.of(PeerRole.LEDGER_QUERY)));
    // future to set when done.
    CompletableFuture<Long> done = new CompletableFuture<>();
    // some variable used by the block listener being set up.
    final AtomicLong bcount = new AtomicLong(0);
    final AtomicLong stopValue = new AtomicLong(stop == -1L ? Long.MAX_VALUE : stop);
    final Channel finalChannel = replayTestChannel;
    final Map<Long, BlockEvent> blockEvents = Collections.synchronizedMap(new HashMap<>(100));
    final String blockListenerHandle = replayTestChannel.registerBlockListener(blockEvent -> {
        try {
            final long blockNumber = blockEvent.getBlockNumber();
            BlockEvent seen = blockEvents.put(blockNumber, blockEvent);
            assertNull(format("Block number %d seen twice", blockNumber), seen);
            assertTrue(format("Wrong type of block seen block number %d. expected filtered block %b but got %b", blockNumber, useFilteredBlocks, blockEvent.isFiltered()), useFilteredBlocks ? blockEvent.isFiltered() : !blockEvent.isFiltered());
            // count starts with 0 not 1 !
            final long count = bcount.getAndIncrement();
            if (count == 0 && stop == -1L) {
                final BlockchainInfo blockchainInfo = finalChannel.queryBlockchainInfo();
                long lh = blockchainInfo.getHeight();
                // blocks 0L 9L are on chain height 10 .. stop on 9
                stopValue.set(lh - 1L);
                // out("height: %d", lh);
                if (bcount.get() + start > stopValue.longValue()) {
                    // test with latest count.
                    // report back latest count.
                    done.complete(bcount.get());
                }
            } else {
                if (bcount.longValue() + start > stopValue.longValue()) {
                    done.complete(count);
                }
            }
        } catch (AssertionError | Exception e) {
            e.printStackTrace();
            done.completeExceptionally(e);
        }
    });
    try {
        // start it all up.
        replayTestChannel.initialize();
        // give a timeout here.
        done.get(30, TimeUnit.SECONDS);
        // sleep a little to see if more blocks trickle in .. they should not
        Thread.sleep(1000);
        replayTestChannel.unregisterBlockListener(blockListenerHandle);
        // Start 2 and stop is 3  expect 2
        final long expectNumber = stopValue.longValue() - start + 1L;
        assertEquals(format("Didn't get number we expected %d but got %d block events. Start: %d, end: %d, height: %d", expectNumber, blockEvents.size(), start, stop, stopValue.longValue()), expectNumber, blockEvents.size());
        for (long i = stopValue.longValue(); i >= start; i--) {
            // make sure all are there.
            final BlockEvent blockEvent = blockEvents.get(i);
            assertNotNull(format("Missing block event for block number %d. Start= %d", i, start), blockEvent);
        }
        // light weight test just see if we get reasonable values for traversing the block. Test just whats common between
        // Block and FilteredBlock.
        int transactionEventCounts = 0;
        int chaincodeEventsCounts = 0;
        for (long i = stopValue.longValue(); i >= start; i--) {
            final BlockEvent blockEvent = blockEvents.get(i);
            // out("blockwalker %b, start: %d, stop: %d, i: %d, block %d", useFilteredBlocks, start, stopValue.longValue(), i, blockEvent.getBlockNumber());
            // check again
            assertEquals(useFilteredBlocks, blockEvent.isFiltered());
            if (useFilteredBlocks) {
                // should not have raw block event.
                assertNull(blockEvent.getBlock());
                // should have raw filtered block.
                assertNotNull(blockEvent.getFilteredBlock());
            } else {
                // should not have raw block event.
                assertNotNull(blockEvent.getBlock());
                // should have raw filtered block.
                assertNull(blockEvent.getFilteredBlock());
            }
            assertEquals(replayTestChannel.getName(), blockEvent.getChannelId());
            for (BlockInfo.EnvelopeInfo envelopeInfo : blockEvent.getEnvelopeInfos()) {
                if (envelopeInfo.getType() == TRANSACTION_ENVELOPE) {
                    BlockInfo.TransactionEnvelopeInfo transactionEnvelopeInfo = (BlockInfo.TransactionEnvelopeInfo) envelopeInfo;
                    // only have valid blocks.
                    assertTrue(envelopeInfo.isValid());
                    assertEquals(envelopeInfo.getValidationCode(), 0);
                    ++transactionEventCounts;
                    for (BlockInfo.TransactionEnvelopeInfo.TransactionActionInfo ta : transactionEnvelopeInfo.getTransactionActionInfos()) {
                        // out("\nTA:", ta + "\n\n");
                        ChaincodeEvent event = ta.getEvent();
                        if (event != null) {
                            assertNotNull(event.getChaincodeId());
                            assertNotNull(event.getEventName());
                            chaincodeEventsCounts++;
                        }
                    }
                } else {
                    assertEquals("Only non transaction block should be block 0.", blockEvent.getBlockNumber(), 0);
                }
            }
        }
        assertTrue(transactionEventCounts > 0);
        if (expectNumber > 4) {
            // this should be enough blocks with CC events.
            assertTrue(chaincodeEventsCounts > 0);
        }
        // all done.
        replayTestChannel.shutdown(true);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : ArrayList(java.util.ArrayList) PeerOptions(org.hyperledger.fabric.sdk.Channel.PeerOptions) PeerOptions.createPeerOptions(org.hyperledger.fabric.sdk.Channel.PeerOptions.createPeerOptions) CompletableFuture(java.util.concurrent.CompletableFuture) BlockInfo(org.hyperledger.fabric.sdk.BlockInfo) Peer(org.hyperledger.fabric.sdk.Peer) Channel(org.hyperledger.fabric.sdk.Channel) BlockchainInfo(org.hyperledger.fabric.sdk.BlockchainInfo) 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) AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicLong(java.util.concurrent.atomic.AtomicLong) ChaincodeEvent(org.hyperledger.fabric.sdk.ChaincodeEvent) BlockEvent(org.hyperledger.fabric.sdk.BlockEvent)

Example 12 with Channel

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

the class End2endIT method runFabricTest.

public void runFabricTest(final SampleStore sampleStore) throws Exception {
    // //////////////////////////
    // Setup client
    // Create instance of client.
    HFClient client = HFClient.createNewInstance();
    client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
    // //////////////////////////
    // Construct and run the channels
    SampleOrg sampleOrg = testConfig.getIntegrationTestsSampleOrg("peerOrg1");
    Channel fooChannel = constructChannel(FOO_CHANNEL_NAME, client, sampleOrg);
    sampleStore.saveChannel(fooChannel);
    runChannel(client, fooChannel, true, sampleOrg, 0);
    assertFalse(fooChannel.isShutdown());
    // Force foo channel to shutdown clean up resources.
    fooChannel.shutdown(true);
    assertTrue(fooChannel.isShutdown());
    assertNull(client.getChannel(FOO_CHANNEL_NAME));
    out("\n");
    sampleOrg = testConfig.getIntegrationTestsSampleOrg("peerOrg2");
    Channel barChannel = constructChannel(BAR_CHANNEL_NAME, client, sampleOrg);
    assertTrue(barChannel.isInitialized());
    /**
     * sampleStore.saveChannel uses {@link Channel#serializeChannel()}
     */
    sampleStore.saveChannel(barChannel);
    assertFalse(barChannel.isShutdown());
    // run a newly constructed bar channel with different b value!
    runChannel(client, barChannel, true, sampleOrg, 100);
    // let bar channel just shutdown so we have both scenarios.
    out("\nTraverse the blocks for chain %s ", barChannel.getName());
    blockWalker(client, barChannel);
    assertFalse(barChannel.isShutdown());
    assertTrue(barChannel.isInitialized());
    out("That's all folks!");
}
Also used : Channel(org.hyperledger.fabric.sdk.Channel) HFClient(org.hyperledger.fabric.sdk.HFClient)

Example 13 with Channel

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

the class NetworkConfigIT method deployChaincodeIfRequired.

// Determines whether or not the chaincode has been deployed and deploys it if necessary
private static void deployChaincodeIfRequired() throws Exception {
    // //////////////////////////
    // Setup client
    HFClient client = getTheClient();
    Channel channel = constructChannel(client, FOO_CHANNEL_NAME);
    // Use any old peer...
    Peer peer = channel.getPeers().iterator().next();
    if (!checkInstantiatedChaincode(channel, peer, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION)) {
        // The chaincode we require does not exist, so deploy it...
        deployChaincode(client, channel, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION);
    }
}
Also used : Channel(org.hyperledger.fabric.sdk.Channel) Peer(org.hyperledger.fabric.sdk.Peer) HFClient(org.hyperledger.fabric.sdk.HFClient)

Example 14 with Channel

use of org.hyperledger.fabric.sdk.Channel 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)

Example 15 with Channel

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

the class SampleStore method getChannel.

Channel getChannel(HFClient client, String name) throws IOException, ClassNotFoundException, InvalidArgumentException {
    Channel ret = null;
    String channelHex = getValue("channel." + name);
    if (channelHex != null) {
        ret = client.deSerializeChannel(Hex.decode(channelHex));
    }
    return ret;
}
Also used : Channel(org.hyperledger.fabric.sdk.Channel)

Aggregations

Channel (org.hyperledger.fabric.sdk.Channel)15 Peer (org.hyperledger.fabric.sdk.Peer)8 HFClient (org.hyperledger.fabric.sdk.HFClient)7 File (java.io.File)5 CryptoSuite (org.hyperledger.fabric.sdk.security.CryptoSuite)5 MalformedURLException (java.net.MalformedURLException)4 LinkedList (java.util.LinkedList)4 BlockEvent (org.hyperledger.fabric.sdk.BlockEvent)4 EventHub (org.hyperledger.fabric.sdk.EventHub)4 User (org.hyperledger.fabric.sdk.User)4 String.format (java.lang.String.format)3 UTF_8 (java.nio.charset.StandardCharsets.UTF_8)3 Collection (java.util.Collection)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Properties (java.util.Properties)3 Set (java.util.Set)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 CompletionException (java.util.concurrent.CompletionException)3 TimeUnit (java.util.concurrent.TimeUnit)3