Submit Message to Private Topic

Summary

In the previous tutorial, "Submit Your First Message," you have learned how to submit a message to a public topic. It means anyone can send a message to the topic you created because you didn't set a Submit Key.

When setting a Submit Key, your topic becomes a private topic because each message needs to be signed by the Submit Key. Therefore, you can control who can submit messages to your topic. Of course, the data is still public, as is all data on a public ledger, but we say the topic is private because the topic is restricted by who can submit messages to it.

Prerequisites

We recommend you complete the "Submit Your First Message" tutorial here to get a basic understanding of the Hedera Consensus Service. This example does not build upon the previous examples.

You can find a full code check for this tutorial at the bottom of this page.

1. Create a private topic

To create a private topic, you will use setSubmitKey() to set a Submit Key. This key needs to sign all messages someone sends to the topic. A message will be rejected if you don't sign the message or sign with an incorrect key. The cost of creating a private topic is the same as a public topic: $0.01.

// Create a new topic
TransactionResponse txResponse = new TopicCreateTransaction()
   .setSubmitKey(myPrivateKey.getPublicKey())
   .execute(client);

// Get the receipt
TransactionReceipt receipt = txResponse.getReceipt(client);
        
// Get the topic ID
TopicId topicId = receipt.topicId;

// Log the topic ID
System.out.println("Your topic ID is: " +topicId);

// Wait 5 seconds between consensus topic creation and subscription creation
Thread.sleep(5000);

2. Subscribe to a topic

The code used to subscribe to a public or private topic doesn't change. Anyone can listen to the messages you send to your private topic. You need to provide the TopicMessageQuery() with your topic ID to subscribe to it.

3. Submit a message

Now you are ready to submit a message to your private topic. To do this, you will use TopicMessageSubmitTransaction(). However, you need to sign this transaction with your Submit Key. The cost for sending a message to a private topic is the same as a public topic: $0.0001.

To conclude: The total cost to create a topic and send a message to it is $0.0101.

Code Check ✅

Java
JavaScript
Go

Last updated