Compare commits

...

39 Commits

Author SHA1 Message Date
Steven Allen
3da5bbbe45 Merge pull request #92 from b5/chore_remove_gx
docs(readme): remove reference to gx
2019-12-09 06:47:25 -06:00
Steven Allen
9d598bbdbd Merge pull request #98 from ipfs/dependabot/go_modules/github.com/multiformats/go-multihash-0.0.10
Bump github.com/multiformats/go-multihash from 0.0.9 to 0.0.10
2019-12-09 06:24:09 -06:00
dependabot-preview[bot]
b420452400 Bump github.com/multiformats/go-multihash from 0.0.9 to 0.0.10
Bumps [github.com/multiformats/go-multihash](https://github.com/multiformats/go-multihash) from 0.0.9 to 0.0.10.
- [Release notes](https://github.com/multiformats/go-multihash/releases)
- [Commits](https://github.com/multiformats/go-multihash/compare/v0.0.9...v0.0.10)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-09 11:21:09 +00:00
Steven Allen
ed7dab1755 Merge pull request #97 from ipfs/fix/parse-panic
fix parsing issues and nits
2019-12-03 09:50:46 -05:00
Steven Allen
5df89959a0 test: test parsing non-sha256 hashes 2019-12-02 20:41:59 -05:00
Steven Allen
60ab0f84f0 chore: avoid magic numbers 2019-12-02 20:35:36 -05:00
Steven Allen
08e15f8a6c chore: avoid re-validated already validated CIDs 2019-12-02 20:35:27 -05:00
Steven Allen
58b483a841 fix: avoid panicing if we try to parse a non-sha multihash as a CIDv0
I'm pretty sure we never call `Parse` multihashes anyways, but we should be careful.
2019-12-02 20:34:30 -05:00
Whyrusleeping
79e75dffeb Merge pull request #95 from ipfs/feat/cid-from-bytes
Add a function to read a cid from an array of bytes
2019-11-12 10:17:18 +09:00
whyrusleeping
d93d4baeab add a simple test for reading cids from a buffer 2019-11-11 16:48:19 -08:00
whyrusleeping
cf8cf8856e Use optimized multihash method for parsing 2019-11-11 16:33:49 -08:00
Steven Allen
aa8072eeb5 Merge pull request #96 from ipfs/fix/verif-v0
Verify that prefix is correct v0 prefix
2019-11-11 11:29:02 -08:00
Jakub Sztandera
51871ccaa9 Disable gx builds
License: MIT
Signed-off-by: Jakub Sztandera <kubuxu@protocol.ai>
2019-11-11 20:04:40 +01:00
Jakub Sztandera
9238d1a533 Verify that prefix is correct v0 prefix
License: MIT
Signed-off-by: Jakub Sztandera <kubuxu@protocol.ai>
2019-11-11 20:00:31 +01:00
whyrusleeping
16bbe1cf14 Add a command to read a cid from an array of bytes 2019-11-10 22:17:41 -08:00
b5
c91a795815 docs(readme): remove reference to gx 2019-10-24 10:06:43 -04:00
Steven Allen
64acce09e1 Merge pull request #91 from ipfs/dependabot/go_modules/github.com/multiformats/go-multihash-0.0.8
Bump github.com/multiformats/go-multihash from 0.0.1 to 0.0.8
2019-09-24 16:11:26 -07:00
dependabot-preview[bot]
2a2f67d2c4 Bump github.com/multiformats/go-multihash from 0.0.1 to 0.0.8
Bumps [github.com/multiformats/go-multihash](https://github.com/multiformats/go-multihash) from 0.0.1 to 0.0.8.
- [Release notes](https://github.com/multiformats/go-multihash/releases)
- [Commits](https://github.com/multiformats/go-multihash/compare/v0.0.1...v0.0.8)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-09-24 23:01:51 +00:00
Steven Allen
86ca2a8300 Merge pull request #90 from ipfs/feat/lead-maintainer
doc: add a lead maintainer
2019-09-18 22:09:20 -07:00
Steven Allen
e0a778be45 doc: add a lead maintainer 2019-09-18 22:08:21 -07:00
Steven Allen
9bb7ea6920 Merge pull request #86 from lidel/feat/libp2p-key
Add support for libp2p-key multicodec to go-cid
2019-05-27 16:46:10 -07:00
Marcin Rataj
3f1777738f Add libp2p-key multicodec
Context: https://github.com/multiformats/multicodec/issues/130

License: MIT
Signed-off-by: Marcin Rataj <lidel@lidel.org>
2019-05-28 01:40:54 +02:00
Steven Allen
b1cc3e404d Merge pull request #85 from ipfs/feat/cidv1-default-base32
default cidv1 to base32
2019-05-13 10:54:14 -07:00
Steven Allen
b16425b966 make CID in readme base32 2019-05-10 09:41:01 -07:00
Steven Allen
f04f9216e7 default cidv1 to base32 2019-05-06 16:22:17 -07:00
Jakub Sztandera
e7e67e08cf Add gomod and travis 2019-02-28 18:32:58 +01:00
Steven Allen
29a66d1820 gx publish 0.9.3 2019-02-20 20:12:25 -08:00
Steven Allen
08f30d213e Merge pull request #84 from ipfs/fix/83
fix inline CIDs generated by Prefix.Sum
2019-02-20 20:11:24 -08:00
Steven Allen
cf3b4efcaf fix inline CIDs generated by Prefix.Sum 2019-02-20 19:06:04 -08:00
Hector Sanjuan
ca991e8eb6 Merge pull request #82 from ipfs/gx/0.9.2
gx publish 0.9.2
2019-02-20 16:21:43 +00:00
Hector Sanjuan
8d327b2f4b gx publish 0.9.2 2019-02-20 16:21:01 +00:00
Hector Sanjuan
14b828acf5 Merge pull request #81 from ipfs/feat/binary-marshaler
Let Cid implement Binary[Un]Marshaler and Text[Un]Marshaler interfaces.
2019-02-20 16:20:09 +00:00
Hector Sanjuan
00439572fb Let Cid implement Binary[Un]Marshaler and Text[Un]Marshaler interfaces.
This makes Cid implement https://golang.org/pkg/encoding/#BinaryMarshaler
which is used by go-codec to decide if things know how to serialize themselves
(currently we need do manual wrapping for anything containing a CID).

Since I was at it, I did the TextMarshaling one too.
2019-02-19 16:41:30 +00:00
Jakub Sztandera
37bf2f9503 Merge pull request #80 from madper/fix_typo
fix typo in comment
2019-02-15 18:30:48 +01:00
Madper Xie
e6d04f280e fix typo in comment 2019-02-15 20:19:46 +08:00
Steven Allen
033594dcd6 gx publish 0.9.1 2018-11-02 16:51:23 -07:00
Steven Allen
c9e99b39db Merge pull request #78 from samli88/dash-codecs
add codecs for Dash blocks, tx
2018-10-23 05:29:30 +01:00
Samuel Li
3ec3578fe9 add dash to codecs table 2018-10-07 11:44:18 -07:00
Samuel Li
628ab3426c add codecs for Dash blocks, tx 2018-10-07 11:21:41 -07:00
10 changed files with 353 additions and 84 deletions

View File

@@ -1 +1 @@
0.9.0: QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7 0.9.3: QmTbxNB1NwDesLmKTscr4udL2tVP7MaxvXnD1D9yX7g3PN

View File

@@ -1,24 +1,31 @@
sudo: false os:
- linux
language: go language: go
go: go:
- 'tip' - 1.11.x
env:
global:
- GOTFLAGS="-race"
matrix:
- BUILD_DEPTYPE=gomod
# disable travis install
install: install:
- go get github.com/whyrusleeping/gx - true
- go get github.com/whyrusleeping/gx-go
- gx install --global script:
script: - bash <(curl -s https://raw.githubusercontent.com/ipfs/ci-helpers/master/travis-ci/run-standard-tests.sh)
- gx test -v -race -coverprofile=coverage.txt -covermode=atomic .
after_success:
- bash <(curl -s https://codecov.io/bash)
cache: cache:
directories: directories:
- $GOPATH/src/gx - $GOPATH/src/gx
- $GOPATH/pkg/mod
- $HOME/.cache/go-build
notifications: notifications:
email: false email: false

View File

@@ -14,6 +14,9 @@ go-cid
This is an implementation in Go of the [CID spec](https://github.com/ipld/cid). This is an implementation in Go of the [CID spec](https://github.com/ipld/cid).
It is used in `go-ipfs` and related packages to refer to a typed hunk of data. It is used in `go-ipfs` and related packages to refer to a typed hunk of data.
## Lead Maintainer
[Eric Myhre](https://github.com/warpfork)
## Table of Contents ## Table of Contents
@@ -31,43 +34,23 @@ It is used in `go-ipfs` and related packages to refer to a typed hunk of data.
go get github.com/ipfs/go-cid go get github.com/ipfs/go-cid
``` ```
Note that `go-cid` is packaged with Gx, so it is recommended to use Gx to install and use it (see Usage section).
## Usage ## Usage
### Using Gx and Gx-go
This module is packaged with [Gx](https://github.com/whyrusleeping/gx). In order to use it in your own project it is recommended that you:
```sh
go get -u github.com/whyrusleeping/gx
go get -u github.com/whyrusleeping/gx-go
cd <your-project-repository>
gx init
gx import github.com/ipfs/go-cid
gx install --global
gx-go --rewrite
```
Please check [Gx](https://github.com/whyrusleeping/gx) and [Gx-go](https://github.com/whyrusleeping/gx-go) documentation for more information.
### Running tests ### Running tests
Before running tests, please run: Run tests with `go test` from the directory root
```sh ```sh
make deps go test
``` ```
This will make sure that dependencies are rewritten to known working versions.
### Examples ### Examples
#### Parsing string input from users #### Parsing string input from users
```go ```go
// Create a cid from a marshaled string // Create a cid from a marshaled string
c, err := cid.Decode("zdvgqEMYmNeH5fKciougvQcfzMcNjF3Z1tPouJ8C7pc3pe63k") c, err := cid.Decode("bafzbeigai3eoy2ccc7ybwjfz5r3rdxqrinwi4rwytly24tdbh6yk7zslrm")
if err != nil {...} if err != nil {...}
fmt.Println("Got CID: ", c) fmt.Println("Got CID: ", c)

View File

@@ -8,6 +8,7 @@ const (
DagProtobuf = 0x70 DagProtobuf = 0x70
DagCBOR = 0x71 DagCBOR = 0x71
Libp2pKey = 0x72
GitRaw = 0x78 GitRaw = 0x78
@@ -34,6 +35,7 @@ var Codecs = map[string]uint64{
"raw": Raw, "raw": Raw,
"protobuf": DagProtobuf, "protobuf": DagProtobuf,
"cbor": DagCBOR, "cbor": DagCBOR,
"libp2p-key": Libp2pKey,
"git-raw": GitRaw, "git-raw": GitRaw,
"eth-block": EthBlock, "eth-block": EthBlock,
"eth-block-list": EthBlockList, "eth-block-list": EthBlockList,
@@ -57,6 +59,7 @@ var CodecToStr = map[uint64]string{
Raw: "raw", Raw: "raw",
DagProtobuf: "protobuf", DagProtobuf: "protobuf",
DagCBOR: "cbor", DagCBOR: "cbor",
Libp2pKey: "libp2p-key",
GitRaw: "git-raw", GitRaw: "git-raw",
EthBlock: "eth-block", EthBlock: "eth-block",
EthBlockList: "eth-block-list", EthBlockList: "eth-block-list",

View File

@@ -38,7 +38,7 @@ func (p V0Builder) Sum(data []byte) (Cid, error) {
if err != nil { if err != nil {
return Undef, err return Undef, err
} }
return NewCidV0(hash), nil return Cid{string(hash)}, nil
} }
func (p V0Builder) GetCodec() uint64 { func (p V0Builder) GetCodec() uint64 {

153
cid.go
View File

@@ -21,6 +21,7 @@ package cid
import ( import (
"bytes" "bytes"
"encoding"
"encoding/binary" "encoding/binary"
"encoding/json" "encoding/json"
"errors" "errors"
@@ -61,6 +62,7 @@ const (
DagProtobuf = 0x70 DagProtobuf = 0x70
DagCBOR = 0x71 DagCBOR = 0x71
Libp2pKey = 0x72
GitRaw = 0x78 GitRaw = 0x78
@@ -79,6 +81,8 @@ const (
ZcashTx = 0xc1 ZcashTx = 0xc1
DecredBlock = 0xe0 DecredBlock = 0xe0
DecredTx = 0xe1 DecredTx = 0xe1
DashBlock = 0xf0
DashTx = 0xf1
) )
// Codecs maps the name of a codec to its type // Codecs maps the name of a codec to its type
@@ -87,6 +91,7 @@ var Codecs = map[string]uint64{
"raw": Raw, "raw": Raw,
"protobuf": DagProtobuf, "protobuf": DagProtobuf,
"cbor": DagCBOR, "cbor": DagCBOR,
"libp2p-key": Libp2pKey,
"git-raw": GitRaw, "git-raw": GitRaw,
"eth-block": EthBlock, "eth-block": EthBlock,
"eth-block-list": EthBlockList, "eth-block-list": EthBlockList,
@@ -103,6 +108,8 @@ var Codecs = map[string]uint64{
"zcash-tx": ZcashTx, "zcash-tx": ZcashTx,
"decred-block": DecredBlock, "decred-block": DecredBlock,
"decred-tx": DecredTx, "decred-tx": DecredTx,
"dash-block": DashBlock,
"dash-tx": DashTx,
} }
// CodecToStr maps the numeric codec to its name // CodecToStr maps the numeric codec to its name
@@ -126,27 +133,43 @@ var CodecToStr = map[uint64]string{
ZcashTx: "zcash-tx", ZcashTx: "zcash-tx",
DecredBlock: "decred-block", DecredBlock: "decred-block",
DecredTx: "decred-tx", DecredTx: "decred-tx",
DashBlock: "dash-block",
DashTx: "dash-tx",
}
// tryNewCidV0 tries to convert a multihash into a CIDv0 CID and returns an
// error on failure.
func tryNewCidV0(mhash mh.Multihash) (Cid, error) {
// Need to make sure hash is valid for CidV0 otherwise we will
// incorrectly detect it as CidV1 in the Version() method
dec, err := mh.Decode(mhash)
if err != nil {
return Undef, err
}
if dec.Code != mh.SHA2_256 || dec.Length != 32 {
return Undef, fmt.Errorf("invalid hash for cidv0 %d-%d", dec.Code, dec.Length)
}
return Cid{string(mhash)}, nil
} }
// NewCidV0 returns a Cid-wrapped multihash. // NewCidV0 returns a Cid-wrapped multihash.
// They exist to allow IPFS to work with Cids while keeping // They exist to allow IPFS to work with Cids while keeping
// compatibility with the plain-multihash format used used in IPFS. // compatibility with the plain-multihash format used used in IPFS.
// NewCidV1 should be used preferentially. // NewCidV1 should be used preferentially.
//
// Panics if the multihash isn't sha2-256.
func NewCidV0(mhash mh.Multihash) Cid { func NewCidV0(mhash mh.Multihash) Cid {
// Need to make sure hash is valid for CidV0 otherwise we will c, err := tryNewCidV0(mhash)
// incorrectly detect it as CidV1 in the Version() method
dec, err := mh.Decode(mhash)
if err != nil { if err != nil {
panic(err) panic(err)
} }
if dec.Code != mh.SHA2_256 || dec.Length != 32 { return c
panic("invalid hash for cidv0")
}
return Cid{string(mhash)}
} }
// NewCidV1 returns a new Cid using the given multicodec-packed // NewCidV1 returns a new Cid using the given multicodec-packed
// content type. // content type.
//
// Panics if the multihash is invalid.
func NewCidV1(codecType uint64, mhash mh.Multihash) Cid { func NewCidV1(codecType uint64, mhash mh.Multihash) Cid {
hashlen := len(mhash) hashlen := len(mhash)
// two 8 bytes (max) numbers plus hash // two 8 bytes (max) numbers plus hash
@@ -161,7 +184,12 @@ func NewCidV1(codecType uint64, mhash mh.Multihash) Cid {
return Cid{string(buf[:n+hashlen])} return Cid{string(buf[:n+hashlen])}
} }
// Cid represents a self-describing content adressed var _ encoding.BinaryMarshaler = Cid{}
var _ encoding.BinaryUnmarshaler = (*Cid)(nil)
var _ encoding.TextMarshaler = Cid{}
var _ encoding.TextUnmarshaler = (*Cid)(nil)
// Cid represents a self-describing content addressed
// identifier. It is formed by a Version, a Codec (which indicates // identifier. It is formed by a Version, a Codec (which indicates
// a multicodec-packed content type) and a Multihash. // a multicodec-packed content type) and a Multihash.
type Cid struct{ str string } type Cid struct{ str string }
@@ -189,7 +217,7 @@ func Parse(v interface{}) (Cid, error) {
case []byte: case []byte:
return Cast(v2) return Cast(v2)
case mh.Multihash: case mh.Multihash:
return NewCidV0(v2), nil return tryNewCidV0(v2)
case Cid: case Cid:
return v2, nil return v2, nil
default: default:
@@ -220,7 +248,7 @@ func Decode(v string) (Cid, error) {
return Undef, err return Undef, err
} }
return NewCidV0(hash), nil return tryNewCidV0(hash)
} }
_, data, err := mbase.Decode(v) _, data, err := mbase.Decode(v)
@@ -276,36 +304,38 @@ func uvError(read int) error {
// Please use decode when parsing a regular Cid string, as Cast does not // Please use decode when parsing a regular Cid string, as Cast does not
// expect multibase-encoded data. Cast accepts the output of Cid.Bytes(). // expect multibase-encoded data. Cast accepts the output of Cid.Bytes().
func Cast(data []byte) (Cid, error) { func Cast(data []byte) (Cid, error) {
if len(data) == 34 && data[0] == 18 && data[1] == 32 { nr, c, err := CidFromBytes(data)
h, err := mh.Cast(data)
if err != nil { if err != nil {
return Undef, err return Undef, err
} }
return NewCidV0(h), nil if nr != len(data) {
return Undef, fmt.Errorf("trailing bytes in data buffer passed to cid Cast")
} }
vers, n := binary.Uvarint(data) return c, nil
if err := uvError(n); err != nil {
return Undef, err
} }
if vers != 1 { // UnmarshalBinary is equivalent to Cast(). It implements the
return Undef, fmt.Errorf("expected 1 as the cid version number, got: %d", vers) // encoding.BinaryUnmarshaler interface.
} func (c *Cid) UnmarshalBinary(data []byte) error {
casted, err := Cast(data)
_, cn := binary.Uvarint(data[n:])
if err := uvError(cn); err != nil {
return Undef, err
}
rest := data[n+cn:]
h, err := mh.Cast(rest)
if err != nil { if err != nil {
return Undef, err return err
}
c.str = casted.str
return nil
} }
return Cid{string(data[0 : n+cn+len(h)])}, nil // UnmarshalText is equivalent to Decode(). It implements the
// encoding.TextUnmarshaler interface.
func (c *Cid) UnmarshalText(text []byte) error {
decodedCid, err := Decode(string(text))
if err != nil {
return err
}
c.str = decodedCid.str
return nil
} }
// Version returns the Cid version. // Version returns the Cid version.
@@ -334,7 +364,7 @@ func (c Cid) String() string {
case 0: case 0:
return c.Hash().B58String() return c.Hash().B58String()
case 1: case 1:
mbstr, err := mbase.Encode(mbase.Base58BTC, c.Bytes()) mbstr, err := mbase.Encode(mbase.Base32, c.Bytes())
if err != nil { if err != nil {
panic("should not error with hardcoded mbase: " + err.Error()) panic("should not error with hardcoded mbase: " + err.Error())
} }
@@ -398,6 +428,18 @@ func (c Cid) Bytes() []byte {
return []byte(c.str) return []byte(c.str)
} }
// MarshalBinary is equivalent to Bytes(). It implements the
// encoding.BinaryMarshaler interface.
func (c Cid) MarshalBinary() ([]byte, error) {
return c.Bytes(), nil
}
// MarshalText is equivalent to String(). It implements the
// encoding.TextMarshaler interface.
func (c Cid) MarshalText() ([]byte, error) {
return []byte(c.String()), nil
}
// Equals checks that two Cids are the same. // Equals checks that two Cids are the same.
// In order for two Cids to be considered equal, the // In order for two Cids to be considered equal, the
// Version, the Codec and the Multihash must match. // Version, the Codec and the Multihash must match.
@@ -490,7 +532,18 @@ type Prefix struct {
// Sum uses the information in a prefix to perform a multihash.Sum() // Sum uses the information in a prefix to perform a multihash.Sum()
// and return a newly constructed Cid with the resulting multihash. // and return a newly constructed Cid with the resulting multihash.
func (p Prefix) Sum(data []byte) (Cid, error) { func (p Prefix) Sum(data []byte) (Cid, error) {
hash, err := mh.Sum(data, p.MhType, p.MhLength) length := p.MhLength
if p.MhType == mh.ID {
length = -1
}
if p.Version == 0 && (p.MhType != mh.SHA2_256 ||
(p.MhLength != 32 && p.MhLength != -1)) {
return Undef, fmt.Errorf("invalid v0 prefix")
}
hash, err := mh.Sum(data, p.MhType, length)
if err != nil { if err != nil {
return Undef, err return Undef, err
} }
@@ -548,3 +601,41 @@ func PrefixFromBytes(buf []byte) (Prefix, error) {
MhLength: int(mhlen), MhLength: int(mhlen),
}, nil }, nil
} }
func CidFromBytes(data []byte) (int, Cid, error) {
if len(data) > 2 && data[0] == mh.SHA2_256 && data[1] == 32 {
if len(data) < 34 {
return 0, Undef, fmt.Errorf("not enough bytes for cid v0")
}
h, err := mh.Cast(data[:34])
if err != nil {
return 0, Undef, err
}
return 34, Cid{string(h)}, nil
}
vers, n := binary.Uvarint(data)
if err := uvError(n); err != nil {
return 0, Undef, err
}
if vers != 1 {
return 0, Undef, fmt.Errorf("expected 1 as the cid version number, got: %d", vers)
}
_, cn := binary.Uvarint(data[n:])
if err := uvError(cn); err != nil {
return 0, Undef, err
}
mhnr, _, err := mh.MHFromBytes(data[n+cn:])
if err != nil {
return 0, Undef, err
}
l := n + cn + mhnr
return l, Cid{string(data[0:l])}, nil
}

View File

@@ -19,6 +19,7 @@ var tCodecs = map[uint64]string{
Raw: "raw", Raw: "raw",
DagProtobuf: "protobuf", DagProtobuf: "protobuf",
DagCBOR: "cbor", DagCBOR: "cbor",
Libp2pKey: "libp2p-key",
GitRaw: "git-raw", GitRaw: "git-raw",
EthBlock: "eth-block", EthBlock: "eth-block",
EthBlockList: "eth-block-list", EthBlockList: "eth-block-list",
@@ -35,6 +36,8 @@ var tCodecs = map[uint64]string{
ZcashTx: "zcash-tx", ZcashTx: "zcash-tx",
DecredBlock: "decred-block", DecredBlock: "decred-block",
DecredTx: "decred-tx", DecredTx: "decred-tx",
DashBlock: "dash-block",
DashTx: "dash-tx",
} }
func assertEqual(t *testing.T, a, b Cid) { func assertEqual(t *testing.T, a, b Cid) {
@@ -71,6 +74,34 @@ func TestTableForV0(t *testing.T) {
} }
} }
func TestPrefixSum(t *testing.T) {
// Test creating CIDs both manually and with Prefix.
// Tests: https://github.com/ipfs/go-cid/issues/83
for _, hashfun := range []uint64{
mh.ID, mh.SHA3, mh.SHA2_256,
} {
h1, err := mh.Sum([]byte("TEST"), hashfun, -1)
if err != nil {
t.Fatal(err)
}
c1 := NewCidV1(Raw, h1)
h2, err := mh.Sum([]byte("foobar"), hashfun, -1)
if err != nil {
t.Fatal(err)
}
c2 := NewCidV1(Raw, h2)
c3, err := c1.Prefix().Sum([]byte("foobar"))
if err != nil {
t.Fatal(err)
}
if !c2.Equals(c3) {
t.Fatal("expected CIDs to be equal")
}
}
}
func TestBasicMarshaling(t *testing.T) { func TestBasicMarshaling(t *testing.T) {
h, err := mh.Sum([]byte("TEST"), mh.SHA3, 4) h, err := mh.Sum([]byte("TEST"), mh.SHA3, 4)
if err != nil { if err != nil {
@@ -156,6 +187,44 @@ func TestBasesMarshaling(t *testing.T) {
} }
} }
func TestBinaryMarshaling(t *testing.T) {
data := []byte("this is some test content")
hash, _ := mh.Sum(data, mh.SHA2_256, -1)
c := NewCidV1(DagCBOR, hash)
var c2 Cid
data, err := c.MarshalBinary()
if err != nil {
t.Fatal(err)
}
err = c2.UnmarshalBinary(data)
if err != nil {
t.Fatal(err)
}
if !c.Equals(c2) {
t.Errorf("cids should be the same: %s %s", c, c2)
}
}
func TestTextMarshaling(t *testing.T) {
data := []byte("this is some test content")
hash, _ := mh.Sum(data, mh.SHA2_256, -1)
c := NewCidV1(DagCBOR, hash)
var c2 Cid
data, err := c.MarshalText()
if err != nil {
t.Fatal(err)
}
err = c2.UnmarshalText(data)
if err != nil {
t.Fatal(err)
}
if !c.Equals(c2) {
t.Errorf("cids should be the same: %s %s", c, c2)
}
}
func TestEmptyString(t *testing.T) { func TestEmptyString(t *testing.T) {
_, err := Decode("") _, err := Decode("")
if err == nil { if err == nil {
@@ -264,6 +333,41 @@ func TestNewPrefixV0(t *testing.T) {
if c1.Prefix() != c2.Prefix() { if c1.Prefix() != c2.Prefix() {
t.Fatal("prefixes mismatch") t.Fatal("prefixes mismatch")
} }
}
func TestInvalidV0Prefix(t *testing.T) {
tests := []Prefix{
{
MhType: mh.SHA2_256,
MhLength: 31,
},
{
MhType: mh.SHA2_256,
MhLength: 33,
},
{
MhType: mh.SHA2_256,
MhLength: -2,
},
{
MhType: mh.SHA2_512,
MhLength: 32,
},
{
MhType: mh.SHA2_512,
MhLength: -1,
},
}
for i, p := range tests {
t.Log(i)
_, err := p.Sum([]byte("testdata"))
if err == nil {
t.Fatalf("should error (index %d)", i)
}
}
} }
func TestPrefixRoundtrip(t *testing.T) { func TestPrefixRoundtrip(t *testing.T) {
@@ -370,13 +474,13 @@ func TestHexDecode(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
if c.String() != "zb2rhhFAEMepUBbGyP1k8tGfz7BSciKXP6GHuUeUsJBaK6cqG" { if c.String() != "bafkreie5qrjvaw64n4tjm6hbnm7fnqvcssfed4whsjqxzslbd3jwhsk3mm" {
t.Fatal("hash value failed to round trip decoding from hex") t.Fatal("hash value failed to round trip decoding from hex")
} }
} }
func ExampleDecode() { func ExampleDecode() {
encoded := "zb2rhhFAEMepUBbGyP1k8tGfz7BSciKXP6GHuUeUsJBaK6cqG" encoded := "bafkreie5qrjvaw64n4tjm6hbnm7fnqvcssfed4whsjqxzslbd3jwhsk3mm"
c, err := Decode(encoded) c, err := Decode(encoded)
if err != nil { if err != nil {
fmt.Printf("Error: %s", err) fmt.Printf("Error: %s", err)
@@ -384,11 +488,11 @@ func ExampleDecode() {
} }
fmt.Println(c) fmt.Println(c)
// Output: zb2rhhFAEMepUBbGyP1k8tGfz7BSciKXP6GHuUeUsJBaK6cqG // Output: bafkreie5qrjvaw64n4tjm6hbnm7fnqvcssfed4whsjqxzslbd3jwhsk3mm
} }
func TestFromJson(t *testing.T) { func TestFromJson(t *testing.T) {
cval := "zb2rhhFAEMepUBbGyP1k8tGfz7BSciKXP6GHuUeUsJBaK6cqG" cval := "bafkreie5qrjvaw64n4tjm6hbnm7fnqvcssfed4whsjqxzslbd3jwhsk3mm"
jsoncid := []byte(`{"/":"` + cval + `"}`) jsoncid := []byte(`{"/":"` + cval + `"}`)
var c Cid var c Cid
err := json.Unmarshal(jsoncid, &c) err := json.Unmarshal(jsoncid, &c)
@@ -402,7 +506,7 @@ func TestFromJson(t *testing.T) {
} }
func TestJsonRoundTrip(t *testing.T) { func TestJsonRoundTrip(t *testing.T) {
exp, err := Decode("zb2rhhFAEMepUBbGyP1k8tGfz7BSciKXP6GHuUeUsJBaK6cqG") exp, err := Decode("bafkreie5qrjvaw64n4tjm6hbnm7fnqvcssfed4whsjqxzslbd3jwhsk3mm")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -446,3 +550,48 @@ func BenchmarkStringV1(b *testing.B) {
b.FailNow() b.FailNow()
} }
} }
func TestReadCidsFromBuffer(t *testing.T) {
cidstr := []string{
"bafkreie5qrjvaw64n4tjm6hbnm7fnqvcssfed4whsjqxzslbd3jwhsk3mm",
"Qmf5Qzp6nGBku7CEn2UQx4mgN8TW69YUok36DrGa6NN893",
"zb2rhZi1JR4eNc2jBGaRYJKYM8JEB4ovenym8L1CmFsRAytkz",
}
var cids []Cid
var buf []byte
for _, cs := range cidstr {
c, err := Decode(cs)
if err != nil {
t.Fatal(err)
}
cids = append(cids, c)
buf = append(buf, c.Bytes()...)
}
var cur int
for _, expc := range cids {
n, c, err := CidFromBytes(buf[cur:])
if err != nil {
t.Fatal(err)
}
if c != expc {
t.Fatal("cids mismatched")
}
cur += n
}
if cur != len(buf) {
t.Fatal("had trailing bytes")
}
}
func TestBadParse(t *testing.T) {
hash, err := mh.Sum([]byte("foobar"), mh.SHA3_256, -1)
if err != nil {
t.Fatal(err)
}
_, err = Parse(hash)
if err == nil {
t.Fatal("expected to fail to parse an invalid CIDv1 CID")
}
}

8
go.mod Normal file
View File

@@ -0,0 +1,8 @@
module github.com/ipfs/go-cid
require (
github.com/multiformats/go-multibase v0.0.1
github.com/multiformats/go-multihash v0.0.10
)
go 1.13

28
go.sum Normal file
View File

@@ -0,0 +1,28 @@
github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1 h1:lYpkrQH5ajf0OXOcUbGjvZxxijuBwbbmlSxLiuofa+g=
github.com/minio/blake2b-simd v0.0.0-20160723061019-3f5f724cb5b1/go.mod h1:pD8RvIylQ358TN4wwqatJ8rNavkEINozVn9DtGI3dfQ=
github.com/minio/sha256-simd v0.1.1-0.20190913151208-6de447530771 h1:MHkK1uRtFbVqvAgvWxafZe54+5uBxLluGylDiKgdhwo=
github.com/minio/sha256-simd v0.1.1-0.20190913151208-6de447530771/go.mod h1:B5e1o+1/KgNmWrSQK08Y6Z1Vb5pwIktudl0J58iy0KM=
github.com/mr-tron/base58 v1.1.0 h1:Y51FGVJ91WBqCEabAi5OPUz38eAx8DakuAm5svLcsfQ=
github.com/mr-tron/base58 v1.1.0/go.mod h1:xcD2VGqlgYjBdcBLw+TuYLr8afG+Hj8g2eTVqeSzSU8=
github.com/mr-tron/base58 v1.1.2 h1:ZEw4I2EgPKDJ2iEw0cNmLB3ROrEmkOtXIkaG7wZg+78=
github.com/mr-tron/base58 v1.1.2/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc=
github.com/multiformats/go-base32 v0.0.3 h1:tw5+NhuwaOjJCC5Pp82QuXbrmLzWg7uxlMFp8Nq/kkI=
github.com/multiformats/go-base32 v0.0.3/go.mod h1:pLiuGC8y0QR3Ue4Zug5UzK9LjgbkL8NSQj0zQ5Nz/AA=
github.com/multiformats/go-multibase v0.0.1 h1:PN9/v21eLywrFWdFNsFKaU04kLJzuYzmrJR+ubhT9qA=
github.com/multiformats/go-multibase v0.0.1/go.mod h1:bja2MqRZ3ggyXtZSEDKpl0uO/gviWFaSteVbWT51qgs=
github.com/multiformats/go-multihash v0.0.8 h1:wrYcW5yxSi3dU07n5jnuS5PrNwyHy0zRHGVoUugWvXg=
github.com/multiformats/go-multihash v0.0.8/go.mod h1:YSLudS+Pi8NHE7o6tb3D8vrpKa63epEDmG8nTduyAew=
github.com/multiformats/go-multihash v0.0.9 h1:aoijQXYYl7Xtb2pUUP68R+ys1TlnlR3eX6wmozr0Hp4=
github.com/multiformats/go-multihash v0.0.9/go.mod h1:YSLudS+Pi8NHE7o6tb3D8vrpKa63epEDmG8nTduyAew=
github.com/multiformats/go-multihash v0.0.10 h1:lMoNbh2Ssd9PUF74Nz008KGzGPlfeV6wH3rit5IIGCM=
github.com/multiformats/go-multihash v0.0.10/go.mod h1:YSLudS+Pi8NHE7o6tb3D8vrpKa63epEDmG8nTduyAew=
github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI=
github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8 h1:1wopBVtVdWnn03fZelqdXTqk7U7zPQCb+T4rbU9ZEoU=
golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=

View File

@@ -9,9 +9,9 @@
"gxDependencies": [ "gxDependencies": [
{ {
"author": "whyrusleeping", "author": "whyrusleeping",
"hash": "QmPnFwZ2JXKnXgMw8CdBPxn7FWh6LLdjUjxV1fKHuJnkr8", "hash": "QmerPMzPk1mJVowm8KgmoknWa4yCYvvugMPsgWmDNUvDLW",
"name": "go-multihash", "name": "go-multihash",
"version": "1.0.8" "version": "1.0.9"
}, },
{ {
"author": "whyrusleeping", "author": "whyrusleeping",
@@ -25,6 +25,6 @@
"license": "MIT", "license": "MIT",
"name": "go-cid", "name": "go-cid",
"releaseCmd": "git commit -a -m \"gx publish $VERSION\"", "releaseCmd": "git commit -a -m \"gx publish $VERSION\"",
"version": "0.9.0" "version": "0.9.3"
} }