This repository was archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathdaemon-node.js
96 lines (83 loc) · 2.31 KB
/
daemon-node.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// ordinarily we'd open a PR against the multicodec module to get our
// codec number added but since we're just testing we shim our new
// codec into the base-table.json file - this has to be done
// before requiring other modules as the int table will become read-only
const codecName = 'dag-test'
const codecNumber = 392091
const baseTable = require('multicodec/src/base-table.json')
baseTable[codecName] = codecNumber
// now require modules as usual
const IPFSDaemon = require('ipfs-cli/src/daemon')
const multihashing = require('multihashing-async')
const multihash = multihashing.multihash
const multicodec = require('multicodec')
const CID = require('cids')
const ipfsHttpClient = require('ipfs-http-client')
const uint8ArrayToString = require('uint8arrays/to-string')
async function main () {
// see https://github.com/ipld/interface-ipld-format for the interface definition
const format = {
codec: codecNumber,
defaultHashAlg: multicodec.SHA2_256,
util: {
serialize (data) {
return Buffer.from(JSON.stringify(data))
},
deserialize (buf) {
return JSON.parse(uint8ArrayToString(buf))
},
async cid (buf) {
const multihash = await multihashing(buf, format.defaultHashAlg)
return new CID(1, format.codec, multihash)
}
},
resolver: {
resolve: (buf, path) => {
return {
value: format.util.deserialize(buf),
remainderPath: path
}
}
}
}
// start an IPFS Daemon
const daemon = new IPFSDaemon({
ipld: {
formats: [
format
]
}
})
await daemon.start()
// in another process:
const client = ipfsHttpClient({
url: `http://localhost:${daemon._httpApi._apiServers[0].info.port}`,
ipld: {
formats: [
format
]
}
})
const data = {
hello: 'world'
}
const cid = await client.dag.put(data, {
format: codecName,
hashAlg: multihash.codes[format.defaultHashAlg]
})
console.info(`Put ${JSON.stringify(data)} = CID(${cid})`)
const {
value
} = await client.dag.get(cid)
console.info(`Get CID(${cid}) = ${JSON.stringify(value)}`)
await daemon.stop()
}
main()
.catch(err => {
console.error(err)
process.exit(1)
})
.then(() => {
// https://github.com/libp2p/js-libp2p/issues/779
process.exit(0)
})