如何从头开始计算CID?

huangapple go评论144阅读模式
英文:

How do I compute a CID from scratch?

问题

为了测试目的,我需要能够在Go中生成一个(正式)有效的CID,即一个假的CID!该函数可以接收一系列字节、内容类型、CID版本等参数。
我尝试通过查看代码库来理解CID是如何构建的,但是我无法找到正确的方法。

英文:

For testing purposes, I need to be able to generate a (formally) valid CID in Go, i.e., a fake CID! The function could be given a sequence of bytes, the content type, CID version, etc.
I tried understanding how the CID is built by digging the codebase but couldn't really find my way through it.

答案1

得分: 1

有点不确定你所说的“内容类型”是什么意思,因为我认为IPFS并不关心,但看起来你可能需要使用go-cid

从头创建CID

  1. import (
  2. cid "github.com/ipfs/go-cid"
  3. mc "github.com/multiformats/go-multicodec"
  4. mh "github.com/multiformats/go-multihash"
  5. )
  6. // 通过指定“prefix”参数手动创建CID
  7. pref := cid.Prefix{
  8. Version: 1,
  9. Codec: mc.Raw,
  10. MhType: mh.SHA2_256,
  11. MhLength: -1, // 默认长度
  12. }
  13. // 然后提供一些数据
  14. c, err := pref.Sum([]byte("Hello World!"))
  15. if err != nil {...}
  16. fmt.Println("Created CID: ", c)
英文:

A bit unsure of what you mean by "content type" as I don't believe IPFS cares but it looks like go-cid is what you want:

> ## Creating a CID from scratch
> go
> import (
> cid "github.com/ipfs/go-cid"
> mc "github.com/multiformats/go-multicodec"
> mh "github.com/multiformats/go-multihash"
> )
>
> // Create a cid manually by specifying the 'prefix' parameters
> pref := cid.Prefix{
> Version: 1,
> Codec: mc.Raw,
> MhType: mh.SHA2_256,
> MhLength: -1, // default length
> }
>
> // And then feed it some data
> c, err := pref.Sum([]byte("Hello World!"))
> if err != nil {...}
>
> fmt.Println("Created CID: ", c)
>

huangapple
  • 本文由 发表于 2022年7月12日 17:04:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/72949681.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定