api

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 29, 2026 License: MIT Imports: 16 Imported by: 0

README

Unicity Aggregator Public API

This package provides public JSON-RPC request and response types for the Unicity Aggregator. These types can be imported and used by external clients to interact with the aggregator service.

Installation

import "github.com/unicitynetwork/aggregator-go/pkg/api"

Types

Core Types
  • api.StateID - 64-character hex state ID, encoded as raw 32 bytes
  • api.TransactionHash - 64-character hex transaction hash, encoded as raw 32 bytes
  • api.HexBytes - Byte array that serializes to/from hex strings
  • api.BigInt - Big integer with JSON string serialization
  • api.Timestamp - Unix timestamp in milliseconds
Data Structures
  • api.CertificationData - Certification data with secp256k1 signature
  • api.CertificationRequest - State transition certification request
  • api.AggregatorRecord - Finalized certification request with proof data
  • api.Block - Blockchain block information
  • api.InclusionProof - Merkle inclusion proof
  • api.NoDeletionProof - No-deletion proof
  • api.HealthStatus - Service health status
JSON-RPC Request/Response Types
  • api.CertificationRequest / api.CertificationResponse
  • api.GetInclusionProofRequest / api.GetInclusionProofResponse
  • api.GetBlockRequest / api.GetBlockResponse
  • api.GetBlockRecordsRequest / api.GetBlockRecordsResponse
  • api.GetBlockHeightResponse
  • api.GetNoDeletionProofResponse

Example Usage

package main

import (
	"encoding/json"
	"fmt"

	"github.com/unicitynetwork/aggregator-go/pkg/api"
)

func main() {
	// Create a certification request
	req := &api.CertificationRequest{
		StateID: api.RequireNewImprintV2("b1333daf3261d9bfa9d6dd98f170c0e756c26dbe284b5f90b27df900f6a77c04"),
		CertificationData: api.CertificationData{
			OwnerPredicate:  api.NewPayToPublicKeyPredicate([]byte{0x03, 0x20, 0x44, 0xf2}),
			SourceStateHash: api.RequireNewImprintV2("cd60000000000000000000000000000000000000000000000000000000000000"),
			TransactionHash: api.RequireNewImprintV2("cd61000000000000000000000000000000000000000000000000000000000000"),
			Witness:         []byte{0x41, 0x67, 0x51, 0xe8}},
	}

	// Serialize to JSON
	data, _ := json.Marshal(req)
	fmt.Printf("JSON: %s\n", data)

	// Parse JSON response
	var resp api.CertificationResponse
	json.Unmarshal([]byte(`{"status":"SUCCESS"}`), &resp)
	fmt.Printf("Status: %s\n", resp.Status)
}

Features

No Internal Dependencies - The API package has no dependencies on internal types
JSON Serialization - All types support proper JSON marshaling/unmarshaling
Type Safety - Strong typing for all request/response structures
Validation - Built-in validation for hex strings, state IDs, etc.
Compatibility - Compatible with TypeScript aggregator implementations

Client Implementation

See the example client for a complete demonstration of how to use these types to build a client that communicates with the Unicity Aggregator service.

Cryptographic Operations

For cryptographic operations like signature generation and state ID creation, see the internal signing package or implement your own compatible signing logic using secp256k1.

Documentation

Overview

Package api provides public JSON-RPC request and response types for the Unicity Aggregator. These types can be imported and used by clients to interact with the aggregator service.

Index

Constants

View Source
const (
	CertificationRequestTag types.CborTag = 39030
	CertificationDataTag    types.CborTag = 39031
	PredicateTag            types.CborTag = 39032
	InclusionProofTag       types.CborTag = 39033
)

CBOR tag registry for aggregator-go types. Source of truth: https://github.com/unicitynetwork/unicity-ids/blob/main/cbor-tags.json

View Source
const (
	// StateTreeKeyLengthBits is the v2 SMT key size.
	// The key is the raw 32-byte hash value (no per-key algorithm prefix).
	StateTreeKeyLengthBits  = 256
	StateTreeKeyLengthBytes = StateTreeKeyLengthBits / 8
)
View Source
const (
	ShardRootStatusSuccess         = "SUCCESS"
	ShardRootStatusInvalidShardID  = "INVALID_SHARD_ID"
	ShardRootStatusInvalidRootHash = "INVALID_ROOT_HASH"
	ShardRootStatusInternalError   = "INTERNAL_ERROR"
	ShardRootStatusNotLeader       = "NOT_LEADER"
	ShardRootStatusNotReady        = "NOT_READY"
)

Status constants for SubmitShardRootResponse

View Source
const (
	HealthStatusOk        = "ok"
	HealthStatusUnhealthy = "unhealthy"
	HealthStatusDegraded  = "degraded"
)

Health status values returned by the health endpoint.

BitmapSize is the fixed byte length of the depth bitmap. The SMT key is StateTreeKeyLengthBits (256) bits, so the bitmap is 32 bytes.

View Source
const InclusionProofV2HashAlgorithm = SHA256

InclusionProofV2HashAlgorithm is the SMT hash algorithm locked in by the v2 inclusion proof wire contract. It is fixed to SHA-256; changing it requires a format version bump.

View Source
const SiblingSize = 32

SiblingSize is the fixed byte length of each sibling hash and of the leaf key / value hashes in an InclusionCert or ExclusionCert wire encoding. All supported SMT hash algorithms (SHA-256, SHA-3-256) produce 32-byte digests.

Variables

View Source
var (
	ErrCertTruncated        = errors.New("inclusion cert: truncated")
	ErrCertMisalignedSibs   = errors.New("inclusion cert: sibling bytes not aligned to 32")
	ErrCertBitmapMismatch   = errors.New("inclusion cert: sibling count does not match bitmap popcount")
	ErrCertRootMismatch     = errors.New("inclusion cert: root mismatch")
	ErrCertSiblingUnderflow = errors.New("inclusion cert: sibling underflow during verification")
	ErrCertKeyLength        = errors.New("inclusion cert: invalid key length")
	ErrCertRootLength       = errors.New("inclusion cert: invalid root length")
	ErrCertUnknownAlgo      = errors.New("inclusion cert: unknown hash algorithm")
	ErrExclusionNotImpl     = errors.New("exclusion cert: verification not yet implemented")
)

Errors returned by certificate decoding and verification.

View Source
var (
	ErrCertDepthOverlap      = errors.New("inclusion cert: parent and child cert overlap in depth")
	ErrCertDepthOrder        = errors.New("inclusion cert: parent cert depths must be shallower than child cert depths")
	ErrCertChildRootMismatch = errors.New("inclusion cert: parent fragment shard leaf value does not match child root")
	ErrCertMissingChild      = errors.New("inclusion cert: missing child cert")
	ErrCertMissingParent     = errors.New("inclusion cert: missing parent fragment")
)

Functions

func BigintEncode

func BigintEncode(value *big.Int) []byte

BigintEncode matches TypeScript BigintConverter.encode

func CborArray

func CborArray(n int) []byte

CborArray returns the CBOR tag for "array of n elements"

func CborBytes

func CborBytes(n int) []byte

CborBytes returns the CBOR tag for "byte string of n bytes"

func CborNull

func CborNull() []byte

CborNull returns the CBOR tag for null

func FixedBytesToPath added in v0.2.0

func FixedBytesToPath(key []byte, keyLengthBits int) (*big.Int, error)

FixedBytesToPath converts fixed-width SMT key bytes into sentinel-prefixed path form.

func MatchesShardPrefix added in v0.2.0

func MatchesShardPrefix(keyBytes []byte, shardBitmask int) (bool, error)

MatchesShardPrefix checks whether the LSB-first bits of keyBytes match the shard prefix defined by shardBitmask. The bitmask encodes a sentinel-prefixed shard ID (e.g. 0b100 = shard 0 in a 2-bit tree). keyBytes must be at least ceil(shardDepth/8) bytes long.

func MatchesShardPrefixFromHex added in v0.2.0

func MatchesShardPrefixFromHex(keyHex string, shardBitmask int) (bool, error)

MatchesShardPrefixFromHex decodes a hex-encoded 32-byte state key and applies MatchesShardPrefix.

func PathToFixedBytes added in v0.2.0

func PathToFixedBytes(path *big.Int, keyLengthBits int) ([]byte, error)

PathToFixedBytes converts a sentinel-prefixed SMT path into fixed-width key bytes. Byte order follows the v2 SMT bit layout: key bit d is bit (d%8) of key[d/8] (LSB-first across bytes).

func ValidateStateID

func ValidateStateID(stateID StateID, sourceStateHash SourceStateHash, ownerPredicate Predicate) (bool, error)

Types

type AggregatorRecord

type AggregatorRecord struct {
	StateID               StateID           `json:"stateId"`
	CertificationData     CertificationData `json:"certificationData"`
	AggregateRequestCount uint64            `json:"aggregateRequestCount,omitempty,string"`
	BlockNumber           *BigInt           `json:"blockNumber"`
	LeafIndex             *BigInt           `json:"leafIndex"`
	CreatedAt             *Timestamp        `json:"createdAt"`
	FinalizedAt           *Timestamp        `json:"finalizedAt"`
}

AggregatorRecord represents a finalized certification request with proof data

type BigInt

type BigInt struct {
	*big.Int
}

BigInt wraps big.Int for JSON serialization

func NewBigInt

func NewBigInt(x *big.Int) *BigInt

NewBigInt creates a new BigInt

func NewBigIntFromString

func NewBigIntFromString(s string) (*BigInt, error)

NewBigIntFromString creates a BigInt from string

func NewBigIntFromUint64

func NewBigIntFromUint64(n uint64) *BigInt

func (*BigInt) MarshalJSON

func (b *BigInt) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (*BigInt) String

func (b *BigInt) String() string

String returns the string representation for BSON compatibility

func (*BigInt) UnmarshalJSON

func (b *BigInt) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler

type Block

type Block struct {
	Index               *BigInt                  `json:"index"`
	ChainID             string                   `json:"chainId"`
	ShardID             ShardID                  `json:"shardId"`
	Version             string                   `json:"version"`
	ForkID              string                   `json:"forkId"`
	RootHash            HexBytes                 `json:"rootHash"`
	PreviousBlockHash   HexBytes                 `json:"previousBlockHash"`
	NoDeletionProofHash HexBytes                 `json:"noDeletionProofHash"`
	CreatedAt           *Timestamp               `json:"createdAt"`
	UnicityCertificate  HexBytes                 `json:"unicityCertificate"`
	ParentFragment      *ParentInclusionFragment `json:"parentFragment,omitempty"`    // child mode only
	ParentBlockNumber   uint64                   `json:"parentBlockNumber,omitempty"` // child mode only
}

Block represents a blockchain block

type CertificationData

type CertificationData struct {
	Version types.Version `json:"version"`

	// OwnerPredicate is the owner predicate in format: CBOR[engine: uint, code: byte[], params: byte[]].
	//
	// In case of standard PayToPublicKey predicate the values must be:
	//  - engine = 01 (plain CBOR uint value of 1)
	//  - code = 4101 (byte array of length 1 containing the CBOR encoding of uint value 1)
	//  - params = 5821 000102..20 (byte array of length 33 containing the raw bytes of the public key value)
	OwnerPredicate Predicate `json:"ownerPredicate"`

	// SourceStateHash is the raw 32-byte hash of the source data.
	SourceStateHash SourceStateHash `json:"sourceStateHash"`

	// TransactionHash is the raw 32-byte hash of the transaction data.
	TransactionHash TransactionHash `json:"transactionHash"`

	// Witness is the "unlocking part" of owner predicate. In case of PayToPublicKey owner predicate the witness must be
	// a signature created on the hash of CBOR array[SourceStateHash, TransactionHash],
	// in Unicity's [R || S || V] format (65 bytes).
	Witness HexBytes `json:"witness"`
	// contains filtered or unexported fields
}

CertificationData represents the necessary cryptographic data needed for a state transition CertificationRequest.

func (CertificationData) CreateStateID

func (c CertificationData) CreateStateID() (StateID, error)

func (*CertificationData) GetVersion added in v0.2.0

func (c *CertificationData) GetVersion() types.Version

func (CertificationData) Hash

func (c CertificationData) Hash() ([]byte, error)

Hash returns the data hash of certification data. The hash is calculated as the CBOR array [OwnerPredicate, SourceStateHash, TransactionHash, Witness].

func (*CertificationData) MarshalCBOR added in v0.2.0

func (c *CertificationData) MarshalCBOR() ([]byte, error)

func (CertificationData) SigDataHash

func (c CertificationData) SigDataHash() (*DataHash, error)

SigDataHash returns the data hash used for signature generation. The hash is calculated as the CBOR array [SourceStateHash, TransactionHash].

func (*CertificationData) UnmarshalCBOR added in v0.2.0

func (c *CertificationData) UnmarshalCBOR(data []byte) error

type CertificationRequest

type CertificationRequest struct {
	Version types.Version

	// StateID is the unique identifier of the certification request, used as a
	// key in the state tree. In v2 it is the raw 32-byte hash of the CBOR array
	// [CertificationData.OwnerPredicate, CertificationData.SourceStateHash].
	StateID StateID

	// CertificationData contains the necessary cryptographic data needed for the CertificationRequest.
	CertificationData CertificationData

	AggregateRequestCount uint64
	// contains filtered or unexported fields
}

CertificationRequest represents the certification_request JSON-RPC request, sometimes also referred to as StateTransitionCertificationRequest, Commitment or UnicityServiceRequest.

func (*CertificationRequest) GetVersion added in v0.2.0

func (c *CertificationRequest) GetVersion() types.Version

func (*CertificationRequest) MarshalCBOR added in v0.2.0

func (c *CertificationRequest) MarshalCBOR() ([]byte, error)

func (*CertificationRequest) MarshalJSON

func (c *CertificationRequest) MarshalJSON() ([]byte, error)

MarshalJSON marshals the request to CBOR and then hex encodes it, returning the result as a JSON string.

func (*CertificationRequest) UnmarshalCBOR added in v0.2.0

func (c *CertificationRequest) UnmarshalCBOR(data []byte) error

func (*CertificationRequest) UnmarshalJSON

func (c *CertificationRequest) UnmarshalJSON(data []byte) error

UnmarshalJSON expects a hex-encoded CBOR string, decodes it, and then unmarshals the CBOR data.

type CertificationResponse

type CertificationResponse struct {
	Status string `json:"status"`
}

CertificationResponse represents the certification_request JSON-RPC response.

type DataHash

type DataHash struct {
	Algorithm HashAlgorithm
	RawHash   []byte // Raw hash value
	// contains filtered or unexported fields
}

DataHash represents a hash value combined with the algorithm identifier

func CertDataHash

func CertDataHash(ownerPredicate Predicate, sourceStateHash, transactionHash, signature []byte) (*DataHash, error)

CertDataHash returns the data hash of certification data. The hash is calculated as the CBOR array [OwnerPredicate, SourceStateHash, TransactionHash, Witness].

func NewDataHash

func NewDataHash(algorithm HashAlgorithm, hash []byte) *DataHash

NewDataHash creates a DataHash from an algorithm identifier and a hash value

func SigDataHash

func SigDataHash(sourceStateHash []byte, transactionHash []byte) *DataHash

SigDataHash returns the data hash used for signature generation. The hash is calculated as the CBOR array [sourceStateHash, transactionHash].

func StateIDDataHash

func StateIDDataHash(ownerPredicate Predicate, sourceStateHash []byte) (*DataHash, error)

func (*DataHash) GetImprint

func (h *DataHash) GetImprint() []byte

GetImprint computes and caches the imprint representation of the hash value

func (*DataHash) ToHex

func (h *DataHash) ToHex() string

ToHex returns the hex string representation of the hash imprint

type DataHasher

type DataHasher struct {
	// contains filtered or unexported fields
}

DataHasher wraps a hash algorithm identifier and a corresponding hash function object

func NewDataHasher

func NewDataHasher(algorithm HashAlgorithm) *DataHasher

NewDataHasher creates a new DataHasher using the given algorithm

func (*DataHasher) AddCborBytes

func (h *DataHasher) AddCborBytes(data []byte) *DataHasher

AddCborBytes adds data to the hasher as CBOR byte string, returns the hasher for easy call chaining

func (*DataHasher) AddCborNull

func (h *DataHasher) AddCborNull() *DataHasher

AddCborNull adds a CBOR null to the hasher, returns the hasher for easy call chaining

func (*DataHasher) AddData

func (h *DataHasher) AddData(data []byte) *DataHasher

AddData adds data to the hasher, returns the hasher for easy call chaining

func (*DataHasher) GetAlgorithm

func (h *DataHasher) GetAlgorithm() HashAlgorithm

GetAlgorithm returns the algorithm identifier

func (*DataHasher) GetHash

func (h *DataHasher) GetHash() *DataHash

GetHash finalizes the computation and returns the hash value

func (*DataHasher) Reset

func (h *DataHasher) Reset() *DataHasher

Reset resets the hasher to initial state, returns the hasher for easy call chaining

func (*DataHasher) SumRaw

func (h *DataHasher) SumRaw(dst []byte) []byte

SumRaw appends the current hash state to dst and returns the result. Pass dst[:0] where dst has cap >= hash output length to write with zero allocation.

type ExclusionCert added in v0.2.0

type ExclusionCert struct {
	KL       [SiblingSize]byte
	HL       [SiblingSize]byte
	Bitmap   [BitmapSize]byte
	Siblings [][SiblingSize]byte
}

ExclusionCert is the decoded v2 non-inclusion certificate.

Wire format (raw binary, no framing):

k_l[32] || h_l[32] || bitmap[32] || s_1[32] || ... || s_n[32]

(k_l, h_l) is the witness leaf present in the tree at the position reached when routing the query key. bitmap + siblings describe the proof path from the root to that position, under the same root-to- leaf sibling ordering as InclusionCert.

Verification semantics are not yet implemented in Go. The type and codec are frozen so clients can decode today; see docs/inclusion-proof-wire.md.

func (*ExclusionCert) MarshalBinary added in v0.2.0

func (c *ExclusionCert) MarshalBinary() ([]byte, error)

MarshalBinary encodes the exclusion certificate to its wire form.

func (*ExclusionCert) UnmarshalBinary added in v0.2.0

func (c *ExclusionCert) UnmarshalBinary(data []byte) error

UnmarshalBinary decodes the wire form into the exclusion certificate. The sibling count is validated against the bitmap popcount.

func (*ExclusionCert) Verify added in v0.2.0

func (c *ExclusionCert) Verify(queryKey, expectedRoot []byte, algo HashAlgorithm) error

Verify is not yet implemented for exclusion certificates. The wire schema is frozen so clients can decode.

type GetBlockHeightResponse

type GetBlockHeightResponse struct {
	BlockNumber *BigInt `json:"blockNumber"`
}

GetBlockHeightResponse represents the get_block_height JSON-RPC response

type GetBlockRecords

type GetBlockRecords struct {
	BlockNumber *BigInt `json:"blockNumber"`
}

GetBlockRecords represents the get_block_records JSON-RPC request

type GetBlockRecordsResponse

type GetBlockRecordsResponse struct {
	AggregatorRecords []*AggregatorRecord `json:"aggregatorRecords"`
}

GetBlockRecordsResponse represents the get_block_records JSON-RPC response

type GetBlockRequest

type GetBlockRequest struct {
	BlockNumber interface{} `json:"blockNumber"` // Can be number, string, or "latest"
}

GetBlockRequest represents the get_block JSON-RPC request

type GetBlockResponse

type GetBlockResponse struct {
	Block            *Block `json:"block"`
	TotalCommitments uint64 `json:"totalCommitments,string"`
}

GetBlockResponse represents the get_block JSON-RPC response

type GetInclusionProofRequestV2

type GetInclusionProofRequestV2 struct {
	StateID StateID `json:"stateId"`
}

GetInclusionProofRequestV2 represents the get_inclusion_proof JSON-RPC request

type GetInclusionProofResponseV2

type GetInclusionProofResponseV2 struct {
	BlockNumber    uint64            `json:"blockNumber"`
	InclusionProof *InclusionProofV2 `json:"inclusionProof"`
	// contains filtered or unexported fields
}

GetInclusionProofResponseV2 represents the get_inclusion_proof JSON-RPC response

func (*GetInclusionProofResponseV2) MarshalJSON

func (c *GetInclusionProofResponseV2) MarshalJSON() ([]byte, error)

MarshalJSON marshals the request to CBOR and then hex encodes it, returning the result as a JSON string.

func (*GetInclusionProofResponseV2) UnmarshalJSON

func (c *GetInclusionProofResponseV2) UnmarshalJSON(data []byte) error

UnmarshalJSON expects a hex-encoded CBOR string, decodes it, and then unmarshals the CBOR data.

type GetNoDeletionProofResponse

type GetNoDeletionProofResponse struct {
	NoDeletionProof *NoDeletionProof `json:"noDeletionProof"`
}

GetNoDeletionProofResponse represents the get_no_deletion_proof JSON-RPC response

type GetShardProofRequest

type GetShardProofRequest struct {
	ShardID ShardID `json:"shardId"`
}

GetShardProofRequest represents the get_shard_proof JSON-RPC request

type GetShardProofResponse

type GetShardProofResponse struct {
	ParentFragment     *ParentInclusionFragment `json:"parentFragment,omitempty"` // native parent fragment for child v2 composition
	UnicityCertificate HexBytes                 `json:"unicityCertificate"`       // Unicity Certificate from the finalized block
	BlockNumber        uint64                   `json:"blockNumber,omitempty"`
}

GetShardProofResponse represents the get_shard_proof JSON-RPC response

type HashAlgorithm

type HashAlgorithm int

HashAlgorithm identifies a hashing algorithm

const (
	SHA256   HashAlgorithm = 0 // SHA-2-256
	SHA3_256 HashAlgorithm = 1 // SHA-3-256
)

Identifiers of known/supported hashing algorithms

type HealthStatus

type HealthStatus struct {
	Status   string            `json:"status"`
	Role     string            `json:"role"`
	ServerID string            `json:"serverId"`
	Sharding Sharding          `json:"sharding"`
	Details  map[string]string `json:"details,omitempty"`
}

HealthStatus represents the health status of the service

func NewHealthStatus

func NewHealthStatus(role, serverID string) *HealthStatus

NewHealthStatus creates a new health status

func (*HealthStatus) AddDetail

func (h *HealthStatus) AddDetail(key, value string)

AddDetail adds a detail to the health status

type HexBytes

type HexBytes []byte

HexBytes represents byte array that serializes to/from hex string

func NewHexBytes

func NewHexBytes(data []byte) HexBytes

NewHexBytes creates HexBytes from byte slice

func NewHexBytesFromString

func NewHexBytesFromString(s string) (HexBytes, error)

NewHexBytesFromString creates HexBytes from hex string

func (HexBytes) MarshalJSON

func (h HexBytes) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (HexBytes) String

func (h HexBytes) String() string

String returns hex representation

func (*HexBytes) UnmarshalJSON

func (h *HexBytes) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler

type ImprintV2

type ImprintV2 HexBytes

ImprintV2 stores hash-like identifiers used by the public API.

func NewImprintV2

func NewImprintV2(s string) (ImprintV2, error)

func (ImprintV2) Bytes

func (r ImprintV2) Bytes() []byte

func (ImprintV2) DataBytes

func (r ImprintV2) DataBytes() []byte

func (ImprintV2) GetPath

func (r ImprintV2) GetPath() (*big.Int, error)

func (ImprintV2) GetTreeKey added in v0.2.0

func (r ImprintV2) GetTreeKey() ([]byte, error)

GetTreeKey returns the canonical SMT key bytes (32 bytes, no algorithm prefix).

func (ImprintV2) Imprint

func (r ImprintV2) Imprint() []byte

func (ImprintV2) MarshalCBOR

func (r ImprintV2) MarshalCBOR() ([]byte, error)

func (ImprintV2) MarshalJSON

func (r ImprintV2) MarshalJSON() ([]byte, error)

func (ImprintV2) String

func (r ImprintV2) String() string

func (*ImprintV2) UnmarshalCBOR

func (r *ImprintV2) UnmarshalCBOR(cborBytes []byte) error

func (*ImprintV2) UnmarshalJSON

func (r *ImprintV2) UnmarshalJSON(data []byte) error

type InclusionCert added in v0.2.0

type InclusionCert struct {
	Bitmap   [BitmapSize]byte
	Siblings [][SiblingSize]byte
}

InclusionCert is the decoded v2 inclusion certificate.

Wire format (raw binary, no framing):

bitmap[32] || s_1[32] || ... || s_n[32]

where n = popcount(bitmap). Siblings are in generation order (root-to-leaf): s_1 is the sibling at the shallowest depth with a bitmap bit set, s_n at the deepest. Verification walks depths 255..0 and consumes siblings from the end of the slice.

The certificate carries no root, no key, and no value. Verification requires these to be supplied from the outer proof tuple:

  • key (sid) — from the RPC request parameter.
  • value (txhash) — from CertificationData.TransactionHash.
  • root — from UC.IR.h.

See docs/inclusion-proof-wire.md for the full specification.

func ComposeInclusionCert added in v0.2.0

func ComposeInclusionCert(parentFragment *ParentInclusionFragment, child *InclusionCert, childRoot []byte) (*InclusionCert, error)

ComposeInclusionCert merges a child inclusion certificate with the stored parent proof fragment for the child shard. The result is a single public InclusionCert that can later be verified against the parent UC.IR.h.

Invariants enforced here:

  • parentFragment.ShardLeafValue must equal childRoot
  • parent fragment certificate bytes must decode as a valid InclusionCert
  • parent and child bitmaps must not overlap in depth
  • if both certs contain siblings, every parent depth must be shallower than every child depth
  • merged siblings stay in root-to-leaf order: parent first, then child

func (*InclusionCert) MarshalBinary added in v0.2.0

func (c *InclusionCert) MarshalBinary() ([]byte, error)

MarshalBinary encodes the certificate to its wire form.

func (*InclusionCert) UnmarshalBinary added in v0.2.0

func (c *InclusionCert) UnmarshalBinary(data []byte) error

UnmarshalBinary decodes the wire form into the certificate. The sibling count is validated against the bitmap popcount.

func (*InclusionCert) Verify added in v0.2.0

func (c *InclusionCert) Verify(key, value, expectedRoot []byte, algo HashAlgorithm) error

Verify checks that applying the bitmap + siblings path on top of H_leaf(key, value) reproduces expectedRoot under the given hash algorithm.

Parameters:

  • key: 32-byte SMT key, LSB-first layout.
  • value: raw leaf value bytes (v2 inclusion proofs use the tx hash).
  • expectedRoot: raw 32-byte root hash, taken from UC.IR.h.
  • algo: hash algorithm used by the SMT.

type InclusionProofV2

type InclusionProofV2 struct {
	Version            types.Version      `json:"version"`
	CertificationData  *CertificationData `json:"certificationData"`
	CertificateBytes   HexBytes           `json:"certificateBytes"`
	UnicityCertificate types.RawCBOR      `json:"unicityCertificate"`
	// contains filtered or unexported fields
}

InclusionProofV2 is the canonical v2 inclusion proof payload.

Wire form: CBOR tag InclusionProofTag wrapping a 4-element toarray:

#InclusionProofTag ([
  version: uint,
  certificationDataOrNull,
  certificateBytes: bstr,   // InclusionCert or ExclusionCert raw wire form
  unicityCertificate: raw CBOR
])

Discriminator:

  • CertificationData != nil → inclusion. CertificateBytes is an InclusionCert wire payload. The SMT key comes from the outer RPC request (stateId); the leaf value is CertificationData.TransactionHash.
  • CertificationData == nil → non-inclusion. CertificateBytes is an ExclusionCert wire payload. Non-inclusion verification is not yet implemented in Go.

The expected SMT root is ALWAYS taken from UC.IR.h (input record hash of the embedded Unicity Certificate). No root field appears here.

See docs/inclusion-proof-wire.md for the frozen specification.

func (*InclusionProofV2) GetVersion added in v0.2.0

func (p *InclusionProofV2) GetVersion() types.Version

func (*InclusionProofV2) MarshalCBOR added in v0.2.0

func (p *InclusionProofV2) MarshalCBOR() ([]byte, error)

func (*InclusionProofV2) UCInputRecordHashRaw added in v0.2.0

func (p *InclusionProofV2) UCInputRecordHashRaw() ([]byte, error)

UCInputRecordHashRaw decodes the embedded Unicity Certificate and returns UC.IR.h as a raw 32-byte hash. Any other length is rejected.

func (*InclusionProofV2) UnmarshalCBOR added in v0.2.0

func (p *InclusionProofV2) UnmarshalCBOR(data []byte) error

func (*InclusionProofV2) Verify

Verify checks a v2 inclusion proof end-to-end against the outer CertificationRequest and VerifierContext: local SMT path, UnicityCertificate (shard tree → unicity tree → seal), and ShardTreeCertificate.Shard equality.

The nil-guard error strings below are part of the public contract so reference verifiers in other languages can pin them.

type MerkleTreePath

type MerkleTreePath struct {
	Root  string           `json:"root"`
	Steps []MerkleTreeStep `json:"steps"`
}

MerkleTreePath represents the path to verify inclusion in a Merkle tree

func (MerkleTreePath) MarshalCBOR

func (m MerkleTreePath) MarshalCBOR() ([]byte, error)

func (*MerkleTreePath) UnmarshalCBOR

func (m *MerkleTreePath) UnmarshalCBOR(data []byte) error

func (*MerkleTreePath) Verify

func (m *MerkleTreePath) Verify(stateID *big.Int) (*PathVerificationResult, error)

type MerkleTreeStep

type MerkleTreeStep struct {
	Path string  `json:"path"`
	Data *string `json:"data"`
}

MerkleTreeStep represents a single step in a Merkle tree path

type NoDeletionProof

type NoDeletionProof struct {
	Proof     HexBytes   `json:"proof"`
	CreatedAt *Timestamp `json:"createdAt"`
}

NoDeletionProof represents a no-deletion proof

func NewNoDeletionProof

func NewNoDeletionProof(proof HexBytes) *NoDeletionProof

NewNoDeletionProof creates a new no-deletion proof

type ParentInclusionFragment added in v0.2.0

type ParentInclusionFragment struct {
	CertificateBytes HexBytes `json:"certificateBytes"`
	ShardLeafValue   HexBytes `json:"shardLeafValue"`
}

ParentInclusionFragment is the internal parent-tree proof fragment stored on finalized child blocks and returned by get_shard_proof. CertificateBytes uses the same bitmap+sibling wire shape as InclusionCert; ShardLeafValue is the parent leaf value proven by that fragment and must equal the child SMT root before later composition.

func (*ParentInclusionFragment) Verify added in v0.2.0

func (f *ParentInclusionFragment) Verify(shardID ShardID, keyLength int, expectedLeafValue, expectedRoot []byte, algo HashAlgorithm) error

type PathVerificationResult

type PathVerificationResult struct {
	PathValid    bool
	PathIncluded bool
	Result       bool
}

type Predicate

type Predicate struct {
	Engine uint   `json:"engine"`
	Code   []byte `json:"code"`
	Params []byte `json:"params"`
	// contains filtered or unexported fields
}

func NewPayToPublicKeyPredicate

func NewPayToPublicKeyPredicate(publicKey []byte) Predicate

func (Predicate) MarshalCBOR added in v0.2.0

func (p Predicate) MarshalCBOR() ([]byte, error)

Predicate is tag-wrapped but intentionally carries no Version field — the Engine field is already the shape discriminator.

func (*Predicate) UnmarshalCBOR added in v0.2.0

func (p *Predicate) UnmarshalCBOR(data []byte) error

type RootShardInclusionProof

type RootShardInclusionProof struct {
	ParentFragment     *ParentInclusionFragment `json:"parentFragment,omitempty"`
	UnicityCertificate HexBytes                 `json:"unicityCertificate"`
	BlockNumber        uint64                   `json:"blockNumber,omitempty"`
}

func (*RootShardInclusionProof) IsValid

func (r *RootShardInclusionProof) IsValid(shardID ShardID, keyLength int, shardRootHash HexBytes) bool

type ShardID

type ShardID = int

type Sharding

type Sharding struct {
	Mode       string `json:"mode"`
	ShardIDLen int    `json:"shardIdLen"`
	ShardID    int    `json:"shardId"`
	// BFTShardID is the MSB-first bit-string (e.g. "0" or "101") of the BFT
	// shard in bft-shard mode; empty in other modes. Populated separately
	// from ShardIDLen/ShardID because a bit-string does not fit in an int.
	BFTShardID string `json:"bftShardId,omitempty"`
}

type SourceStateHash

type SourceStateHash = ImprintV2

type StateID

type StateID = ImprintV2

func CreateStateID

func CreateStateID(ownerPredicate Predicate, sourceStateHash SourceStateHash) (StateID, error)

CreateStateID creates a StateID from source state hash and owner predicate

func RequireNewImprintV2

func RequireNewImprintV2(s string) StateID

RequireNewImprintV2 is a helper for tests that panics on error

type SubmitShardRootRequest

type SubmitShardRootRequest struct {
	ShardID  ShardID  `json:"shardId"`
	RootHash HexBytes `json:"rootHash"` // Raw root hash from child SMT
}

SubmitShardRootRequest represents the submit_shard_root JSON-RPC request

type SubmitShardRootResponse

type SubmitShardRootResponse struct {
	Status string `json:"status"` // "SUCCESS", "INVALID_SHARD_ID", "INVALID_ROOT_HASH", etc.
}

SubmitShardRootResponse represents the submit_shard_root JSON-RPC response

type Timestamp

type Timestamp struct {
	time.Time
}

Timestamp wraps time.Time for consistent JSON serialization

func NewTimestamp

func NewTimestamp(t time.Time) *Timestamp

NewTimestamp creates a new Timestamp

func Now

func Now() *Timestamp

Now creates a Timestamp for current time

func (*Timestamp) MarshalJSON

func (t *Timestamp) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (*Timestamp) UnmarshalJSON

func (t *Timestamp) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler

type TransactionHash

type TransactionHash = ImprintV2

type VerifierContext added in v0.2.0

type VerifierContext struct {
	TrustBase       types.RootTrustBase
	PartitionID     types.PartitionID
	ExpectedShardID types.ShardID
	ShardConfHash   []byte
}

VerifierContext carries the trust base and expected partition/shard identity a verifier needs to certify a v2 inclusion proof. TrustBase, PartitionID, and ExpectedShardID are required; ShardConfHash is optional (nil skips the cross-check against UC.ShardConfHash).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL