The following code is in draft. It generates a random file. Then it calculates the expected cid and compares this with the output of putFile, which returns a cid upon execution. The cid comparison outputs an error, indicating the expected and actual cids differ.
package main
import (
"crypto/rand"
"fmt"
"io/ioutil"
"os"
"testing"
cid "github.com/ipfs/go-cid"
mh "github.com/multiformats/go-multihash"
"github.com/web3-storage/go-w3s-client"
)
func TestPutFile(t *testing.T) {
client, err := w3s.NewClient(
w3s.WithEndpoint("https://api.web3.storage"),
w3s.WithToken(testToken),
)
if err != nil {
t.Fatalf("error creating client: %v", err)
}
fileContent := make([]byte, 1024)
if _, err := rand.Read(fileContent); err != nil {
t.Fatalf("error generating random bytes: %v", err)
}
file, err := ioutil.TempFile("", "")
if err != nil {
t.Fatalf("error creating temp file: %v", err)
}
defer file.Close()
defer os.Remove(file.Name())
if _, err := file.Write(fileContent); err != nil {
t.Fatalf("error writing to file: %v", err)
}
fileBytes, err := ioutil.ReadFile(file.Name())
if err != nil {
t.Fatalf("error reading file: %v", err)
}
// calculate predicted CID
// codec 0x70 is dag-pb
pref := cid.Prefix{
Version: 1,
Codec: uint64(0x70),
MhType: mh.SHA2_256,
MhLength: -1,
}
calculatedCid, err := pref.Sum(fileContent)
if err != nil {
t.Fatalf("error calculating CID: %v", err)
}
// validation that file content and file bytes are the same
fmt.Printf("fileContent length: %d, first few elements: % x\n", len(fileContent), fileContent[:10])
fmt.Printf("file length: %d, first few elements: % x\n", len(fileBytes), fileBytes[:10])
// putFile takes in args of type fs.File, NOT the bytes of the file
actualCid := putFile(client, file)
if !calculatedCid.Equals(actualCid) {
t.Fatalf(`unmatching cids
expected CID: %s
actual CID: %s`, calculatedCid, actualCid,
)
}
}
fileContent length: 1024, first few elements: 27 25 bc be 8c f5 66 15 a8 6b
file length: 1024, first few elements: 27 25 bc be 8c f5 66 15 a8 6b
Uploading to IPFS via web3.storage...
CID: bafybeidk2alhga7fztbtiyult7hsawnfhawtspy5a6xzzvjtaxavvfn2fm
--- FAIL: TestPutFile (1.09s)
ipfs_test.go:77: unmatching cids
expected CID: bafybeieqzyhpmacugzcn7mrh6pth6xakrxxudvbn3l5kvdtderadua27wy
actual CID: bafybeidk2alhga7fztbtiyult7hsawnfhawtspy5a6xzzvjtaxavvfn2fm
Current hypothesis is that w3s.Put function modifies the file before pinning. CID references below, where the Multihash digests differ in spite of the file contents being identical as shown above.