sessionkey

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: May 6, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package sessionkey provides session key management for delegated signing via the SessionKeyRegistry contract on Filecoin EVM.

Session keys allow applications to sign FWSS (Filecoin Warm Storage Service) operations without exposing the main wallet private key. A session key is authorized by the root account with specific EIP-712 permissions (e.g., CreateDataSet, AddPieces) and a time-bounded expiry.

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

Stability

0.x phase: public API may change between minor releases.

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.DeleteDataSetPermission,
	}
	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 AddPiecesPermission = mustPermission("954bdc254591a7eab1b73f03842464d9283a08352772737094d710a4428fd183")

AddPiecesPermission authorises session keys 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)"

View Source
var CreateDataSetPermission = mustPermission("25ebf20299107c91b4624d5bac3a16d32cabf0db23b450ee09ab7732983b1dc9")

CreateDataSetPermission authorises session keys to create new datasets.

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

DefaultFWSSPermissions contains all four standard FWSS permissions. This is the default set used by Login when no explicit permissions are provided.

View Source
var DeleteDataSetPermission = mustPermission("b0988e9a1e5723860e0f59e0469113fb8a0ce9e83f8a1dd9109527eaad225b37")

DeleteDataSetPermission authorises session keys to delete a dataset.

encodeType: "DeleteDataSet(uint256 dataSetId)"

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 an alias of types.ErrTxFailed kept for backwards compatibility; callers can match either 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).

View Source
var SchedulePieceRemovalsPermission = mustPermission("5415701e313bb627e755b16924727217bb356574fe20e7061442c200b0822b22")

SchedulePieceRemovalsPermission authorises session keys to schedule piece removals from a dataset.

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

Functions

This section is empty.

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 is the minimal RPC surface used by the session key service. It is satisfied by *ethclient.Client. Tests can substitute a mock.

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. Defaults to DefaultFWSSPermissions.
	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; zero values cause sensible defaults to be applied.

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.
	NonceManager *txutil.NonceManager
	// ReceiptWait overrides the default receipt polling timeout.
	ReceiptWait time.Duration
	// Lifecycle, when non-nil, ties this Service to the owning Client's
	// close state. After the Lifecycle is closed, every method returns
	// ErrClosed. Nil is allowed for standalone use.
	Lifecycle *lifecycle.Lifecycle
}

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 PermissionFromEncodeType

func PermissionFromEncodeType(encodeType string) Permission

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

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. Defaults to DefaultFWSSPermissions.
	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 a single Multicall3 batch first and falls back to per-permission sequential reads if the transport-level batch call fails.

GetExpirations returns the best-effort partial Expirations together with errors.Join of every per-permission lookup error. 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.

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 kept as an alias for backwards compatibility.

Jump to

Keyboard shortcuts

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