-
Notifications
You must be signed in to change notification settings - Fork 0
/
cbor.js
206 lines (190 loc) · 5.16 KB
/
cbor.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
const cbor = require('borc')
const multihashes = require('multihashes')
const crypto = require('crypto')
const CID = require('cids')
const Block = require('ipfs-block')
const isCircular = require('is-circular')
const sha2 = b => crypto.createHash('sha256').update(b).digest()
const CID_CBOR_TAG = 42
/* start copy from exisisting dag-cbor */
function tagCID (cid) {
if (typeof cid === 'string') {
cid = new CID(cid).buffer
}
return new cbor.Tagged(CID_CBOR_TAG, Buffer.concat([
Buffer.from('00', 'hex'), // thanks jdag
cid
]))
}
function replaceCIDbyTAG (dagNode) {
let circular
try {
circular = isCircular(dagNode)
} catch (e) {
circular = false
}
if (circular) {
throw new Error('The object passed has circular references')
}
function transform (obj) {
if (!obj || Buffer.isBuffer(obj) || typeof obj === 'string') {
return obj
}
if (Array.isArray(obj)) {
return obj.map(transform)
}
const keys = Object.keys(obj)
// only `{'/': 'link'}` are valid
if (keys.length === 1 && keys[0] === '/') {
// Multiaddr encoding
// if (typeof link === 'string' && isMultiaddr(link)) {
// link = new Multiaddr(link).buffer
// }
return tagCID(obj['/'])
} else if (keys.length > 0) {
// Recursive transform
let out = {}
keys.forEach((key) => {
if (typeof obj[key] === 'object') {
out[key] = transform(obj[key])
} else {
out[key] = obj[key]
}
})
return out
} else {
return obj
}
}
return transform(dagNode)
}
/* end copy from existing dag-cbor */
const chunk = function * (buffer, size) {
let i = 0
yield buffer.slice(i, i + size)
while (i < buffer.length) {
i += size
yield buffer.slice(i, i + size)
}
}
const asBlock = (buffer, type) => {
let hash = multihashes.encode(sha2(buffer), 'sha2-256')
let cid = new CID(1, type, hash)
return new Block(buffer, cid)
}
class NotFound extends Error {
get code () {
return 404
}
}
class IPLD {
constructor (get, maxsize = 1e+7 /* 10megs */) {
this._get = get
this._maxBlockSize = 1e+6 // 1meg
this._maxSize = maxsize
this._decoder = new cbor.Decoder({
tags: {
[CID_CBOR_TAG]: (val) => {
val = val.slice(1)
return {'/': val}
}
},
size: maxsize
})
}
get multicodec () {
return 'dag-cbor'
}
_cid (buffer) {
let hash = multihashes.encode(sha2(buffer), 'sha2-256')
let cid = new CID(1, 'dag-cbor', hash)
return cid.toBaseEncodedString()
}
async cids (buffer) {
let self = this
return (function * () {
yield self._cid(buffer)
let root = self._deserialize(buffer)
if (root['._'] === 'dag-split') {
let cids = root.chunks.map(b => b['/'])
for (let cid of cids) {
yield cid
}
}
})()
// return [iterable of cids]
}
async resolve (buffer, path) {
if (!Array.isArray(path)) {
path = path.split('/').filter(x => x)
}
let root = await this.deserialize(buffer)
while (path.length) {
let prop = path.shift()
root = root[prop]
if (typeof root === 'undefined') {
throw NotFound(`Cannot find link "${prop}".`)
}
if (typeof root === 'object' && root['/']) {
let c = new CID(root['/'])
if (c.codec !== 'dag-cbor') {
return {value: c, remaining: path.join('/')}
}
let buff = await this._get(c.toBaseEncodedString())
return this.resolve(buff, path)
}
}
return {value: root, remaining: path.join('/')}
}
_deserialize (buffer) {
return this._decoder.decodeFirst(buffer)
}
_serialize (dagNode) {
let dagNodeTagged = replaceCIDbyTAG(dagNode)
return cbor.encode(dagNodeTagged)
}
serialize (dagNode) {
// TODO: handle large objects
let buffer = this._serialize(dagNode)
if (buffer.length > this._maxSize) {
throw new Error('cbor node is too large.')
}
let maxBlockSize = this._maxBlockSize
let _serialize = this._serialize
if (buffer.length > maxBlockSize) {
return (function * () {
let node = {'._': 'dag-split'}
node.chunks = []
for (let _chunk of chunk(buffer, maxBlockSize)) {
let block = asBlock(_chunk, 'raw')
yield block
node.chunks.push({'/': block.cid.toBaseEncodedString()})
}
yield asBlock(_serialize(node), 'dag-cbor')
})()
} else {
return [asBlock(buffer, 'dag-cbor')]
}
// return iterable of Blocks
}
async deserialize (buffer) {
let root = this._deserialize(buffer)
if (root['._'] === 'dag-split') {
let cids = root.chunks.map(b => {
return (new CID(b['/'])).toBaseEncodedString()
})
let blocks = cids.map(c => this._get(c))
let buffer = Buffer.concat(await Promise.all(blocks))
return this._deserialize(buffer)
} else {
return root
}
// return native type
}
async tree (buffer) {
// TODO: replaces streaming parsing for cbor using iterator.
return Object.keys(await this.deserialize(buffer))
// returns iterable of keys
}
}
module.exports = (get) => new IPLD(get)