Skip to content

Instantly share code, notes, and snippets.

@ninabreznik
Last active November 30, 2019 12:55
Show Gist options
  • Save ninabreznik/41a78963e9e425419a7ad70ed3c018fd to your computer and use it in GitHub Desktop.
Save ninabreznik/41a78963e9e425419a7ad70ed3c018fd to your computer and use it in GitHub Desktop.
const hypercore = require('hypercore')
const hypertrie = require('hypertrie')
const ram = require('random-access-memory')
const { ClientSwarm } = require('hyperswarm-ws')
const eos = require('end-of-stream')
const dat = 'e7cc14d1f92fc7058d5fc5d5ad6ce450f7b1d9ea67154dbd20ab91b59d9f1104'
const swarm = new ClientSwarm('ws://localhost:4200')
start(dat)
function start (dat) {
const key = Buffer.from(dat, "hex")
const feed = new hypercore(ram, key)
const trie = hypertrie(null, { feed })
swarm.join(key, { live: true })
swarm.on('connection', (connection, info) => {
console.log('connection found')
connection.pipe(feed.replicate(info.client)).pipe(connection)
})
trie.ready(() => {
console.log('Loaded trie', dat)
reallyReady(trie, () => {
console.log('READY')
viewTrie()
})
})
function viewTrie () {
const query = 'foo'
trie.get(query, (err, res) => {
console.log('Query', query)
console.log('Response', res.value.toString('utf8'))
})
}
function reallyReady (trie, cb) {
if (trie.feed.peers.length) {
trie.feed.update({ ifAvailable: true }, cb)
} else {
trie.feed.once('peer-add', () => {
trie.feed.update({ ifAvailable: true }, cb)
})
}
}
}
const hypertrie = require('hypertrie')
const ram = require('random-access-memory')
const replicate = require('@hyperswarm/replicator')
const hyperswarm = require('hyperswarm')
const eos = require('end-of-stream')
const trie = hypertrie(ram)
const swarm = hyperswarm()
trie.ready(() => {
storeToTrie()
swarm.join(trie.key, {
live: true,
lookup: true, // find & connect to peers
announce: true // optional- announce self as a connection target
})
swarm.on('connection', (connection, info) => {
console.log('new connection!', info)
connection.pipe(trie.feed.replicate(info.client)).pipe(connection)
})
})
function viewTrie () {
trie.list('', (err, results) => {
if(err) return log('Error reading from trie', err.message)
for(let {key, value} of results) {
console.log('key:', key, 'value:', Buffer.from(value).toString('utf8'))
}
})
}
function storeToTrie () {
const key = 'foo'
const value = 'bar'
trie.put(key, value, (err) => {
if (err) console.log('Error writing', err.message)
else console.log('wrote', key, '-', value)
console.log(trie.key.toString('hex'))
viewTrie()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment