英文:
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
import (
cid "github.com/ipfs/go-cid"
mc "github.com/multiformats/go-multicodec"
mh "github.com/multiformats/go-multihash"
)
// 通过指定“prefix”参数手动创建CID
pref := cid.Prefix{
Version: 1,
Codec: mc.Raw,
MhType: mh.SHA2_256,
MhLength: -1, // 默认长度
}
// 然后提供一些数据
c, err := pref.Sum([]byte("Hello World!"))
if err != nil {...}
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)
>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论