CodeSampleX

Exemple

github.com/cespare/xxhash/v2 v2.1.2: Digest, New, Sum64

Échantillon vérifié pour golang github.com/cespare/xxhash/v2 v2.1.2: Digest, New, Sum64. Le contrat s'est exécuté sur go 1.26 · linux alpine/x64 · docker et…

sha256:eeb605ba7281687aae3b447556012c7d48d0dee6c3aaf2c97fc17e4daa68346e

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 go

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-28

Cas

HOW
Objectif
verify pkg:golang/github.com/cespare/xxhash/v2@v2.1.2
Paquets
Symboles
  • Digest
  • New
  • Sum64
  • Sum64String
Créé
2026-08-28T00:41:59Z

Contrat

  1. Sum64 calculates 64-bit xxHash checksum for byte slices deterministically
  2. Sum64String calculates 64-bit xxHash checksum for string matching Sum64 on equivalent byte slice
  3. New creates Digest implementing hash.Hash64 that computes matching checksum via Write and Sum64
  4. Digest WriteString computes checksum without extra byte allocation matching Write
  5. Digest Reset clears internal state allowing reuse for independent checksum calculations
  6. Digest Sum appends 8-byte big-endian representation of Sum64 to provided byte slice
  7. Digest MarshalBinary and UnmarshalBinary preserve and restore internal accumulator state across writes

Fichiers

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.go

Télécharger l’artefact source (tar.gz)

Code source

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify pkg:golang/github.com/cespare/xxhash/v2@v2.1.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/cespare/xxhash/v2@v2.1.2
Demonstrate these symbols/APIs:
  - Digest
  - New
  - Sum64
  - Sum64String

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:640ffae6e1fc21242cb5229277a08ca59613999759eebcda5bdb4f0688445fe5","contract":["Sum64 calculates 64-bit xxHash checksum for byte slices deterministically","Sum64String calculates 64-bit xxHash checksum for string matching Sum64 on equivalent byte slice","New creates Digest implementing hash.Hash64 that computes matching checksum via Write and Sum64","Digest WriteString computes checksum without extra byte allocation matching Write","Digest Reset clears internal state allowing reuse for independent checksum calculations","Digest Sum appends 8-byte big-endian representation of Sum64 to provided byte slice","Digest MarshalBinary and UnmarshalBinary preserve and restore internal accumulator state across writes"],"goal":"verify pkg:golang/github.com/cespare/xxhash/v2@v2.1.2","kind":"HOW","packages":["pkg:golang/github.com/cespare/xxhash/v2@v2.1.2"],"schemaVersion":1,"symbols":["Digest","New","Sum64","Sum64String"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/cespare/xxhash/v2@v2.1.2"],"schemaVersion":1,"subject":"pkg:golang/github.com/cespare/xxhash/v2@v2.1.2","symbols":["Digest","New","Sum64","Sum64String"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.26.6

require github.com/cespare/xxhash/v2 v2.1.2 // indirect
go.sum
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
main.go
package main

import (
	"fmt"
	"io"
	"strings"

	"github.com/cespare/xxhash/v2"
)

// StreamHasher wraps an xxhash.Digest for computing hashes over streams and strings.
type StreamHasher struct {
	hasher *xxhash.Digest
}

// NewStreamHasher creates a new StreamHasher instance.
func NewStreamHasher() *StreamHasher {
	return &StreamHasher{
		hasher: xxhash.New(),
	}
}

// HashReader computes the 64-bit xxHash checksum of an io.Reader stream.
func (s *StreamHasher) HashReader(r io.Reader) (uint64, error) {
	s.hasher.Reset()
	if _, err := io.Copy(s.hasher, r); err != nil {
		return 0, err
	}
	return s.hasher.Sum64(), nil
}

// HashString computes the 64-bit xxHash checksum using WriteString.
func (s *StreamHasher) HashString(str string) (uint64, error) {
	s.hasher.Reset()
	if _, err := s.hasher.WriteString(str); err != nil {
		return 0, err
	}
	return s.hasher.Sum64(), nil
}

func main() {
	input := "quick brown fox jumps over the lazy dog"

	// 1. Direct one-shot slice hashing
	hSlice := xxhash.Sum64([]byte(input))
	fmt.Printf("Sum64: %016x\n", hSlice)

	// 2. Direct string hashing
	hString := xxhash.Sum64String(input)
	fmt.Printf("Sum64String: %016x\n", hString)

	// 3. Streaming hasher
	hasher := NewStreamHasher()
	reader := strings.NewReader(input)
	hStream, err := hasher.HashReader(reader)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}
	fmt.Printf("Stream hash: %016x\n", hStream)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/cespare/xxhash/v2@v2.1.2",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/cespare/xxhash/v2@v2.1.2"
  ],
  "symbols": [
    "Digest",
    "New",
    "Sum64",
    "Sum64String"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"os"

	"github.com/cespare/xxhash/v2"
)

func main() {
	// Contract 1: Sum64 calculates 64-bit xxHash checksum for byte slices deterministically
	{
		data1 := []byte("xxhash deterministic byte slice test payload")
		data2 := []byte("xxhash deterministic byte slice test payload")
		data3 := []byte("different payload content")

		h1 := xxhash.Sum64(data1)
		h2 := xxhash.Sum64(data2)
		h3 := xxhash.Sum64(data3)

		if h1 == 0 {
			fmt.Fprintf(os.Stderr, "FAIL: expected non-zero checksum for non-empty input\n")
			os.Exit(1)
		}
		if h1 != h2 {
			fmt.Fprintf(os.Stderr, "FAIL: Sum64 is not deterministic: %x != %x\n", h1, h2)
			os.Exit(1)
		}
		if h1 == h3 {
			fmt.Fprintf(os.Stderr, "FAIL: Sum64 collision on different inputs: %x == %x\n", h1, h3)
			os.Exit(1)
		}
	}

	// Contract 2: Sum64String calculates 64-bit xxHash checksum for string matching Sum64 on equivalent byte slice
	{
		str := "sample string for checksum comparison"
		hStr := xxhash.Sum64String(str)
		hSlice := xxhash.Sum64([]byte(str))

		if hStr != hSlice {
			fmt.Fprintf(os.Stderr, "FAIL: Sum64String (%x) != Sum64 (%x)\n", hStr, hSlice)
			os.Exit(1)
		}

		emptyStr := ""
		if xxhash.Sum64String(emptyStr) != xxhash.Sum64([]byte{}) {
			fmt.Fprintf(os.Stderr, "FAIL: empty string hash mismatch\n")
			os.Exit(1)
		}
	}

	// Contract 3: New creates Digest implementing hash.Hash64 that computes matching checksum via Write and Sum64
	{
		d := xxhash.New()
		if d.Size() != 8 {
			fmt.Fprintf(os.Stderr, "FAIL: Digest.Size() = %d, expected 8\n", d.Size())
			os.Exit(1)
		}
		if d.BlockSize() != 32 {
			fmt.Fprintf(os.Stderr, "FAIL: Digest.BlockSize() = %d, expected 32\n", d.BlockSize())
			os.Exit(1)
		}

		payload := []byte("stream hashing multi-chunk test data stream")
		n, err := d.Write(payload)
		if err != nil || n != len(payload) {
			fmt.Fprintf(os.Stderr, "FAIL: Write returned err=%v, n=%d, expected %d\n", err, n, len(payload))
			os.Exit(1)
		}

		expected := xxhash.Sum64(payload)
		got := d.Sum64()
		if got != expected {
			fmt.Fprintf(os.Stderr, "FAIL: Digest.Sum64() = %x, expected %x\n", got, expected)
			os.Exit(1)
		}
	}

	// Contract 4: Digest WriteString computes checksum without extra byte allocation matching Write
	{
		str := "testing xxhash WriteString direct equivalence"
		d1 := xxhash.New()
		n, err := d1.WriteString(str)
		if err != nil || n != len(str) {
			fmt.Fprintf(os.Stderr, "FAIL: WriteString returned err=%v, n=%d\n", err, n)
			os.Exit(1)
		}

		d2 := xxhash.New()
		_, _ = d2.Write([]byte(str))

		if d1.Sum64() != d2.Sum64() {
			fmt.Fprintf(os.Stderr, "FAIL: WriteString hash (%x) != Write hash (%x)\n", d1.Sum64(), d2.Sum64())
			os.Exit(1)
		}
	}

	// Contract 5: Digest Reset clears internal state allowing reuse for independent checksum calculations
	{
		d := xxhash.New()
		_, _ = d.WriteString("initial stream data to be discarded")
		_ = d.Sum64()

		d.Reset()

		fresh := xxhash.New()
		if d.Sum64() != fresh.Sum64() {
			fmt.Fprintf(os.Stderr, "FAIL: Reset hash %x != fresh hash %x\n", d.Sum64(), fresh.Sum64())
			os.Exit(1)
		}

		payload := "new independent stream payload after reset"
		_, _ = d.WriteString(payload)
		_, _ = fresh.WriteString(payload)

		if d.Sum64() != fresh.Sum64() {
			fmt.Fprintf(os.Stderr, "FAIL: hash after reset %x != fresh %x\n", d.Sum64(), fresh.Sum64())
			os.Exit(1)
		}
	}

	// Contract 6: Digest Sum appends 8-byte big-endian representation of Sum64 to provided byte slice
	{
		d := xxhash.New()
		_, _ = d.WriteString("serialization verification payload")
		sum64 := d.Sum64()

		prefix := []byte("header:")
		out := d.Sum(prefix)

		if len(out) != len(prefix)+8 {
			fmt.Fprintf(os.Stderr, "FAIL: expected length %d, got %d\n", len(prefix)+8, len(out))
			os.Exit(1)
		}

		if !bytes.Equal(out[:len(prefix)], prefix) {
			fmt.Fprintf(os.Stderr, "FAIL: prefix was modified in Sum output\n")
			os.Exit(1)
		}

		appended := binary.BigEndian.Uint64(out[len(prefix):])
		if appended != sum64 {
			fmt.Fprintf(os.Stderr, "FAIL: Sum appended %x, expected %x\n", appended, sum64)
			os.Exit(1)
		}
	}

	// Contract 7: Digest MarshalBinary and UnmarshalBinary preserve and restore internal accumulator state across writes
	{
		chunk1 := []byte("first chunk of multipart stream, ")
		chunk2 := []byte("second chunk of multipart stream.")

		d1 := xxhash.New()
		_, _ = d1.Write(chunk1)

		state, err := d1.MarshalBinary()
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: MarshalBinary error: %v\n", err)
			os.Exit(1)
		}

		d2 := xxhash.New()
		if err := d2.UnmarshalBinary(state); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: UnmarshalBinary error: %v\n", err)
			os.Exit(1)
		}

		_, _ = d1.Write(chunk2)
		_, _ = d2.Write(chunk2)

		if d1.Sum64() != d2.Sum64() {
			fmt.Fprintf(os.Stderr, "FAIL: restored digest hash %x != original %x\n", d2.Sum64(), d1.Sum64())
			os.Exit(1)
		}
	}

	fmt.Println("PASS: github.com/cespare/xxhash/v2 contract passed")
}

Seeder d'origine

anonyme