Tutorials ‐ Hubs - HelloZeroNet/Plugin-PeerMessage GitHub Wiki

Why you need hubs at all

Broadcast messages are the simpliest way to send information over network. However, this also means that every node receives messages. If your site has many peers, this may be slow and use much network traffic. But it's likely that most peers don't need these messages - for example, if you're building group chat, you only need to send messages to members of the group, etc.

So you create a hub which won't store information but rather be a sign of being a member of a group. So each group member will download this hub, and only post messages to those who have this hub downloaded. Rather simple, isn't it?

Create a hub

  1. Create a new empty site
  2. Add "merged_type": "MyAwesomeChat" to content.json.
  3. Sign and publish

Connect hub

Now let's write code to join this hub.

const HUB_ADDRESS = "1BitcoinEaterAddressDontSendf59kuE"; // put hub address here

// Add hub
zeroFrame.cmd("permissionAdd", ["Merger:MyAwesomeChat"], function() {
    zeroFrame.cmd("mergerSiteAdd", [HUB_ADDRESS]);
});

Send messages

Notice that we use command as, so calling as(HUB_ADDRESS, peerBroadcast) is the same as running peerBroadcast in hub code. So, we also need p2p.json in hub's directory.

So let's use our knowledge to send message:

function sendMessage(text) {
    // Send message to those who have downloaded hub
    zeroFrame.cmd("as", [HUB_ADDRESS, "peerBroadcast", {message: text, privatekey: false}]);
}

Receive messages

When ZeroHello is opened, it automatically joins main channel of all sites. It means that it will receive all updates on all sites, allowing it to show when a site is deleted, downloaded or updated.

This brings another problem: ZeroHello would also receive all peerReceive messages. So it will receive all messages, which is a) slow, b) unsecure. PeerMessage has a fix for this: peerReceive channel. So technically you would only receive messages if you join peerReceive channel. PeerMessage plugin makes this easy: if p2p.json file exists, the channel will be joined automatically.

So, the simpliest solution is: just create empty p2p.json in merger site's root, like this:

{}

Notice that it must be valid JSON to avoid parsing errors, however, it shouldn't be valid p2p.json - i.e. it shouldn't contain "filter" property. You won't be able to send messages to this very site, but you'll be able to receive messages from peerReceive channel.

All the code left is the same as in the previous tutorial (Signatures). However, you'll also get "site" property equal to HUB_ADDRESS.

1 hub?

Of course, you can always create as many hubs as you want, save their addresses to some database and then access the one you need.

But notice that in this tutorial we had only 1 hub (HUB_ADDRESS). But hey, why do we need one hub? Check the answer at Known issues.