godcap

package module
v0.0.0-...-cbf774f Latest Latest
Warning

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

Go to latest
Published: May 9, 2025 License: Apache-2.0 Imports: 25 Imported by: 0

README

Go DCAP

License

With Go DCAP, you can request ZK proofs of a quote verification from ZK Prover Network, then verify directly on-chain in native Go.

Features

Go DCAP currently provides the following main features:

  • Provides a fee estimate on quote / zk proof verification:

Use either:

Portal.EstimateBaseFeeVerifyOnChain to estimate the fee to verify quotes fully on-chain

OR

Portal.EstimateBaseFeeVerifyAndAttestWithZKProof to estimate the fee to verify ZK Proof of the Quote Verification executed in a zkVM.

  • Generates ZkProof from a Remote Prover Network

Currently integrates both RiscZero Bonsai and Succinct SP1 Remote Prover Networks.

Use Portal.GenerateZkProof to fetch proofs. To specify the zkVM, pass either zkdcap.ZkTypeRiscZero or zkdcap.ZkTypeSuccinct.

  • ABI Encoder for user-defined Solidity function

The Callback object is a required argument for either verification methods to allow DCAP Portal to perform a callback on the user contract after a successful DCAP Quote / ZK Proof verification. The calldata must be explicitly provided in the Callback object.

Use the NewCallbackFromAbiJSON function to generate the ABI-encoded calldata.

  • Invoke the verifyAndAttestOnChain() or verifyAndAttestWithZKProof contract methods natively in GO

Use either:

Portal.VerifyAndAttestOnChain to verify DCAP quotes fully on-chain.

OR

Portal.VerifyAndAttestWithZKProofto verify ZK Proof of a given DCAP attestation.

Usage

Simplified snippet to show how you can integrate your code with Go DCAP.

func main() {
    // Initiation
    portal, err := godcap.NewDcapPortal(ctx, 
        godcap.WithChainConfig(godcap.ChainAutomataTestnet), 
        godcap.WithPrivateKey(privateKeyStr),
    )
    // error handling

    // generate the callback
    callback := NewCallbackFromAbiJSON(ContractABI).
        .WithParams("functionName", param1, param2, ...)
        .WithTo(contractAddress)
        .WithValue(wei)

    var tx *types.Transaction

    // Option1: verify with zkproof
    {
        // generate proof
        var zkProofType zkdcap.ZkType // zkdcap.ZkTypeRiscZero or zkdcap.ZkTypeSuccinct
        zkproof, err := portal.GenerateZkProof(ctx, zkProofType, quote)
        // error handling

        tx, err = portal.VerifyAndAttestWithZKProof(nil, zkproof, callback)
        // error handling
    }

    // Option2: verify on chain
    {   
        tx, err = portal.VerifyAndAttestOnChain(nil, quote, callback)
        // error handling
    }

    receipt := <-portal.WaitTx(ctx, tx)
    fmt.Printf("%#v\n", receipt)
}

Examples

Note: VerifiedCounter can be found here

Verify on chain
func VerifyAndAttestOnChain(ctx context.Context, quote []byte, privateKeyStr string) error {
    // Create a new DCAP portal instance
    portal, err := godcap.NewDcapPortal(ctx, 
        godcap.WithChainConfig(godcap.ChainAutomataTestnet), 
        godcap.WithPrivateKey(privateKeyStr),
    )
    if err != nil {
        return err
    }

    // setup a callback function when the verification success
    //  function setNumber(uint256 newNumber) public fromDcapPortal
    callback := NewCallbackFromAbiJSON(VerifiedCounter.VerifiedCounterABI)
        .WithParams("setNumber", big.NewInt(10))
        .WithTo(verifiedCounterAddr)

    // Verify the quote on chain
    tx, err := portal.VerifyAndAttestOnChain(nil, quote, callback)
    if err != nil {
        return err
    }

    // waiting for the transaction receipt
    receipt := <-portal.WaitTx(ctx, tx)
    fmt.Printf("%#v\n", receipt)
}
Verify with Risc0 ZkProof
//
// Make sure you export the API key to BONSAI_API_KEY
//   export BONSAI_API_KEY=${API_KEY}

func VerifyWithRisc0ZkProof(ctx context.Context, quote []byte, privateKeyStr string) error {
    // Create a new DCAP portal instance
    portal, err := godcap.NewDcapPortal(ctx, 
        godcap.WithChainConfig(godcap.ChainAutomataTestnet), 
        godcap.WithPrivateKey(privateKeyStr),
    )
    if err != nil {
        return err
    }

    // Generate a ZkProof using Risc0, this function will take a while to finish
    zkproof, err := portal.GenerateZkProof(ctx, zkdcap.ZkTypeRiscZero, quote)
    if err != nil {
        return err
    }

    // setup a callback function when the verification success
    //  function setNumber(uint256 newNumber) public fromDcapPortal
    callback := NewCallbackFromAbiJSON(VerifiedCounter.VerifiedCounterABI)
        .WithParams("setNumber", big.NewInt(10))
        .WithTo(verifiedCounterAddr)

    // Verify the ZkProof and attest on chain
    tx, err := portal.VerifyAndAttestWithZKProof(nil, zkproof, callback)
    if err != nil {
        return err
    }

    // waiting for the transaction receipt
    receipt := <-portal.WaitTx(ctx, tx)
    fmt.Printf("%#v\n", receipt)
}
Verify with Succinct ZkProof

//
// Make sure you export the Succinct private key to NETWORK_PRIVATE_KEY
//   export NETWORK_PRIVATE_KEY=${KEY}

func VerifyWithSuccinctZkProof(ctx context.Context, quote []byte, privateKeyStr string) error {
    // Create a new DCAP portal instance
    portal, err := godcap.NewDcapPortal(ctx, 
        godcap.WithChainConfig(godcap.ChainAutomataTestnet), 
        godcap.WithPrivateKey(privateKeyStr),
    )
    if err != nil {
        return err
    }

    // Generate a ZkProof using Succinct, this function will take a while to finish
    zkproof, err := portal.GenerateZkProof(ctx, zkdcap.ZkTypeSuccinct, quote)
    if err != nil {
        return err
    }

    // setup a callback function when the verification success
    //  function setNumber(uint256 newNumber) public fromDcapPortal
    callback := NewCallbackFromAbiJSON(VerifiedCounter.VerifiedCounterABI)
        .WithParams("setNumber", big.NewInt(10))
        .WithTo(verifiedCounterAddr)

    // Verify the ZkProof and attest on chain
    tx, err := portal.VerifyAndAttestWithZKProof(nil, zkproof, callback)
    if err != nil {
        return err
    }

    // waiting for the transaction receipt
    receipt := <-portal.WaitTx(ctx, tx)
    fmt.Printf("%#v\n", receipt)
}

Find more examples here

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrValueShouldBeNil        = logex.Define("value in TransactOpts should be nil")
	ErrTransactOptsMissingFrom = logex.Define("TransactOpts missing from")
	ErrInsuccifientFunds       = logex.Define("InsuccifientFunds")
	DcapError                  = map[string]string{
		"0x1356a63b": "AutomataDcapAttestation: BP_Not_Valid()",
		"0x1a72054d": "AutomataDcapAttestation: Insuccifient_Funds()",
		"0xc40a532b": "AutomataDcapAttestation: Withdrawal_Failed()",
	}
)
View Source
var ChainArbitrumMainnet = parseChainConfig(arbitrumMainnet)
View Source
var ChainArbitrumSepolia = parseChainConfig(arbitrumSepolia)
View Source
var ChainAutomataMainnet = parseChainConfig(automataMainnet)
View Source
var ChainAutomataTestnet = parseChainConfig(automataTestnet)
View Source
var ChainAvalancheCFuji = parseChainConfig(avalancheCFuji)
View Source
var ChainAvalancheCMainnet = parseChainConfig(avalancheCMainnet)
View Source
var ChainBaseMainnet = parseChainConfig(baseMainnet)
View Source
var ChainBaseSepolia = parseChainConfig(baseSepolia)
View Source
var ChainBscMainnet = parseChainConfig(bscMainnet)
View Source
var ChainBscTestnet = parseChainConfig(bscTestnet)
View Source
var ChainEthereumHolesky = parseChainConfig(ethereumHolesky)
View Source
var ChainEthereumHoodi = parseChainConfig(ethereumHoodi)
View Source
var ChainEthereumMainnet = parseChainConfig(ethereumMainnet)
View Source
var ChainEthereumSepolia = parseChainConfig(ethereumSepolia)
View Source
var ChainOPMainnet = parseChainConfig(opMainnet)
View Source
var ChainOPSepolia = parseChainConfig(opSepolia)
View Source
var ChainPolygonPosAmoy = parseChainConfig(polygonPosAmoy)
View Source
var ChainPolygonPosMainnet = parseChainConfig(polygonPosMainnet)
View Source
var ChainWorldMainnet = parseChainConfig(worldMainnet)
View Source
var ChainWorldSepolia = parseChainConfig(worldSepolia)

Functions

func AddChainConfig

func AddChainConfig(chain *ChainConfig) bool

Types

type Callback

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

func NewCallback

func NewCallback(abi abi.ABI) *Callback

func NewCallbackFromAbiJSON

func NewCallbackFromAbiJSON(json string) *Callback

func (*Callback) Abi

func (c *Callback) Abi() (gen.IDcapPortalCallback, error)

func (*Callback) Value

func (c *Callback) Value() *big.Int

func (*Callback) WithParams

func (c *Callback) WithParams(method string, args ...interface{}) *Callback

func (*Callback) WithTo

func (c *Callback) WithTo(to common.Address) *Callback

func (*Callback) WithValue

func (c *Callback) WithValue(value *big.Int) *Callback

type ChainConfig

type ChainConfig struct {
	ChainId                    int64             `json:"chain_id"`
	Name                       string            `json:"name"`
	Testnet                    bool              `json:"testnet"`
	OneRpc                     string            `json:"one_rpc"`
	Endpoint                   string            `json:"endpoint"`
	EIP1559                    bool              `json:"eip_1559"`
	Explorer                   string            `json:"explorer"`
	DcapPortal                 common.Address    `json:"dcap_portal"`
	AutomataDcapAttestationFee common.Address    `json:"automata_dcap_attestation_fee"`
	PCCSRouter                 common.Address    `json:"pccs_router"`
	V3QuoteVerifier            common.Address    `json:"v3_quote_verifier"`
	V4QuoteVerifier            common.Address    `json:"v4_quote_verifier"`
	PCCS                       *pccs.ChainConfig `json:"pccs"`
}

func ChainConfigFromChainId

func ChainConfigFromChainId(chainId int64) *ChainConfig

type DcapPortal

type DcapPortal struct {
	Stub *gen.DcapPortal
	// contains filtered or unexported fields
}

DcapPortal represents the main interface for interacting with DCAP attestation

func NewDcapPortal

func NewDcapPortal(ctx context.Context, options ...DcapPortalOption) (*DcapPortal, error)

NewDcapPortal creates a new instance of DcapPortal with the provided options. It will connect to AutomataTestnet(https://explorer-testnet.ata.network) by default

func (*DcapPortal) BuildTransactOpts

func (p *DcapPortal) BuildTransactOpts(ctx context.Context) (*bind.TransactOpts, error)

BuildTransactOpts builds transaction options using the provided private key. Returns error if key transactor creation or options normalization fails.

func (*DcapPortal) CalculateAttestationFee

func (p *DcapPortal) CalculateAttestationFee(tx *types.Transaction, callback *Callback, receipt *types.Receipt) *big.Int

CalculateAttestationFee calculates the actual attestation fee based on the transaction receipt.

func (*DcapPortal) CheckQuote

func (p *DcapPortal) CheckQuote(ctx context.Context, quote []byte) (bool, error)

CheckQuote verifies if a quote is valid by doing a simulated call. Returns true if quote is valid, false otherwise.

func (*DcapPortal) CheckZkProof

func (p *DcapPortal) CheckZkProof(ctx context.Context, proof *zkdcap.ZkProof) (bool, error)

CheckZkProof verifies if a ZK proof is valid by doing a simulated call. Returns true if proof is valid, false otherwise.

func (*DcapPortal) Client

func (p *DcapPortal) Client() *ethclient.Client

Client returns the Ethereum client associated with the DcapPortal.

func (*DcapPortal) EstimateAttestationFee

func (p *DcapPortal) EstimateAttestationFee(tx *types.Transaction, callback *Callback) *big.Int

EstimateAttestationFee estimates the attestation fee for a transaction.

func (*DcapPortal) EstimateBaseFeeVerifyAndAttestWithZKProof

func (p *DcapPortal) EstimateBaseFeeVerifyAndAttestWithZKProof(ctx context.Context, zkProof *zkdcap.ZkProof) (*big.Int, error)

EstimateFeeBaseVerifyAndAttestWithZKProof estimates the base fee for ZK proof verification and attestation. The actual fee will be base fee multiplied by gas price.

func (*DcapPortal) EstimateBaseFeeVerifyOnChain

func (p *DcapPortal) EstimateBaseFeeVerifyOnChain(ctx context.Context, rawQuote []byte) (*big.Int, error)

EstimateFeeBaseVerifyOnChain estimates the base fee for quote verification. The actual fee will be base fee multiplied by gas price.

func (*DcapPortal) GenerateZkProof

func (p *DcapPortal) GenerateZkProof(ctx context.Context, ty zkdcap.ZkType, quote []byte) (*zkdcap.ZkProof, error)

GenerateZkProof generates zero-knowledge proof for the given quote. Returns error if zkproof client is not initialized or proof generation fails.

Note: EnableZkProof() should be called before using this function.

func (*DcapPortal) Pccs

func (d *DcapPortal) Pccs() *pccs.Client

Pccs returns the PCCS server instance associated with the DcapPortal.

func (*DcapPortal) PrintAttestationFee

func (p *DcapPortal) PrintAttestationFee(tx *types.Transaction, callback *Callback, receipt *types.Receipt)

PrintAttestationFee prints the attestation fee details for a transaction.

func (*DcapPortal) VerifyAndAttestOnChain

func (p *DcapPortal) VerifyAndAttestOnChain(opts *bind.TransactOpts, rawQuote []byte, callback *Callback) (*types.Transaction, error)

VerifyOnChain submits quote for on-chain verification with callback. Returns transaction hash and error if submission fails.

func (*DcapPortal) VerifyAndAttestWithZKProof

func (p *DcapPortal) VerifyAndAttestWithZKProof(opts *bind.TransactOpts, zkProof *zkdcap.ZkProof, callback *Callback) (*types.Transaction, error)

VerifyAndAttestWithZKProof verifies and attests the ZK proof on chain. Returns transaction hash and error if verification fails.

func (*DcapPortal) WaitTx

func (p *DcapPortal) WaitTx(ctx context.Context, tx *types.Transaction) <-chan *types.Receipt

WaitTx waits for the transaction receipt and returns it through a channel.

type DcapPortalOption

type DcapPortalOption func(context.Context, *DcapPortal) error

func WithChainConfig

func WithChainConfig(chainConfig *ChainConfig) DcapPortalOption

Custom chain config

func WithClient

func WithClient(client *ethclient.Client) DcapPortalOption

Connect to the portal with the provided client

func WithEndpoint

func WithEndpoint(endpoint string) DcapPortalOption

Connect to the portal with the provided endpoint

func WithPrivateKey

func WithPrivateKey(key string) DcapPortalOption

func WithZkProof

func WithZkProof(cfg *zkdcap.ZkProofConfig) DcapPortalOption

Enable zero-knowledge proof functionality cfg can be nil

type JsonError

type JsonError interface {
	Error() string
	ErrorCode() int
	ErrorData() interface{}
}

JsonError represents a JSON error with code and data

Jump to

Keyboard shortcuts

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