-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcid_dag_metadata.js
More file actions
70 lines (59 loc) · 2.08 KB
/
cid_dag_metadata.js
File metadata and controls
70 lines (59 loc) · 2.08 KB
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
import * as multihash from 'multiformats/hashes/digest';
import { getContentHash } from './common.js';
import { CID } from 'multiformats/cid';
import * as dagPB from '@ipld/dag-pb';
import { UnixFS } from 'ipfs-unixfs';
/**
* Build a UnixFS DAG-PB file node from raw chunks.
*
* (By default with SHA2 multihash)
*/
export async function buildUnixFSDagPB(chunks, mhCode = 0x12) {
if (!chunks?.length) {
throw new Error('❌ buildUnixFSDag: chunks[] is empty')
}
// UnixFS blockSizes = sizes of child blocks (must be BigInt for ipfs-unixfs v11+)
const blockSizes = chunks.map(c => BigInt(c.len))
console.log(`🧩 Building UnixFS DAG from chunks:
• totalChunks: ${chunks.length}
• blockSizes: ${blockSizes.join(', ')}`)
// Build UnixFS file metadata (no inline data here)
const fileData = new UnixFS({
type: 'file',
blockSizes
})
// DAG-PB node: our file with chunk links (Tsize must be regular number for dag-pb)
const dagNode = dagPB.prepare({
Data: fileData.marshal(),
Links: chunks.map(c => ({
Name: '',
Tsize: Number(c.len),
Hash: c.cid
}))
})
// Encode DAG-PB
const dagBytes = dagPB.encode(dagNode)
// Hash DAG to produce CIDv1
const rootCid = await cidFromBytes(dagBytes, dagPB.code, mhCode)
console.log(`✅ DAG root CID: ${rootCid.toString()}`)
return { rootCid, dagBytes }
}
/**
* Create CID for data.
* Default to `0x55 (raw)` with blake2b_256 hash.
*
* 0xb220:
* - 0xb2 = the multihash algorithm family for BLAKE2b
* - 0x20 = the digest length in bytes (32 bytes = 256 bits)
*
* See: https://github.com/multiformats/multicodec/blob/master/table.csv
*/
export async function cidFromBytes(bytes, cidCodec = 0x55, mhCode = 0xb220) {
console.log(`[CID]: Using cidCodec: ${cidCodec} and mhCode: ${mhCode}`);
const mh = multihash.create(mhCode, getContentHash(bytes, mhCode));
return CID.createV1(cidCodec, mh);
}
export function convertCid(cid, cidCodec) {
const mh = cid.multihash;
return CID.createV1(cidCodec, mh);
}