Skip to content

Instantly share code, notes, and snippets.

@ninabreznik
Last active August 26, 2020 14:52
Show Gist options
  • Save ninabreznik/4c105a13fc1266fb798f768c446b0e78 to your computer and use it in GitHub Desktop.
Save ninabreznik/4c105a13fc1266fb798f768c446b0e78 to your computer and use it in GitHub Desktop.
Read feed
const Hypercore = require('hypercore')
const reallyReady = require('hypercore-really-ready')
const ram = require('random-access-memory')
const hyperswarm = require('hyperswarm')
const swarm = hyperswarm()
const feedkey = '49ca10ed402f7385466c6dcea59a0169585765a289d972f0498cc6d200616637'
const swarmkey = 'b69ffcfbdc4dae9d9d8df33adec6f4386db41c292e62c9e0759e2950ea95fc05'
goReader(feedkey, swarmkey)
async function goReader (feedkey, swarmkey) {
await getData(feedkey, swarmkey)
}
function getData (feedkey, swarmkey) {
const key = Buffer.from(feedkey, 'hex')
const topic = Buffer.from(swarmkey, 'hex')
return new Promise(async (resolve, reject) => {
const feed = new Hypercore(ram, key)
const swarm = hyperswarm()
swarm.join(topic, { lookup: true })
swarm.on('connection',(socket, info) => {
console.log('Connected to the publisher')
socket.pipe(feed.replicate(info.client)).pipe(socket)
const data = []
const feedPubkey = feed.key
feed.rootHashes(feed.length - 1, (err, res) => {
if (err) return LOG(err) && reject(err)
const children = res.map(renameProperties)
feed.signature((err, { signature }) => {
if (err) LOG(err) && reject(err)
data.push(feedPubkey)
console.log('New data feed created', feedPubkey, feedPubkey.toString('hex'))
data.push({ hashType: 2, children }) // push TreeHashPayload
data.push(signature)
resolve(data)
})
})
})
})
function renameProperties (root) {
return { hash: root.hash, hash_number: root.index, total_length: root.size }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment