Search code examples
goipfs

How do I compute a CID from scratch?


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.


Solution

  • 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

    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)