Replicate & persist
In the HyperDHT How-to (Connect Two Peers) and the Hyperswarm How-to (Connect Many Peers), peers can exchange chat messages so long as both are online at the same time and directly connected. The application is ephemeral, the messages are not persisted - they will be lost if the recipient is offline. Hypercore provides the persistence.
Hypercore
is a secure, distributed append-only log. It is built for sharing enormous datasets and streams of real-time data. It has a secure transport protocol, making it easy to build fast and scalable peer-to-peer applications.
Build with Pear - Episode 05: Replication and Persistence
In this guide we'll extend the ephemeral chat example in Connect Many Peers but using Hypercore to add many significant new features:
Persistence: The owner of the Hypercore can add messages at any time, and they'll be persisted to disk. Whenever they come online, readers can replicate these messages over Hyperswarm.
Many Readers: New messages added to the Hypercore will be broadcast to interested readers. The owner gives each reader a reading capability (
core.key
) and a corresponding discovery key (core.discoveryKey
). The former is used to authorize the reader, ensuring that they have permission to read messages, and the latter is used to discover the owner (and other readers) on the swarm.
The following example consists of two Pear Terminal Applications: reader-app
and writer-app
. When these two applications are opened, two peers are created and connected to each other. A Hypercore is used to store the data entered into the command line.
The writer-app
code stores the data entered into the command line to the Hypercore instance. The Hypercore instance is replicated with other peers using Hyperswarm.
Create the writer-app
project with these commands:
Alter the generated writer-app/index.js
file to the following:
The reader-app
uses Hyperswarm to connect to the previously initiated peer and synchronize the local Hypercore instance with the Hypercore instance of the writer.
Create the reader-app
project with these commands:
Alter the generated reader-app/index.js
file to the following:
In one terminal, open writer-app
with pear run --dev .
.
The writer-app
will output the Hypercore key.
In another terminal, open the reader-app
and pass it the key:
As inputs are made to the terminal running the writer application, outputs should be shown in the terminal running the reader application.
Last updated