tokens

package
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AddToken    = "store-token"
	DeleteToken = "delete-token"
)

Variables

This section is empty.

Functions

func WrapMetadataWithType

func WrapMetadataWithType(typ driver.Type, id driver.Metadata) (driver.Metadata, error)

WrapMetadataWithType creates a new TypedMetadata with the given type and raw representation, and returns its serialized bytes.

func WrapWithType

func WrapWithType(typ driver.Type, id driver.Token) (driver.Token, error)

WrapWithType creates a new TypedToken with the given type and raw representation, and returns its serialized bytes.

Types

type Cache

type Cache interface {
	// Get retrieves a cache entry by key.
	Get(key string) (*CacheEntry, bool)
	// Add adds a new entry to the cache.
	Add(key string, value *CacheEntry)
	// Delete removes an entry from the cache.
	Delete(key string)
}

Cache defines the interface for caching token requests and their extracted actions.

type CacheEntry

type CacheEntry struct {
	// Request is the original token request.
	Request *token.Request
	// ToSpend is the list of token IDs to be marked as spent.
	ToSpend []*token2.ID
	// ToAppend is the list of tokens to be added to the local store.
	ToAppend []TokenToAppend
	// MsgToSign is the serialized message that was signed.
	MsgToSign []byte
}

CacheEntry represents a cached token request along with its pre-extracted spend and append actions.

type DBStorage

type DBStorage struct {
	// Notifier is used to publish events when tokens are added or deleted.
	Notifier events.Publisher
	// TokenDB is the underlying persistent store for tokens.
	TokenDB *tokendb.StoreService
	// TMSID is the identifier for the TMS this storage belongs to.
	TMSID token.TMSID
}

DBStorage provides a high-level wrapper over TokenDB for managing token persistence. It handles transaction orchestration and event notification.

func NewDBStorage

func NewDBStorage(notifier events.Publisher, tokenDB *tokendb.StoreService, tmsID token.TMSID) (*DBStorage, error)

NewDBStorage creates a new DBStorage instance.

func (*DBStorage) ContinueTransaction

func (d *DBStorage) ContinueTransaction(tx dbdriver.Transaction) (*DBTransaction, error)

ContinueTransaction starts a new transaction for local storage operations.

func (*DBStorage) NewTransaction

func (d *DBStorage) NewTransaction() (*DBTransaction, error)

NewTransaction starts a new transaction for local storage operations.

func (*DBStorage) StorePublicParams

func (d *DBStorage) StorePublicParams(ctx context.Context, raw []byte) error

StorePublicParams persists the public parameters associated with the TMS.

func (*DBStorage) TransactionExists

func (d *DBStorage) TransactionExists(ctx context.Context, id string) (bool, error)

TransactionExists checks if a transaction with the given ID has already been recorded in local storage.

type DBTransaction

type DBTransaction struct {
	// Notifier is used to publish events upon successful deletion or addition.
	Notifier events.Publisher
	// Tx is the underlying database transaction.
	Tx *tokendb.Transaction
	// TMSID is the TMS identifier for the transaction.
	TMSID token.TMSID
	// contains filtered or unexported fields
}

DBTransaction encapsulates a single atomic update to the token database.

Events recorded while the transaction is open are buffered and published only once the transaction has been committed, so that a subscriber never observes a token that is later rolled back. A DBTransaction is not safe for concurrent use, like the underlying database transaction it wraps.

func NewTransaction

func NewTransaction(notifier events.Publisher, tx *tokendb.Transaction, tmsID token.TMSID) (*DBTransaction, error)

NewTransaction creates a new transaction wrapper.

func (*DBTransaction) AppendToken

func (t *DBTransaction) AppendToken(ctx context.Context, tta TokenToAppend) error

AppendToken records a new token in the database and records an add-token event for each of its owners. The events are published only after the transaction commits, see Notify and FlushEvents.

func (*DBTransaction) Commit

func (t *DBTransaction) Commit(ctx context.Context) error

Commit persists all changes made in the transaction and, only if that succeeds, publishes the events recorded for it.

func (*DBTransaction) DeleteToken

func (t *DBTransaction) DeleteToken(ctx context.Context, tokenID token2.ID, deletedBy string) error

DeleteToken removes a single token from the database and records a delete-token event for each of its owners. The events are published only after the transaction commits, see Notify and FlushEvents.

Delete is idempotent: marking an unknown token as spent is not an error, so a failure returned by Delete always signals a real storage failure and is propagated even when the token is not present in the local store. Swallowing it there would let a lost spend be recorded as a processed transaction.

func (*DBTransaction) DeleteTokens

func (t *DBTransaction) DeleteTokens(ctx context.Context, deletedBy string, ids []*token2.ID) error

DeleteTokens removes multiple tokens from the database.

func (*DBTransaction) FlushEvents added in v0.18.0

func (t *DBTransaction) FlushEvents(ctx context.Context)

FlushEvents publishes the events recorded so far, in the order they were recorded, and empties the buffer.

It must be called only after the transaction that produced the events has been successfully committed. Commit does this for transactions owned by this type; when the transaction is owned by the caller (see DBStorage.ContinueTransaction), the caller is responsible for calling FlushEvents after its own commit succeeds. Calling it more than once is safe: the buffer is empty after the first call.

func (*DBTransaction) Notify

func (t *DBTransaction) Notify(ctx context.Context, topic string, tmsID token.TMSID, walletID string, tokenType token2.Type, txID string, index uint64)

Notify records a token-related event for publication on the system's notification bus. The event is not published here: it is buffered until the transaction that produced it has been committed, and then published by FlushEvents. Publishing inside the open transaction would let subscribers observe tokens that are never persisted.

func (*DBTransaction) Rollback

func (t *DBTransaction) Rollback() error

Rollback cancels all changes made in the transaction and discards the events recorded for it, so that nothing is published for a transaction that never reached the store.

func (*DBTransaction) SetSpendableBySupportedTokenTypes

func (t *DBTransaction) SetSpendableBySupportedTokenTypes(ctx context.Context, supportedTokens []token2.Format) error

SetSpendableBySupportedTokenTypes marks all tokens matching the given formats as spendable.

func (*DBTransaction) SetSpendableFlag

func (t *DBTransaction) SetSpendableFlag(ctx context.Context, value bool, ids []*token2.ID) error

SetSpendableFlag updates the spendable status for the given tokens in the database.

type Flags

type Flags struct {
	// Mine is true if the token belongs to one of my wallets.
	Mine bool
	// Auditor is true if I am an auditor for this token.
	Auditor bool
	// Issuer is true if I issued this token.
	Issuer bool
	// Redeemed is true if this token is a redeem (empty owner) attributed to one of my issuer identities.
	Redeemed bool
}

Flags represents the ownership and auditing roles associated with a token.

type GetTMSProviderFunc

type GetTMSProviderFunc = func() *token.ManagementServiceProvider

GetTMSProviderFunc is a function type that returns a token management service provider.

type MetaData

type MetaData interface {
	// SpentTokenID returns the list of token identifiers that have been spent in this transaction.
	SpentTokenID() []*token2.ID
}

MetaData defines the interface for accessing metadata associated with a token request.

type NetworkProvider

type NetworkProvider interface {
	// GetNetwork returns the network for the given network and channel identifiers.
	GetNetwork(network string, channel string) (*network.Network, error)
}

NetworkProvider defines the interface for obtaining a network instance.

type PostCommit added in v0.18.0

type PostCommit = func(ctx context.Context)

PostCommit publishes the token events recorded while the caller's transaction was open.

The caller of AppendValid owns that transaction and therefore decides whether it is committed or rolled back. It must invoke the returned PostCommit once its commit has succeeded, and must not invoke it when the transaction is rolled back: only then do subscribers observe exactly the tokens that were persisted. It is never nil, so it can be called unconditionally on the success path.

type Service

type Service struct {

	// TMSProvider is used to obtain management services for different TMS IDs.
	TMSProvider TMSProvider
	// NetworkProvider is used to interact with the underlying blockchain network.
	NetworkProvider NetworkProvider
	// Storage manages the persistent storage of tokens in TokenDB.
	Storage *DBStorage
	// RequestsCache provides an in-memory cache for pending token requests to optimize commit performance.
	RequestsCache Cache
	// contains filtered or unexported fields
}

Service provides high-level operations for managing the local lifecycle of tokens. It handles the synchronization of tokens between the ledger and the local TokenDB, manages request caching, and provides utilities for state inspection.

func GetService

func GetService(sp token.ServiceProvider, tmsID token.TMSID) (*Service, error)

GetService is a helper function that retrieves the ServiceManager from the provider and returns the Service for the given TMS ID.

func NewService

func NewService(tmsID token.TMSID, TMSProvider TMSProvider, networkProvider NetworkProvider, storage *DBStorage, requestsCache Cache) *Service

func (*Service) AppendValid

func (t *Service) AppendValid(ctx context.Context, tx dbdriver.Transaction, txID token.RequestAnchor, request *token.Request) (postCommit PostCommit, err error)

AppendValid extracts actions from a token request, applies them to the local storage, and sets the transaction status to Confirmed. This is a convenience function that combines Append with SetStatus for valid/confirmed transactions.

The passed transaction is owned by the caller and is neither committed nor finished here. The add-token and delete-token events produced by the applied actions are therefore not published either: they are buffered, and the returned PostCommit publishes them. The caller must invoke it after committing tx, see PostCommit.

func (*Service) CacheRequest

func (t *Service) CacheRequest(ctx context.Context, request *token.Request) error

CacheRequest extracts actions from a token request and caches them locally to avoid redundant parsing during the commit phase.

func (*Service) DeleteTokens

func (t *Service) DeleteTokens(ctx context.Context, ids ...*token2.ID) (err error)

DeleteTokens marks the tokens as spent in the database, attributed to the caller's stack trace.

func (*Service) DeleteTokensBy

func (t *Service) DeleteTokensBy(ctx context.Context, deletedBy string, ids ...*token2.ID) (err error)

DeleteTokensBy marks the tokens identified by ids as spent in the database, attributed to a specific actor.

func (*Service) GetCachedTokenRequest

func (t *Service) GetCachedTokenRequest(txID string) (*token.Request, []byte)

GetCachedTokenRequest retrieves a cached token request and its serialized message.

func (*Service) Parse

func (t *Service) Parse(
	ctx context.Context,
	auth driver.Authorization,
	requestAnchor token.RequestAnchor,
	md MetaData,
	is *token.InputStream,
	os *token.OutputStream,
	auditorFlag bool,
	precision uint64,
	graphHiding bool,
) (toSpend []*token2.ID, toAppend []TokenToAppend, err error)

Parse returns the tokens to store and spend as the result of a transaction

func (*Service) PruneInvalidUnspentTokens

func (t *Service) PruneInvalidUnspentTokens(ctx context.Context) ([]*token2.ID, error)

PruneInvalidUnspentTokens identifies and removes unspent tokens from the local store that are no longer available on the ledger.

func (*Service) SetSpendableBySupportedTokenTypes

func (t *Service) SetSpendableBySupportedTokenTypes(ctx context.Context, types []token2.Format) error

SetSpendableBySupportedTokenTypes sets the spendable flag for all tokens that match the provided formats.

func (*Service) SetSpendableFlag

func (t *Service) SetSpendableFlag(ctx context.Context, value bool, ids ...*token2.ID) error

SetSpendableFlag sets the spendable status for the specified tokens.

func (*Service) SetSupportedTokenFormats

func (t *Service) SetSupportedTokenFormats(tokenTypes []token2.Format) error

SetSupportedTokenFormats updates the list of token formats currently supported by the storage.

func (*Service) StorePublicParams

func (t *Service) StorePublicParams(ctx context.Context, raw []byte) error

StorePublicParams persists the raw byte representation of public parameters in TokenDB.

func (*Service) UnsupportedTokensIteratorBy

func (t *Service) UnsupportedTokensIteratorBy(ctx context.Context, walletID string, typ token2.Type) (driver.UnsupportedTokensIterator, error)

UnsupportedTokensIteratorBy returns an iterator for tokens that are no longer supported, typically used during upgrade processes.

type ServiceManager

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

ServiceManager handles the lifecycle and lazy initialization of Service instances per TMS. It uses a lazy provider to ensure that services are only created when needed.

func NewServiceManager

func NewServiceManager(
	tmsProvider TMSProvider,
	storeServiceManager StoreServiceManager,
	networkProvider NetworkProvider,
	notifier events.Publisher,
) *ServiceManager

NewServiceManager creates a new ServiceManager instance.

func (*ServiceManager) ServiceByTMSId

func (cm *ServiceManager) ServiceByTMSId(tmsID token.TMSID) (*Service, error)

ServiceByTMSId returns the Service instance associated with the given TMS identifier.

type StoreServiceManager

type StoreServiceManager = tokendb.StoreServiceManager

StoreServiceManager defines the interface for obtaining a token database store service by TMS ID.

type TMSProvider

type TMSProvider interface {
	// GetManagementService returns the management service for the given options.
	GetManagementService(opts ...token.ServiceOption) (*token.ManagementService, error)
}

TMSProvider defines the interface for obtaining a token management service.

type TokenMessage

type TokenMessage struct {
	// TMSID is the TMS identifier for the event.
	TMSID token.TMSID
	// WalletID is the unique identifier of the wallet affected by the event.
	WalletID string
	// TokenType is the type of the token.
	TokenType token2.Type
	// TxID is the transaction ID.
	TxID string
	// Index is the token index within the transaction.
	Index uint64
}

TokenMessage contains the details of a token-related event.

type TokenProcessorEvent

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

TokenProcessorEvent encapsulates a message published by the Tokens Service.

func NewTokenProcessorEvent

func NewTokenProcessorEvent(topic string, message *TokenMessage) *TokenProcessorEvent

NewTokenProcessorEvent creates a new event with the given topic and message.

func (*TokenProcessorEvent) Message

func (t *TokenProcessorEvent) Message() any

Message returns the event's payload.

func (*TokenProcessorEvent) Topic

func (t *TokenProcessorEvent) Topic() string

Topic returns the event's topic.

type TokenToAppend

type TokenToAppend struct {
	// TxID is the transaction ID that created this token.
	TxID string
	// Index is the output index of the token within the transaction.
	Index uint64
	// Tok is the de-obfuscated token information.
	Tok *token2.Token
	// TokenOnLedgerFormat is the format of the token as it appears on the ledger.
	TokenOnLedgerFormat token2.Format
	// TokenOnLedger is the raw byte representation of the token output on the ledger.
	TokenOnLedger []byte
	// TokenOnLedgerMetadata is the metadata associated with the token output on the ledger.
	TokenOnLedgerMetadata []byte
	// OwnerType is the type of the token owner's identity.
	OwnerType string
	// OwnerIdentity is the de-obfuscated identity of the owner.
	OwnerIdentity token.Identity
	// OwnerWalletID is the local wallet identifier if the owner is mine.
	OwnerWalletID string
	// Owners is the list of unique identifiers for all recipients/owners.
	Owners []string
	// Issuer is the identity of the token issuer.
	Issuer token.Identity
	// Precision is the number of decimal places for quantity calculations.
	Precision uint64
	// Flags indicates my relationship with this token.
	Flags Flags
}

TokenToAppend contains the detailed information required to store a new token in the database.

type Transaction

type Transaction interface {
	// ID returns the transaction identifier.
	ID() string
	// Network returns the network name the transaction belongs to.
	Network() string
	// Channel returns the channel name.
	Channel() string
	// Namespace returns the namespace (chaincode ID) of the transaction.
	Namespace() string
	// Request returns the underlying token request.
	Request() *token.Request
}

Transaction models a token transaction within Panurus, providing access to its identifiers and request content.

type TypedMetadata

type TypedMetadata struct {
	// Type encodes the metadata version or format type.
	Type driver.Type
	// Metadata encodes the raw byte representation of the metadata itself.
	Metadata driver.Metadata
}

TypedMetadata encodes token metadata along with its type identifier.

func UnmarshalTypedMetadata

func UnmarshalTypedMetadata(metadata driver.Metadata) (*TypedMetadata, error)

UnmarshalTypedMetadata deserializes an ASN.1 encoded byte slice into a TypedMetadata structure.

func (TypedMetadata) Bytes

func (i TypedMetadata) Bytes() ([]byte, error)

Bytes serializes the TypedMetadata into its ASN.1 byte representation.

type TypedToken

type TypedToken struct {
	// Type encodes the token's version or format type (e.g., Fabtoken, Commitment).
	Type driver.Type
	// Token encodes the raw byte representation of the token itself.
	Token driver.Token
}

TypedToken encodes a token representation along with its type identifier. This structure is used to support multiple cryptographic token formats in a unified way.

func UnmarshalTypedToken

func UnmarshalTypedToken(token driver.Token) (*TypedToken, error)

UnmarshalTypedToken deserializes an ASN.1 encoded byte slice into a TypedToken structure.

func (TypedToken) Bytes

func (i TypedToken) Bytes() ([]byte, error)

Bytes serializes the TypedToken into its ASN.1 byte representation.

type UnspendableTokensIterator

type UnspendableTokensIterator = driver.UnsupportedTokensIterator

UnspendableTokensIterator is an alias for the driver's UnsupportedTokensIterator.

Directories

Path Synopsis
core
Code generated by counterfeiter.
Code generated by counterfeiter.

Jump to

Keyboard shortcuts

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