Skip to content

Instantly share code, notes, and snippets.

@amtoine
Last active January 12, 2023 09:44
Show Gist options
  • Save amtoine/69c8be3dd38ec75afb86da78210c524d to your computer and use it in GitHub Desktop.
Save amtoine/69c8be3dd38ec75afb86da78210c524d to your computer and use it in GitHub Desktop.
The JS source from "Juan Benet: Enter the Merkle Forest" (https://youtu.be/Bqs_LzBjQyk)
/*
* Construction of the blocks with IPLD
*/
var ipld = require('ipld')
var obj1 = { "data": "Hello " }
var obj1Data = ipld.marshal(obj1)
var obj1Hash = ipld.multihash(obj1Data)
> obj1Data.toString('base64')
oWRkYXRhZkhlbGxvIA==
> obj1Hash
QmUUuaD...Z88Bg
var obj2 = { "data": "World\n" }
var obj2Data = ipld.marshal(obj2)
var obj2Hash = ipld.multihash(obj2Data)
> obj2Hash
QmSVuc2...ydAHV
var obj3 = {
"file": [
{ "/": "QmUUuaD...Z88Bg" },
{ "/": "QmSVuc2...ydAHV" },
]
}
var obj3Data = ipld.marshal(obj3)
var obj3Hash = ipld.multihash(obj3Data)
> obj3Hash
QmdhMzs...FcAhw
/*
* Adding the block to an IPFS node
*/
var ipfs = require('ipfs')
ipfs.add(obj1)
ipfs.add(obj2)
ipfs.add(obj3)
/*
* Getting the blocks from the IPFS P2P network
*/
> ipfs.resolve("QmUUuaD...Z88Bg")
{ "data": "Hello " }
> ipfs.resolve("QmSVuc2...ydAHV")
{ "data": "World\n" }
> ipfs.resolve("QmUUuaD...Z88Bg/data")
"Hello "
> ipfs.resolve("QmSVuc2...ydAHV/data")
"World\n"
> ipfs.resolve("QmdhMzs...FcAhw")
{
"file": [
{ "/": "QmUUuaD...Z88Bg" },
{ "/": "QmSVuc2...ydAHV" },
]
}
> ipfs.resolve("QmdhMzs...FcAhw/files/0")
{ "data": "Hello " }
> ipfs.resolve("QmdhMzs...FcAhw/files/1")
{ "data": "World\n" }
> ipfs.resolve("QmdhMzs...FcAhw/files/0/data")
"Hello "
> ipfs.resolve("QmdhMzs...FcAhw/files/1/data")
"World\n"
/*
* Creating a pseudo file system in a few lines
*/
// {
// "data": "content".
// "files": [
// <link>,
// <link>,
// <link>,
// ...
// ]
// }
function catFile(link) {
var obj = ipfs.resolve(link)
var out = obj.data || ""
for (var file of (obj.files || [])) {
out += catFile(file)
}
return out
}
> catFile("QmUUuaD...Z88Bg")
"Hello "
> catFile("QmSVuc2...ydAHV")
"World\n"
> catFile("QmdhMzs...FcAhw")
"Hello World\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment