How recreate a hash digest of a multihash in IPFS

前端 未结 3 913
猫巷女王i
猫巷女王i 2021-01-12 20:24

Assuming I\'m adding data to IPFS like this:

$ echo Hello World | ipfs add

This will give me QmWATWQ7fVPP2EFGu71UkfnqhYXDYH566qy47CnJ

3条回答
  •  逝去的感伤
    2021-01-12 20:48

    According to Steven's answer, using protobuf is working. Here is the full code of my approach.

    ipfs.proto

    syntax = "proto3";
    
    message PBNode {
    bytes Data = 1;
    }
    
    message PBLink {
    bytes Hash = 1;
    string Name = 2;
    uint64 Tsize = 3;
    }
    
    message Data {
    enum DataType {
        Raw = 0;
        Directory = 1;
        File = 2;
        Metadata = 3;
        Symlink = 4;
        HAMTShard = 5;
    }
    DataType Type = 1;
    bytes Data = 2;
    }
    

    cid.js

    const mh = require('multihashes');
    const axios = require('axios');
    const crypto = require('crypto');
    const protobuf = require("protobufjs");
    const IPFS = protobuf.loadSync('./ipfs.proto').lookupType('PBNode');
    
    class CID {
    /**
    * convert IPFS multihash to sha2-256 hash string
    * @param {string} multihash
    * @param {boolean} prefix
    * @returns {string} sha2-256 hash string starting with 0x
    */
    static toHash(multihash, prefix = false) {
        return prefix ? '0x' : ''
        + mh.decode(mh.fromB58String(multihash)).digest.toString('hex')
    }
    
    /**
    * convert sha2-256 hash string to IPFS multihash
    * @param {string} str
    * @returns {string} IPFS multihash starting with Qm
    */
    static fromHash(str) {
        str = str.startsWith('0x') ? str.slice(2) : str;
        return mh.toB58String(mh.encode(Buffer.from(str, 'hex'), 'sha2-256'))
    }
    
    /**
    * hash the buffer and get the SHA256 result compatible with IPFS multihash
    * @param {Buffer} buf
    * @returns {string}
    */
    static hash(buf) {
        const r = IPFS.encode({
        Data: {
            Type: 2,
            Data: buf,
            filesize: buf.length
        }
    
        }).finish();
        return crypto.createHash('sha256').update(r).digest('hex');
    }
    }
    
    async function ipfsGet(cid) {
    const x = await axios.get(`http://your.address.xxx/ipfs/${cid}`, {
        responseType: 'arraybuffer'
    });
    return Buffer.from(x.data);
    }
    
    const r = "QmfQj4DUWEudeFdWKVzPaTbYimdYzsp14DZX1VLV1BbtdN";
    const hashFromCID = CID.toHash(r);
    console.log(hashFromCID);
    ipfsGet(r).then(buf => {
    const hashCalculated = CID.hash(buf);
    console.log(hashCalculated);
    console.log(hashCalculated === hashFromCID);
    console.log(CID.fromHash(hashCalculated) === r)
    });
    
    module.exports = CID;

提交回复
热议问题