CodeSampleX

示例

google.golang.org/protobuf v1.36.10

已验证示例 — golang google.golang.org/protobuf v1.36.10. contract 在 go 1.26 · linux alpine/x64 · docker 上运行并通过: protojson.MarshalOptions with Multiline and Indent…

sha256:42ed15717532a65a5a1275da13378eb001c1ee1993ead8fc285d7aa9f2c2bf3b

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 go

验证运行环境

环境 契约 阶段 运行日期
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-27

案例

HOW
目标
verify pkg:golang/google.golang.org/protobuf@v1.36.10
包
创建时间
2026-08-27T20:40:35Z

契约

  1. protojson.MarshalOptions with Multiline and Indent formats JSON output with consistent indentation
  2. protojson.UnmarshalOptions with DiscardUnknown permits decoding JSON payloads containing unknown fields without error
  3. fieldmaskpb.FieldMask encodes to comma-separated camelCase paths in JSON and decodes back to snake_case field paths
  4. anypb.Any serializes to JSON with @type URL and polymorphic message body, and UnmarshalNew restores the original message
  5. proto.MarshalOptions with Deterministic produces identical byte slices across multiple marshal operations with matching proto.Size

文件

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

下载源代码构件 (tar.gz)

源代码

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/google.golang.org/protobuf@v1.36.10
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.36.10
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:b3c898446a4857ee0884a117ae98103551c5d8b3df58c2d24adb2820fe4ffb6a","contract":["protojson.MarshalOptions with Multiline and Indent formats JSON output with consistent indentation","protojson.UnmarshalOptions with DiscardUnknown permits decoding JSON payloads containing unknown fields without error","fieldmaskpb.FieldMask encodes to comma-separated camelCase paths in JSON and decodes back to snake_case field paths","anypb.Any serializes to JSON with @type URL and polymorphic message body, and UnmarshalNew restores the original message","proto.MarshalOptions with Deterministic produces identical byte slices across multiple marshal operations with matching proto.Size"],"goal":"verify pkg:golang/google.golang.org/protobuf@v1.36.10","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.36.10"],"schemaVersion":1},"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/google.golang.org/protobuf@v1.36.10"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.36.10","verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.26.6

require google.golang.org/protobuf v1.36.10
go.sum
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
main.go
package main

import (
	"fmt"
	"time"

	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/anypb"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
	"google.golang.org/protobuf/types/known/structpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// DocumentRecord encapsulates a dynamic data structure with metadata and masking support.
type DocumentRecord struct {
	Body      *structpb.Struct
	Mask      *fieldmaskpb.FieldMask
	Extension *anypb.Any
}

// NewDocumentRecord creates a DocumentRecord from Go map data and field mask paths.
func NewDocumentRecord(data map[string]any, paths []string, extension proto.Message) (*DocumentRecord, error) {
	st, err := structpb.NewStruct(data)
	if err != nil {
		return nil, fmt.Errorf("failed to create structpb: %w", err)
	}

	fm := &fieldmaskpb.FieldMask{Paths: paths}

	var extAny *anypb.Any
	if extension != nil {
		extAny, err = anypb.New(extension)
		if err != nil {
			return nil, fmt.Errorf("failed to create anypb: %w", err)
		}
	}

	return &DocumentRecord{
		Body:      st,
		Mask:      fm,
		Extension: extAny,
	}, nil
}

// FormatPrettyJSON marshals a protobuf message with 2-space indentation.
func FormatPrettyJSON(m proto.Message) ([]byte, error) {
	opts := protojson.MarshalOptions{
		Multiline: true,
		Indent:    "  ",
	}
	return opts.Marshal(m)
}

// ParsePermissiveJSON unmarshals a JSON payload ignoring unknown fields.
func ParsePermissiveJSON(data []byte, target proto.Message) error {
	opts := protojson.UnmarshalOptions{
		DiscardUnknown: true,
	}
	return opts.Unmarshal(data, target)
}

func main() {
	now := timestamppb.New(time.Now())
	rec, err := NewDocumentRecord(
		map[string]any{"title": "System Audit", "level": float64(3)},
		[]string{"user_id", "audit_log.timestamp"},
		now,
	)
	if err != nil {
		fmt.Printf("Error creating record: %v\n", err)
		return
	}

	prettyBytes, err := FormatPrettyJSON(rec.Body)
	if err != nil {
		fmt.Printf("JSON format error: %v\n", err)
		return
	}
	fmt.Printf("Indented body:\n%s\n", string(prettyBytes))

	fmBytes, err := protojson.Marshal(rec.Mask)
	if err != nil {
		fmt.Printf("FieldMask JSON error: %v\n", err)
		return
	}
	fmt.Printf("FieldMask JSON representation: %s\n", string(fmBytes))
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/google.golang.org/protobuf@v1.36.10",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.36.10"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.go
package main

import (
	"bytes"
	"fmt"
	"os"
	"strings"
	"time"

	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/anypb"
	"google.golang.org/protobuf/types/known/emptypb"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
	"google.golang.org/protobuf/types/known/structpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

func main() {
	// Assertion 1: protojson.MarshalOptions with Multiline and Indent formats JSON output with consistent indentation
	{
		st, err := structpb.NewStruct(map[string]any{
			"service_name": "gateway",
			"active":       true,
			"port":         float64(8080),
		})
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: structpb.NewStruct error: %v\n", err)
			os.Exit(1)
		}

		opts := protojson.MarshalOptions{
			Multiline: true,
			Indent:    "  ",
		}
		formatted, err := opts.Marshal(st)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: protojson.MarshalOptions.Marshal error: %v\n", err)
			os.Exit(1)
		}

		out := string(formatted)
		if !strings.HasPrefix(out, "{\n  \"") {
			fmt.Fprintf(os.Stderr, "FAIL: output missing expected multi-line opening format: %q\n", out)
			os.Exit(1)
		}
		if !strings.Contains(out, "\n  \"active\":") || !strings.Contains(out, "\n  \"port\":") {
			fmt.Fprintf(os.Stderr, "FAIL: output missing 2-space indented fields: %q\n", out)
			os.Exit(1)
		}
		if !strings.HasSuffix(out, "\n}") {
			fmt.Fprintf(os.Stderr, "FAIL: output missing expected multi-line closing format: %q\n", out)
			os.Exit(1)
		}
	}

	// Assertion 2: protojson.UnmarshalOptions with DiscardUnknown permits decoding JSON payloads containing unknown fields without error
	{
		rawJSON := `{"unrecognized_extra_key": 9999}`

		uoStrict := protojson.UnmarshalOptions{
			DiscardUnknown: false,
		}
		var emptyStrict emptypb.Empty
		if err := uoStrict.Unmarshal([]byte(rawJSON), &emptyStrict); err == nil {
			fmt.Fprintf(os.Stderr, "FAIL: expected error when DiscardUnknown is false, got nil\n")
			os.Exit(1)
		}

		uoPermissive := protojson.UnmarshalOptions{
			DiscardUnknown: true,
		}
		var emptyPermissive emptypb.Empty
		if err := uoPermissive.Unmarshal([]byte(rawJSON), &emptyPermissive); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: unexpected error with DiscardUnknown true: %v\n", err)
			os.Exit(1)
		}
	}

	// Assertion 3: fieldmaskpb.FieldMask encodes to comma-separated camelCase paths in JSON and decodes back to snake_case field paths
	{
		fm := &fieldmaskpb.FieldMask{
			Paths: []string{"user_id", "user_profile.first_name", "account_settings.is_active"},
		}

		jsonBytes, err := protojson.Marshal(fm)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: fieldmask marshal failed: %v\n", err)
			os.Exit(1)
		}

		expectedJSON := `"userId,userProfile.firstName,accountSettings.isActive"`
		if string(jsonBytes) != expectedJSON {
			fmt.Fprintf(os.Stderr, "FAIL: expected JSON %s, got %s\n", expectedJSON, string(jsonBytes))
			os.Exit(1)
		}

		var decodedFM fieldmaskpb.FieldMask
		if err := protojson.Unmarshal(jsonBytes, &decodedFM); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: fieldmask unmarshal failed: %v\n", err)
			os.Exit(1)
		}

		if len(decodedFM.Paths) != 3 ||
			decodedFM.Paths[0] != "user_id" ||
			decodedFM.Paths[1] != "user_profile.first_name" ||
			decodedFM.Paths[2] != "account_settings.is_active" {
			fmt.Fprintf(os.Stderr, "FAIL: decoded paths do not match snake_case originals: %v\n", decodedFM.Paths)
			os.Exit(1)
		}
	}

	// Assertion 4: anypb.Any serializes to JSON with @type URL and polymorphic message body, and UnmarshalNew restores the original message
	{
		originalTs := timestamppb.New(time.Date(2026, 8, 27, 20, 30, 0, 0, time.UTC))
		anyMsg, err := anypb.New(originalTs)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb.New error: %v\n", err)
			os.Exit(1)
		}

		anyJSON, err := protojson.Marshal(anyMsg)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb protojson marshal error: %v\n", err)
			os.Exit(1)
		}

		if !strings.Contains(string(anyJSON), `"@type":"type.googleapis.com/google.protobuf.Timestamp"`) {
			fmt.Fprintf(os.Stderr, "FAIL: anypb JSON missing expected @type identifier: %s\n", string(anyJSON))
			os.Exit(1)
		}

		var decodedAny anypb.Any
		if err := protojson.Unmarshal(anyJSON, &decodedAny); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: anypb protojson unmarshal error: %v\n", err)
			os.Exit(1)
		}

		unpackedMsg, err := decodedAny.UnmarshalNew()
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: UnmarshalNew failed: %v\n", err)
			os.Exit(1)
		}

		unpackedTs, ok := unpackedMsg.(*timestamppb.Timestamp)
		if !ok {
			fmt.Fprintf(os.Stderr, "FAIL: expected *timestamppb.Timestamp, got %T\n", unpackedMsg)
			os.Exit(1)
		}

		if !proto.Equal(originalTs, unpackedTs) {
			fmt.Fprintf(os.Stderr, "FAIL: unpacked Timestamp does not equal original\n")
			os.Exit(1)
		}
	}

	// Assertion 5: proto.MarshalOptions with Deterministic produces identical byte slices across multiple marshal operations with matching proto.Size
	{
		st, err := structpb.NewStruct(map[string]any{
			"alpha": "value_a",
			"gamma": "value_g",
			"beta":  "value_b",
			"delta": "value_d",
		})
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: structpb.NewStruct error: %v\n", err)
			os.Exit(1)
		}

		expectedSize := proto.Size(st)
		if expectedSize <= 0 {
			fmt.Fprintf(os.Stderr, "FAIL: proto.Size returned %d\n", expectedSize)
			os.Exit(1)
		}

		detOpts := proto.MarshalOptions{Deterministic: true}
		b1, err := detOpts.Marshal(st)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: deterministic marshal 1 failed: %v\n", err)
			os.Exit(1)
		}

		b2, err := detOpts.Marshal(st)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: deterministic marshal 2 failed: %v\n", err)
			os.Exit(1)
		}

		if !bytes.Equal(b1, b2) {
			fmt.Fprintf(os.Stderr, "FAIL: deterministic marshal outputs differ across runs\n")
			os.Exit(1)
		}

		if len(b1) != expectedSize {
			fmt.Fprintf(os.Stderr, "FAIL: marshaled bytes len (%d) does not match proto.Size (%d)\n", len(b1), expectedSize)
			os.Exit(1)
		}
	}

	fmt.Println("PASS: google.golang.org/protobuf contract passed")
}

原始种子者

匿名