Help us shape the future of Go! Take the 2026 Go Developer Survey

sessionkey

package
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package sessionkey provides SessionKeyRegistry authorization management on Filecoin EVM.

Session keys are authorized by a root account with specific EIP-712 permissions (e.g., CreateDataSet, AddPieces) and a time-bounded expiry. This package manages those on-chain authorizations and expiry checks. A root Client can remain the storage payer and direct transaction signer while a separately authorized key signs Storage EIP-712 messages.

This is separate from the signer package because session keys represent a higher-level authorization concept, not just a signing primitive.

Permission values

CreateDataSetPermission, AddPiecesPermission, SchedulePieceRemovalsPermission, and TerminateServicePermission return independent Permission values. DefaultFWSSPermissions returns a new slice on each call. Changing these values or slices does not change SDK defaults.

Nil permissions select all four standard permissions for login, revocation, and expiry queries. An explicit empty slice selects none. Pass a custom slice through LoginOptions, RevokeOptions, or Service.GetExpirations to choose permissions for an individual operation.

Migrating permission variables

The standard permissions and DefaultFWSSPermissions are now functions. Replace variable reads with calls, for example AddPiecesPermission(). To take a permission's address or slice its bytes, first assign it to a local variable:

permission := AddPiecesPermission()
bytes := permission[:]
pointer := &permission
Example

Example shows querying session-key authorization expirations for a set of permissions. In practice a Service is obtained from synapse.Client.SessionKey.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ethereum/go-ethereum/common"
	"github.com/strahe/synapse-go/sessionkey"
)

func main() {
	var svc *sessionkey.Service // obtained from synapse.Client.SessionKey()

	ctx := context.Background()
	root := common.HexToAddress("0x...")
	sk := common.HexToAddress("0x...")

	perms := []sessionkey.Permission{
		sessionkey.AddPiecesPermission(),
		sessionkey.TerminateServicePermission(),
	}
	exp, err := svc.GetExpirations(ctx, root, sk, perms)
	for p, epoch := range exp {
		fmt.Printf("%s expires at %d\n", p, epoch)
	}
	if err != nil {
		log.Printf("partial expiry lookup failure: %v", err)
	}
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrClosed = lifecycle.ErrClosed

ErrClosed is returned when a method is called after the owning Client has been closed. It aliases the shared closed-client sentinel.

View Source
var ErrInvalidArgument = errors.New("sessionkey: invalid argument")

ErrInvalidArgument is returned, wrapped via fmt.Errorf with %w, when a caller passes an argument that violates a precondition (nil pointer, zero address, negative/invalid amount, past ExpiresAt timestamp). Match it with errors.Is(err, sessionkey.ErrInvalidArgument).

View Source
var ErrTxFailed = types.ErrTxFailed

ErrTxFailed reports that a transaction was mined but reverted on-chain. Use errors.Is to match errors returned by state-changing calls.

This is a convenience re-export of [types.ErrTxFailed]; the two values are the same sentinel and can be matched interchangeably.

View Source
var ErrUninitialized = errors.New("sessionkey: service not initialized; use sessionkey.New")

ErrUninitialized is returned when a method is invoked on a zero-value Service (one that was not constructed via New).

Functions

func PermissionName added in v0.4.0

func PermissionName(p Permission) (string, bool)

PermissionName returns the EIP-712 primary type name for a standard FWSS permission. Unknown permissions return false and should be rendered by hash.

Types

type Backend

type Backend interface {
	bind.ContractBackend
	TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error)
	BlockNumber(ctx context.Context) (uint64, error)
}

Backend provides the Ethereum RPC methods used by Service. The root Client supplies its configured Ethereum client.

type Expirations

type Expirations map[Permission]uint64

Expirations maps each Permission to its expiry timestamp (Unix epoch seconds). A zero value means the permission is not authorised.

func DefaultEmptyExpirations

func DefaultEmptyExpirations() Expirations

DefaultEmptyExpirations returns an Expirations map containing the four default FWSS permissions, each with a zero (expired) expiry.

type LoginOptions

type LoginOptions struct {
	// Permissions to authorise. Nil uses a fresh [DefaultFWSSPermissions] slice;
	// an explicit empty slice authorises no permissions.
	Permissions []Permission
	// ExpiresAt is the Unix timestamp (seconds) when the session key
	// authorisation expires. Zero defaults to time.Now().Unix() + 3600
	// (one hour from now).
	ExpiresAt uint64
	// Origin is an application identifier stored on-chain. Defaults to
	// "synapse".
	Origin string
}

LoginOptions configures a Login or LoginAndFund call. All fields are optional; nil or zero values cause sensible defaults to be applied.

type NonceManager added in v0.5.0

type NonceManager interface {
	Acquire(ctx context.Context) (nonce uint64, release func(), err error)
}

NonceManager serializes transaction-nonce acquisition for one signing address. The root Client supplies a shared coordinator. On success, Acquire must return the next pending nonce and a non-nil, idempotent release function. Callers may invoke release more than once, but must invoke it after broadcasting or abandoning the transaction.

type Options

type Options struct {
	// Backend is the Ethereum RPC client. Required.
	Backend Backend
	// ChainID of the target FEVM chain. Required; must be > 0.
	ChainID sdktypes.ChainID
	// RegistryAddress is the SessionKeyRegistry contract address. Required.
	RegistryAddress common.Address
	// Signer is used to sign transactions. Required for write methods
	// (Login, Revoke); may be nil when the Service is used for reads only.
	Signer signer.EVMSigner
	// Logger is optional. When nil, logging is disabled.
	Logger *slog.Logger
	// NonceManager is optional. The root synapse Client injects a shared
	// coordinator across all write-capable services; standalone callers may
	// leave this nil to create one for this Service. A typed-nil value is treated
	// as nil.
	NonceManager NonceManager
	// ReceiptWait overrides the default receipt polling timeout.
	ReceiptWait time.Duration
	// MaxMulticallCalls limits the number of actual contract calls in each
	// dynamic Multicall3 request. Zero uses the default of 64. Negative values
	// are invalid. Batches execute serially and may observe different blocks;
	// this count does not bound request or response bytes, gas, or execution
	// time.
	MaxMulticallCalls int
	// Lifecycle is checked before service operations that can touch configured
	// backends. Any error returned by CheckClosed is returned without touching
	// those backends. The root synapse Client injects a shared checker whose
	// closed error matches ErrClosed. Nil is allowed for standalone use. A
	// typed-nil value is treated as nil.
	Lifecycle interface{ CheckClosed() error }
}

Options bundles the dependencies for constructing a Service.

type Permission

type Permission [32]byte

Permission is a 32-byte keccak256 hash that identifies a specific operation that a session key may perform on behalf of the root account.

Each permission corresponds to the keccak256 of the EIP-712 encodeType for that operation's primary type (including referenced struct types, sorted alphabetically).

func AddPiecesPermission

func AddPiecesPermission() Permission

AddPiecesPermission returns the permission to add pieces to a dataset.

encodeType: "AddPieces(uint256 clientDataSetId,uint256 nonce,Cid[] pieceData,PieceMetadata[] pieceMetadata)Cid(bytes data)MetadataEntry(string key,string value)PieceMetadata(uint256 pieceIndex,MetadataEntry[] metadata)"

func CreateDataSetPermission

func CreateDataSetPermission() Permission

CreateDataSetPermission returns the permission to create new datasets.

encodeType: "CreateDataSet(uint256 clientDataSetId,address payee,MetadataEntry[] metadata)MetadataEntry(string key,string value)"

func DefaultFWSSPermissions

func DefaultFWSSPermissions() []Permission

DefaultFWSSPermissions returns an independent slice of the four standard FWSS permissions, ordered as create dataset, add pieces, schedule removals, and terminate service. Modifying it does not change future defaults.

func PermissionFromEncodeType

func PermissionFromEncodeType(encodeType string) Permission

PermissionFromEncodeType computes a Permission from the full EIP-712 encodeType string by taking its keccak256 hash.

func SchedulePieceRemovalsPermission

func SchedulePieceRemovalsPermission() Permission

SchedulePieceRemovalsPermission returns the permission to schedule piece removals from a dataset.

encodeType: "SchedulePieceRemovals(uint256 clientDataSetId,uint256[] pieceIds)"

func TerminateServicePermission added in v0.4.0

func TerminateServicePermission() Permission

TerminateServicePermission returns the permission to terminate a service.

encodeType: "TerminateService(uint256 dataSetId)"

func (Permission) Hex

func (p Permission) Hex() string

Hex returns the permission hash as a 0x-prefixed hex string.

func (Permission) String

func (p Permission) String() string

String implements fmt.Stringer and returns the same as Hex.

type RevokeOptions

type RevokeOptions struct {
	// Permissions to revoke. Nil uses a fresh [DefaultFWSSPermissions] slice;
	// an explicit empty slice revokes no permissions.
	Permissions []Permission
	// Origin is an application identifier stored on-chain. Defaults to
	// "synapse".
	Origin string
}

RevokeOptions configures a Revoke call.

type Service

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

Service provides session key management against the SessionKeyRegistry contract. It handles login (authorization), revocation, and expiry queries.

It is safe for concurrent use. All state-changing calls return a sdktypes.WriteResult whose Receipt is only populated when WithWait is supplied.

func New

func New(opts Options) (*Service, error)

New constructs a Service.

func (*Service) AuthorizationExpiry

func (s *Service) AuthorizationExpiry(ctx context.Context, rootAddr, sessionKeyAddr common.Address, permission Permission) (uint64, error)

AuthorizationExpiry returns the Unix timestamp at which a specific permission for a session key expires. Returns 0 if not authorised.

func (*Service) GetExpirations

func (s *Service) GetExpirations(ctx context.Context, rootAddr, sessionKeyAddr common.Address, permissions []Permission) (Expirations, error)

GetExpirations queries the on-chain authorization expiry for each of the given permissions. It attempts serial, size-limited Multicall3 batches first and falls back to per-permission sequential reads if any transport-level batch call fails.

GetExpirations returns the best-effort partial Expirations together with errors.Join of every per-permission lookup error. Nil permissions use DefaultFWSSPermissions; an explicit empty slice queries no permissions. Expiry values of 0 mean "not authorized" or "revoked" — these are valid state, not errors, and are not reflected in the returned error.

Callers should therefore check both the map and err:

exps, err := svc.GetExpirations(ctx, root, key, nil)
// exps may be partially populated even when err != nil.
if err != nil { /* log / surface partial failure */ }

func (*Service) IsExpired

func (s *Service) IsExpired(ctx context.Context, rootAddr, sessionKeyAddr common.Address, permission Permission) (bool, error)

IsExpired returns true when the given permission for a session key has expired (i.e., the on-chain expiry is in the past).

func (*Service) Login

func (s *Service) Login(ctx context.Context, sessionKeyAddr common.Address, opts ...WriteOption) (*sdktypes.WriteResult, error)

Login authorises the given session key address with default options (DefaultFWSSPermissions, 1 hour expiry, origin "synapse").

func (*Service) LoginAndFund

func (s *Service) LoginAndFund(ctx context.Context, sessionKeyAddr common.Address, value *big.Int, opts ...WriteOption) (*sdktypes.WriteResult, error)

LoginAndFund authorises a session key and transfers value (native FIL) in the same transaction using the payable loginAndFund method.

func (*Service) LoginAndFundWithOptions

func (s *Service) LoginAndFundWithOptions(ctx context.Context, sessionKeyAddr common.Address, value *big.Int, loginOpts *LoginOptions, writeOpts ...WriteOption) (*sdktypes.WriteResult, error)

LoginAndFundWithOptions is the full-option variant of LoginAndFund.

func (*Service) LoginWithOptions

func (s *Service) LoginWithOptions(ctx context.Context, sessionKeyAddr common.Address, loginOpts *LoginOptions, writeOpts ...WriteOption) (*sdktypes.WriteResult, error)

LoginWithOptions authorises the given session key address with custom login options.

func (*Service) RegistryAddress

func (s *Service) RegistryAddress() common.Address

RegistryAddress returns the configured SessionKeyRegistry contract address.

func (*Service) Revoke

func (s *Service) Revoke(ctx context.Context, sessionKeyAddr common.Address, opts ...WriteOption) (*sdktypes.WriteResult, error)

Revoke revokes default FWSS permissions from a session key.

func (*Service) RevokeWithOptions

func (s *Service) RevokeWithOptions(ctx context.Context, sessionKeyAddr common.Address, revokeOpts *RevokeOptions, writeOpts ...WriteOption) (*sdktypes.WriteResult, error)

RevokeWithOptions revokes specific permissions from a session key.

type SessionKey

type SessionKey struct {
	// Address is the session key's own address.
	Address common.Address
	// RootAddress is the root account that authorized this session key.
	RootAddress common.Address
	// KeyType identifies the key algorithm (e.g. "secp256k1").
	KeyType string
	// Expirations maps each permission to its on-chain expiry.
	Expirations Expirations
}

SessionKey represents a session key with its current authorization state. It does not perform event watching — call GetExpirations to refresh.

func (*SessionKey) HasPermission

func (sk *SessionKey) HasPermission(p Permission) bool

HasPermission returns true if the given permission is currently active (i.e., its expiry is in the future).

func (*SessionKey) HasPermissionAt

func (sk *SessionKey) HasPermissionAt(t time.Time, p Permission) bool

HasPermissionAt returns true if the given permission is active at the specified point in time. This variant enables deterministic testing.

func (*SessionKey) HasPermissions

func (sk *SessionKey) HasPermissions(ps []Permission) bool

HasPermissions returns true if all given permissions are currently active.

type WriteOption

type WriteOption func(*writeConfig)

WriteOption tunes the behaviour of a single state-changing call. Nil options are ignored.

func WithConfirmations

func WithConfirmations(n uint64) WriteOption

WithConfirmations requires N block confirmations in addition to WithWait. Has no effect unless WithWait is also passed with a positive timeout.

func WithWait

func WithWait(timeout time.Duration) WriteOption

WithWait makes the call block until the transaction is mined, or the given timeout elapses. Use zero or a negative duration to return as soon as the tx is broadcast (the default).

type WriteResult

type WriteResult = sdktypes.WriteResult

WriteResult is a convenience re-export of [types.WriteResult]. The two names refer to the same type and are interchangeable.

Jump to

Keyboard shortcuts

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