This repository has been archived by the owner on Sep 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
index.js
363 lines (323 loc) · 9.14 KB
/
index.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
'use strict'
const mh = require('multihashes')
const multibase = require('multibase')
const multicodec = require('multicodec')
const CIDUtil = require('./cid-util')
const { concat: uint8ArrayConcat } = require('uint8arrays/concat')
const { toString: uint8ArrayToString } = require('uint8arrays/to-string')
const { equals: uint8ArrayEquals } = require('uint8arrays/equals')
const codecs = multicodec.nameToCode
const codecInts = /** @type {CodecName[]} */(Object.keys(codecs)).reduce((p, name) => {
p[codecs[name]] = name
return p
}, /** @type {Record<CodecCode, CodecName>} */({}))
const symbol = Symbol.for('@ipld/js-cid/CID')
/**
* @typedef {Object} SerializedCID
* @property {string} codec
* @property {number} version
* @property {Uint8Array} hash
*/
/**
* @typedef {0|1} CIDVersion
* @typedef {import('multibase').BaseNameOrCode} BaseNameOrCode
* @typedef {import('multicodec').CodecName} CodecName
* @typedef {import('multicodec').CodecCode} CodecCode
*/
/**
* Class representing a CID `<mbase><version><mcodec><mhash>`
* , as defined in [ipld/cid](https://github.com/multiformats/cid).
*
* @class CID
*/
class CID {
/**
* Create a new CID.
*
* The algorithm for argument input is roughly:
* ```
* if (cid)
* -> create a copy
* else if (str)
* if (1st char is on multibase table) -> CID String
* else -> bs58 encoded multihash
* else if (Uint8Array)
* if (1st byte is 0 or 1) -> CID
* else -> multihash
* else if (Number)
* -> construct CID by parts
* ```
*
* @param {CIDVersion | string | Uint8Array | CID} version
* @param {string|number} [codec]
* @param {Uint8Array} [multihash]
* @param {string} [multibaseName]
*
* @example
* new CID(<version>, <codec>, <multihash>, <multibaseName>)
* new CID(<cidStr>)
* new CID(<cid.bytes>)
* new CID(<multihash>)
* new CID(<bs58 encoded multihash>)
* new CID(<cid>)
*/
constructor (version, codec, multihash, multibaseName) {
// We have below three blank field accessors only because
// otherwise TS will not pick them up if done after assignemnts
/**
* The version of the CID.
*
* @type {CIDVersion}
*/
// eslint-disable-next-line no-unused-expressions
this.version
/**
* The codec of the CID.
*
* @deprecated
* @type {CodecName}
*/
// eslint-disable-next-line no-unused-expressions
this.codec
/**
* The multihash of the CID.
*
* @type {Uint8Array}
*/
// eslint-disable-next-line no-unused-expressions
this.multihash
Object.defineProperty(this, symbol, { value: true })
if (CID.isCID(version)) {
// version is an exising CID instance
const cid = /** @type {CID} */(version)
this.version = cid.version
this.codec = cid.codec
this.multihash = cid.multihash
// Default guard for when a CID < 0.7 is passed with no multibaseName
// @ts-ignore
this.multibaseName = cid.multibaseName || (cid.version === 0 ? 'base58btc' : 'base32')
return
}
if (typeof version === 'string') {
// e.g. 'base32' or false
const baseName = multibase.isEncoded(version)
if (baseName) {
// version is a CID String encoded with multibase, so v1
const cid = multibase.decode(version)
this.version = /** @type {CIDVersion} */(parseInt(cid[0].toString(), 16))
this.codec = multicodec.getCodec(cid.slice(1))
this.multihash = multicodec.rmPrefix(cid.slice(1))
this.multibaseName = baseName
} else {
// version is a base58btc string multihash, so v0
this.version = 0
this.codec = 'dag-pb'
this.multihash = mh.fromB58String(version)
this.multibaseName = 'base58btc'
}
CID.validateCID(this)
Object.defineProperty(this, 'string', { value: version })
return
}
if (version instanceof Uint8Array) {
const v = parseInt(version[0].toString(), 16)
if (v === 1) {
// version is a CID Uint8Array
const cid = version
this.version = v
this.codec = multicodec.getCodec(cid.slice(1))
this.multihash = multicodec.rmPrefix(cid.slice(1))
this.multibaseName = 'base32'
} else {
// version is a raw multihash Uint8Array, so v0
this.version = 0
this.codec = 'dag-pb'
this.multihash = version
this.multibaseName = 'base58btc'
}
CID.validateCID(this)
return
}
// otherwise, assemble the CID from the parameters
this.version = version
if (typeof codec === 'number') {
// @ts-ignore
codec = codecInts[codec]
}
this.codec = /** @type {CodecName} */ (codec)
this.multihash = /** @type {Uint8Array} */ (multihash)
/**
* Multibase name as string.
*
* @deprecated
* @type {string}
*/
this.multibaseName = multibaseName || (version === 0 ? 'base58btc' : 'base32')
CID.validateCID(this)
}
/**
* The CID as a `Uint8Array`
*
* @returns {Uint8Array}
*
*/
get bytes () {
// @ts-ignore
let bytes = this._bytes
if (!bytes) {
if (this.version === 0) {
bytes = this.multihash
} else if (this.version === 1) {
const codec = multicodec.getCodeVarint(this.codec)
bytes = uint8ArrayConcat([
[1], codec, this.multihash
], 1 + codec.byteLength + this.multihash.byteLength)
} else {
throw new Error('unsupported version')
}
// Cache this Uint8Array so it doesn't have to be recreated
Object.defineProperty(this, '_bytes', { value: bytes })
}
return bytes
}
/**
* The prefix of the CID.
*
* @returns {Uint8Array}
*/
get prefix () {
const codec = multicodec.getCodeVarint(this.codec)
const multihash = mh.prefix(this.multihash)
const prefix = uint8ArrayConcat([
[this.version], codec, multihash
], 1 + codec.byteLength + multihash.byteLength)
return prefix
}
/**
* The codec of the CID in its number form.
*
* @returns {CodecCode}
*/
get code () {
return codecs[this.codec]
}
/**
* Convert to a CID of version `0`.
*
* @returns {CID}
*/
toV0 () {
if (this.codec !== 'dag-pb') {
throw new Error('Cannot convert a non dag-pb CID to CIDv0')
}
const { name, length } = mh.decode(this.multihash)
if (name !== 'sha2-256') {
throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')
}
if (length !== 32) {
throw new Error('Cannot convert non 32 byte multihash CID to CIDv0')
}
return new CID(0, this.codec, this.multihash)
}
/**
* Convert to a CID of version `1`.
*
* @returns {CID}
*/
toV1 () {
return new CID(1, this.codec, this.multihash, this.multibaseName)
}
/**
* Encode the CID into a string.
*
* @param {BaseNameOrCode} [base=this.multibaseName] - Base encoding to use.
* @returns {string}
*/
toBaseEncodedString (base = this.multibaseName) {
// @ts-ignore non enumerable cache property
if (this.string && this.string.length !== 0 && base === this.multibaseName) {
// @ts-ignore non enumerable cache property
return this.string
}
let str
if (this.version === 0) {
if (base !== 'base58btc') {
throw new Error('not supported with CIDv0, to support different bases, please migrate the instance do CIDv1, you can do that through cid.toV1()')
}
str = mh.toB58String(this.multihash)
} else if (this.version === 1) {
str = uint8ArrayToString(multibase.encode(base, this.bytes))
} else {
throw new Error('unsupported version')
}
if (base === this.multibaseName) {
// cache the string value
Object.defineProperty(this, 'string', { value: str })
}
return str
}
/**
* CID(QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n)
*
* @returns {string}
*/
[Symbol.for('nodejs.util.inspect.custom')] () {
return 'CID(' + this.toString() + ')'
}
/**
* Encode the CID into a string.
*
* @param {BaseNameOrCode} [base=this.multibaseName] - Base encoding to use.
* @returns {string}
*/
toString (base) {
return this.toBaseEncodedString(base)
}
/**
* Serialize to a plain object.
*
* @returns {SerializedCID}
*/
toJSON () {
return {
codec: this.codec,
version: this.version,
hash: this.multihash
}
}
/**
* Compare equality with another CID.
*
* @param {CID} other
* @returns {boolean}
*/
equals (other) {
return this.codec === other.codec &&
this.version === other.version &&
uint8ArrayEquals(this.multihash, other.multihash)
}
/**
* Test if the given input is a valid CID object.
* Throws if it is not.
*
* @param {any} other - The other CID.
* @returns {void}
*/
static validateCID (other) {
const errorMsg = CIDUtil.checkCIDComponents(other)
if (errorMsg) {
throw new Error(errorMsg)
}
}
/**
* Check if object is a CID instance
*
* @param {any} value
* @returns {value is CID}
*/
static isCID (value) {
return value instanceof CID || Boolean(value && value[symbol])
}
}
CID.codecs = codecs
module.exports = CID