Documentation ¶
Overview ¶
Package session implements a session to which a user can attach his or her credentials. He or she can then use the session to open, use, and settle state channels.
Each session runs an instance of state channel network client and is owned by the user of the session. Data within a session is continuously persisted in runtime, allowing the user to close and restore the same session later.
Index ¶
- Constants
- type ChClient
- type ChProposalResponder
- type ChUpdateResponder
- type ChainConfig
- type Channel
- func (ch *Channel) ChallengeDurSecs() uint64
- func (ch *Channel) Close(pctx context.Context) (perun.ChInfo, perun.APIError)
- func (ch *Channel) Currencies() []perun.Currency
- func (ch *Channel) Currency(symbol string) (int, perun.Currency, bool)
- func (ch *Channel) GetChInfo() perun.ChInfo
- func (ch *Channel) HandleAdjudicatorEvent(e pchannel.AdjudicatorEvent)
- func (ch *Channel) HandleUpdate(currState *pchannel.State, chUpdate pclient.ChannelUpdate, ...)
- func (ch *Channel) ID() string
- func (ch *Channel) Parts() []string
- func (ch *Channel) RespondChUpdate(pctx context.Context, updateID string, accept bool) (perun.ChInfo, perun.APIError)
- func (ch *Channel) SendChUpdate(pctx context.Context, updater perun.StateUpdater) (perun.ChInfo, perun.APIError)
- func (ch *Channel) SubChUpdates(notifier perun.ChUpdateNotifier) perun.APIError
- func (ch *Channel) UnsubChUpdates() perun.APIError
- type Closer
- type Config
- type Error
- type PChannel
- type Session
- func (s *Session) AddPeerID(peerID perun.PeerID) perun.APIError
- func (s *Session) Close(force bool) ([]perun.ChInfo, perun.APIError)
- func (s *Session) DeployAssetERC20(tokenAddr string) (assetAddr string, _ perun.APIError)
- func (s *Session) GetCh(chID string) (perun.ChAPI, perun.APIError)
- func (s *Session) GetChsInfo() []perun.ChInfo
- func (s *Session) GetPeerID(alias string) (perun.PeerID, perun.APIError)
- func (s *Session) HandleProposal(chProposal pclient.ChannelProposal, responder *pclient.ProposalResponder)
- func (s *Session) HandleProposalWInterface(chProposal pclient.ChannelProposal, responder ChProposalResponder)
- func (s *Session) HandleUpdate(currState *pchannel.State, chUpdate pclient.ChannelUpdate, ...)
- func (s *Session) HandleUpdateWInterface(currState *pchannel.State, chUpdate pclient.ChannelUpdate, ...)
- func (s *Session) ID() string
- func (s *Session) OpenCh(pctx context.Context, openingBalInfo perun.BalInfo, app perun.App, ...) (perun.ChInfo, perun.APIError)
- func (s *Session) RespondChProposal(pctx context.Context, chProposalID string, accept bool) (perun.ChInfo, perun.APIError)
- func (s *Session) SubChProposals(notifier perun.ChProposalNotifier) perun.APIError
- func (s *Session) UnsubChProposals() perun.APIError
- type User
- type UserConfig
- type WalletConfig
Constants ¶
const ( ResTypeUpdate perun.ResourceType = "update" ResTypeUpdateSub perun.ResourceType = "updatesSub" ResTypeChannel perun.ResourceType = "channel" ResTypeProposal perun.ResourceType = "proposal" ResTypeProposalSub perun.ResourceType = "proposalsSub" ResTypePeerID perun.ResourceType = "peerID" ResTypeSession perun.ResourceType = "session" ResTypeCurrency perun.ResourceType = "currency" )
Enumeration of valid resource types for used in ResourceNotFound and ResourceExists errors.
const ( ArgNameAmount perun.ArgumentName = "amount" ArgNameCurrency perun.ArgumentName = "currency" ArgNamePeerAlias perun.ArgumentName = "peerAlias" ArgNameOffChainAddr perun.ArgumentName = "offChainAddress" ArgNameConfigFile perun.ArgumentName = "configFile" ArgNamePayee perun.ArgumentName = "payee" ArgNameToken perun.ArgumentName = "token" ArgNameAsset perun.ArgumentName = "asset" )
Enumeration of valid argument names for using in InvalidArgument error.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ChClient ¶ added in v0.6.0
type ChClient interface { perun.Registerer ProposeChannel(context.Context, pclient.ChannelProposal) (PChannel, error) Handle(pclient.ProposalHandler, pclient.UpdateHandler) Channel(pchannel.ID) (PChannel, error) Close() error EnablePersistence(ppersistence.PersistRestorer) OnNewChannel(handler func(PChannel)) Restore(context.Context) error RestoreChs(databaseDir string, timeout time.Duration, handler func(PChannel)) error Log() plog.Logger }
ChClient allows the user to establish off-chain channels and transact on these channels. The channel data are continuously persisted and hence it can be shutdown and restarted without loosing any data.
However, care should be taken when shutting down the client when it has open channels.Because if any channel the user was participating in was closed with a wrong state when the channel client was not running, dispute resolution process will not be triggered.
This interface is defined for isolating the client type from session.
type ChProposalResponder ¶ added in v0.5.0
type ChProposalResponder interface { Accept(context.Context, *pclient.LedgerChannelProposalAcc) (PChannel, error) Reject(ctx context.Context, reason string) error }
ChProposalResponder defines the methods on proposal responder that will be used by the perun node.
type ChUpdateResponder ¶ added in v0.5.0
type ChUpdateResponder interface { Accept(ctx context.Context) error Reject(ctx context.Context, reason string) error }
ChUpdateResponder represents the methods on channel update responder that will be used the perun node.
type ChainConfig ¶ added in v0.6.0
type ChainConfig struct { // URL for connecting to the blockchain node. URL string // ChainID is the unique identifier for different chains in the ethereum ecosystem. ChainID int // ConnTimeout is the timeout used when dialing for new connections to the on-chain node. ConnTimeout time.Duration // OnChainTxTimeout is the timeout to wait for a blockchain transaction to be finalized. OnChainTxTimeout time.Duration // Address of the valid AssetETH and Adjudicator contracts. // These values are set by the node and will not parsed from the user // provided configuration. AssetETH, Adjudicator pwire.Address `yaml:"-"` }
ChainConfig represents the configuration parameters for connecting to blockchain.
type Channel ¶ added in v0.5.0
Channel represents the perun channel established between different parties.
It implements the perun.ChAPI interface.
func (*Channel) ChallengeDurSecs ¶ added in v0.5.0
ChallengeDurSecs returns the challenge duration for the channel (in seconds) for refuting when an invalid/older state is registered on the blockchain closing the channel.
Does not require a mutex lock, as the data will remain unchanged throughout the lifecycle of the channel.
func (*Channel) Close ¶ added in v0.5.0
Close closes the channel. First it tries to finalize the last agreed state of the payment channel off-chain (by sending a finalizing update) and then settling it on the blockchain. If the channel participants reject/not respond to the finalizing update, the last agreed state will be finalized directly on the blockchain. The call will return after this.
The node will then wait for the challenge duration to pass (if the channel was directly settled on the blockchain) and the withdraw the balance as per the settled state to the user's account. It then sends a channel update notification with update types as `Closed`.
If there is an error in the closing update, it will be one of the following codes: - ErrTxTimedOut with TxType: "Conclude" or "ConcludeFinal" when on-chain finalizing tx times out. - ErrTxTimedOut with TxType: "Withdraw" when withdrawing tx times out. - ErrChainNotReachable when connection to blockchain drops while finalizing on-chain or withdrawing. - ErrUnknownInternal
If there is an error returned by this API, it will be one of the following codes: - ErrTxTimedOut with TxType: "Register" when register tx times out. - ErrChainNotReachable when connection to blockchain drops while register. - ErrUnknownInternal.
func (*Channel) Currencies ¶ added in v0.6.0
func (ch *Channel) Currencies() []perun.Currency
Currencies returns the currency interpreters used in the channel.
Does not require a mutex lock, as the data will remain unchanged throughout the lifecycle of the channel.
func (*Channel) Currency ¶ added in v0.5.0
Currency returns the index of this currency in channel balances and the currency interpreter. If symbol is unknown, returns an false.
Does not require a mutex lock, as the data will remain unchanged throughout the lifecycle of the channel.
func (*Channel) GetChInfo ¶ added in v0.5.0
func (ch *Channel) GetChInfo() perun.ChInfo
GetChInfo gets the last agreed state of the specified payment channel.
func (*Channel) HandleAdjudicatorEvent ¶ added in v0.6.0
func (ch *Channel) HandleAdjudicatorEvent(e pchannel.AdjudicatorEvent)
HandleAdjudicatorEvent is invoked when an on-chain event is received from the adjudicator contract. It process the event depending upon its type and whether the channel is finalized (collaborative close) or not (non-collaborative close).
func (*Channel) HandleUpdate ¶ added in v0.5.0
func (ch *Channel) HandleUpdate( currState *pchannel.State, chUpdate pclient.ChannelUpdate, responder ChUpdateResponder)
HandleUpdate handles the incoming updates on an open channel. All updates are sent to a centralized update handler defined on the session. The centrazlied handler identifies the channel and then invokes this function to process the update.
func (*Channel) ID ¶ added in v0.5.0
ID returns the ID of the channel.
Does not require a mutex lock, as the data will remain unchanged throughout the lifecycle of the channel.
func (*Channel) Parts ¶ added in v0.5.0
Parts returns the list of aliases of the channel participants.
Does not require a mutex lock, as the data will remain unchanged throughout the lifecycle of the channel.
func (*Channel) RespondChUpdate ¶ added in v0.5.0
func (ch *Channel) RespondChUpdate(pctx context.Context, updateID string, accept bool) ( perun.ChInfo, perun.APIError)
RespondChUpdate responds to an incoming channel update for which a notification had been received. Response should be sent before the notification expires. Use the `Time` API to fetch current time of the perun node for checking notification expiry.
If there is an error, it will be one of the following codes: - ErrResourceNotFound with ResourceType: "update" when update ID is not known. - ErrUserResponseTimedOut when user responded after time out expired. - ErrUnknownInternal.
func (*Channel) SendChUpdate ¶ added in v0.5.0
func (ch *Channel) SendChUpdate(pctx context.Context, updater perun.StateUpdater) (perun.ChInfo, perun.APIError)
SendChUpdate sends an update on the channel. The state will be passed to the updater function which can update it. The updated state will then be validated and then sent to other participants for their signature.
If there is an error, it will be one of the following codes: - ErrInvalidArgument with Name:"Amount" when any of the amounts is invalid. - ErrPeerRequestTimedOut when peer request times out. - ErrPeerRejected when peer rejects the request. - ErrUnknownInternal.
func (*Channel) SubChUpdates ¶ added in v0.5.0
func (ch *Channel) SubChUpdates(notifier perun.ChUpdateNotifier) perun.APIError
SubChUpdates subscribes to notifications on new incoming channel updates for the specified channel in the session. Only one subscription can be made at a time. Making a new subscription without canceling the previous one will return an error.
See perun.ChUpateNotif for the format of notification.
The incoming channel update received when there was no subscription will have been cached by the node. Once a new subscription is made, node will send these cached requests (if any), as individual notifications. It will then continue to send a notification for each new incoming channel update.
Response to the notifications can be sent using the RespondChUpdate API before the notification expires.
If there is an error, it will be one of the following codes: - ErrResourceExists with ResourceType: "updatesSub" when a subscription already exists.
func (*Channel) UnsubChUpdates ¶ added in v0.5.0
func (ch *Channel) UnsubChUpdates() perun.APIError
UnsubChUpdates unsubscribes from notifications on new incoming channel updates for the specified channel in the specified session.
If there is an error, it will be one of the following codes: - ErrResourceNotFound with ResourceType: "updatesSub" when a subscription does not exist.
type Closer ¶ added in v0.6.0
type Closer interface {
Close() error
}
Closer is used to call close on database.
type Config ¶
type Config struct { User UserConfig IDProviderType string // Type of ID provider. IDProviderURL string // URL for accessing the ID provider. ChainURL string // URL of the blockchain node. ChainID int // See chainconfig. ChainConnTimeout time.Duration // Timeout for connecting to blockchain node. OnChainTxTimeout time.Duration // Timeout to wait for confirmation of on-chain tx. ResponseTimeout time.Duration // Timeout to wait for a response from the peer / user. DatabaseDir string // Path to directory containing persistence database. // Timeout for re-establishing all open channels (if any) that was persisted during the // previous running instance of the node. PeerReconnTimeout time.Duration // Address of the valid AssetETH and Adjudicator contracts. // These values are set by the node and will not parsed from the user // provided configuration. AssetETH, Adjudicator pwire.Address `yaml:"-"` }
Config defines the parameters required to configure a session.
func ParseConfig ¶
ParseConfig parses the session configuration from a file.
type Error ¶ added in v0.6.0
type Error string
Error type is used to define error constants for this package.
const ( // For failed pre-condition. ErrChClosed Error = "action not allowed on a closed channel" ErrSessionClosed Error = "action not allowed on a closed session" // For invalid config. ErrUnsupportedType Error = "type not supported, see node config for supported types" ErrRepeatedPeerAlias Error = "found repeated entries but each value should be unique" ErrEntryForSelfNotFound Error = "own peer alias (self) not found" )
Definition of error constants for this package.
type PChannel ¶ added in v0.6.0
type PChannel interface { Close() error ID() pchannel.ID Idx() pchannel.Index IsClosed() bool Params() *pchannel.Params Peers() []pwire.Address Phase() pchannel.Phase State() *pchannel.State OnUpdate(cb func(from, to *pchannel.State)) UpdateBy(ctx context.Context, update func(*pchannel.State) error) error Settle(ctx context.Context, isSecondary bool) error Watch(pclient.AdjudicatorEventHandler) error }
PChannel represents the methods on the state channel controller defined in go-perun used by the perun node. This interface is introduced for the purpose of mocking during tests.
type Session ¶ added in v0.5.0
Session provides a context for the user to interact with a node. It manages user data (such as keys, peer IDs), and channel client.
It implements the perun.SessionAPI interface. Once established, a user can establish and transact on state channels.
func New ¶
func New(cfg Config, currencyRegistry perun.ROCurrencyRegistry, contractRegistry perun.ContractRegistry) ( *Session, perun.APIError)
New initializes a SessionAPI instance for the given configuration, read-only currency registry and returns an instance of it. All methods on it are safe for concurrent use.
func (*Session) AddPeerID ¶ added in v0.5.0
func (s *Session) AddPeerID(peerID perun.PeerID) perun.APIError
AddPeerID adds the peer ID to the ID provider instance of the session.
If there is an error, it will be one of the following codes: - ErrFailedPrecondition when the session is closed. - ErrResourceExists with ResourceType: "peerID" when peer ID is already registered - ErrInvalidArgument with Name:"peerAlias" when peer alias is used for another peer, - ErrInvalidArgument with Name:"offChainAddress" when off-chain address is invalid. - ErrUnknownInternal.
func (*Session) Close ¶ added in v0.5.0
Close closes the specified session. All session data will be persisted to disk.
`Force` parameter determines what happens when there are open channels in the session.
- If `False` the API returns an error when there are open channels. This should be used by default.
- If `True`, the session is forcibly closed and the API returns list of open channels that were persisted. When a session is re-opened with the same config file, these channels can be restored in open state. However, use this with caution, as closing a session with open channels creates a possibility for channel participants in any of the those open open channels to register an older, invalid state on the blockchain and finalize it.
If there is an error, it will be one of the following codes:
- ErrFailedPrecondition when the session is closed.
- ErrFailedPreCondition when force=false and unclosed channels exists. Additional Info will contain an extra field: OpenChannelsInfo that contains a list of Channel Info.
- ErrUnknownInternal.
func (*Session) DeployAssetERC20 ¶ added in v0.6.0
DeployAssetERC20 deploys a new ERC20 asset holder contract for the given token.
If there is an error, it will be one of the following codes: - ErrFailedPreCondition when session is closed - ErrInvalidArgument with Name:"token", when token address cannot be parsed. - ErrTxTimedOut when there is tx timed error while funding. - ErrChainNotReachable when connection to blockchain drops while deploying. - ErrUnknownInternal.
func (*Session) GetCh ¶ added in v0.5.0
GetCh is an internal API that retreives the channel API instance corresponding to the given channel ID.
The channel instance is safe for concurrent user.
If there is an error, it will be one of the following codes: - perun.ErrResourceNotFound when the channel ID is not known.
func (*Session) GetChsInfo ¶ added in v0.5.0
func (s *Session) GetChsInfo() []perun.ChInfo
GetChsInfo gets the list of all channels in the session with their latest agreed state.
func (*Session) GetPeerID ¶ added in v0.5.0
GetPeerID gets the peer ID for the given alias from the ID provider instance of the session.
If there is an error, it will be one of the following codes: - ErrFailedPrecondition when the session is closed. - ErrResourceNotFound with ResourceType: "peerID" when peer alias is not known.
func (*Session) HandleProposal ¶ added in v0.5.0
func (s *Session) HandleProposal(chProposal pclient.ChannelProposal, responder *pclient.ProposalResponder)
HandleProposal is a handler to be registered on the channel client for processing incoming channel proposals.
func (*Session) HandleProposalWInterface ¶ added in v0.5.0
func (s *Session) HandleProposalWInterface(chProposal pclient.ChannelProposal, responder ChProposalResponder)
HandleProposalWInterface is the actual implemention of HandleProposal that takes arguments as interface types.
It is implemented this way to enable easier testing.
func (*Session) HandleUpdate ¶ added in v0.5.0
func (s *Session) HandleUpdate( currState *pchannel.State, chUpdate pclient.ChannelUpdate, responder *pclient.UpdateResponder)
HandleUpdate is a handler to be registered on the channel client for processing incoming channel updates. This function just identifies the channel to which update is received and invokes the handler for that channel.
func (*Session) HandleUpdateWInterface ¶ added in v0.5.0
func (s *Session) HandleUpdateWInterface( currState *pchannel.State, chUpdate pclient.ChannelUpdate, responder ChUpdateResponder)
HandleUpdateWInterface is the actual implemention of HandleUpdate that takes arguments as interface types. It is implemented this way to enable easier testing.
If the session is closed, it drops the incoming updates.
func (*Session) OpenCh ¶ added in v0.5.0
func (s *Session) OpenCh(pctx context.Context, openingBalInfo perun.BalInfo, app perun.App, challengeDurSecs uint64) ( perun.ChInfo, perun.APIError)
OpenCh proposes a channel to the participants with the specified opening balance and app, funds it on the blockchain when the proposal is accepted and sets it up for off-chain transactions when all the participants have funded the channel on the blockchain.
`Challenge duration` is the time available for the node to refute in case of disputes when a state is registered on the blockchain.
If there is an error, it will be one of the following codes: - ErrFailedPrecondition when the session is closed. - ErrResourceNotFound with ResourceType: "peerID" when any of the peer aliases are not known. - ErrResourceNotFound with ResourceType: "currency" when the currency is not known. - ErrInvalidArgument with Name:"amount" when any of the amounts is invalid. - ErrPeerRequestTimedOut when peer request times out. - ErrPeerRejected when peer rejects the request. - ErrPeerNotFunded when peer did not fund the channel in time. - ErrTxTimedOut with TxType: "Fund" when funding tx times out. - ErrChainNotReachable when connection to blockchain drops while funding. - ErrUnknownInternal.
func (*Session) RespondChProposal ¶ added in v0.5.0
func (s *Session) RespondChProposal(pctx context.Context, chProposalID string, accept bool) ( perun.ChInfo, perun.APIError)
RespondChProposal responds to the specified channel proposal for which a notification had been received. Response should be sent before the notification expires. Use the `Time` API to fetch current time of the perun node as as reference for checking notification expiry.
If there is an error, it will be one of the following codes: - ErrFailedPrecondition when the session is closed. - ErrResourceNotFound with ResourceType: "proposal" when proposal ID is not known. - ErrPeerNotFunded when peer did not fund the channel in time. - ErrUserResponseTimedOut when user responded after time out expired. - ErrTxTimedOut with TxType: "Fund" when there is tx timed error while funding. - ErrChainNotReachable when connection to blockchain drops while funding. - ErrUnknownInternal.
func (*Session) SubChProposals ¶ added in v0.5.0
func (s *Session) SubChProposals(notifier perun.ChProposalNotifier) perun.APIError
SubChProposals subscribes to notifications on new incoming channel proposals in the session. Only one subscription can be made at a time. Making a new subscription without canceling the previous one will return an error.
See perun.ChProposalNotif for the format of notification.
The incoming channel proposal received when there was no subscription will have been cached by the node. Once a new subscription is made, node will send these cached requests (if any), as individual notifications. It will then continue to send a notification for each new incoming channel proposal.
Response to the notifications can be sent using the RespondChProposal API before the notification expires.
If the proposal was received from a `Peer ID` that is not found in the ID provider of the session, the proposal will be automatically rejected by the node. User will still receive a notification of this proposal with the `Alias` of the peer set to the hex representation of its off-chain address in the `Opening Balance` and the app. These notifications should not be responded to. If the user till responds to it, a ErrResourceNotFound error will be returned.
If there is an error, it will be one of the following codes: - ErrFailedPrecondition when the session is closed. - ErrResourceExists with ResourceType: "proposalsSub" when a subscription already exists.
func (*Session) UnsubChProposals ¶ added in v0.5.0
func (s *Session) UnsubChProposals() perun.APIError
UnsubChProposals unsubscribes from notifications on new incoming channel proposals in the specified session.
If there is an error, it will be one of the following codes: - ErrFailedPrecondition when the session is closed. - ErrResourceNotFound with ResourceType: "proposalsSub" when a subscription does not exist.
type User ¶ added in v0.6.0
type User struct { perun.PeerID OnChain perun.Credential // Account for funding the channel and the on-chain transactions. OffChain perun.Credential // Account (corresponding to off-chain address) used for signing authentication messages. // List of participant addresses for this user in each open channel. // OffChain credential is used for managing all these accounts. PartAddrs []pwallet.Address }
User represents a participant in the off-chain network that uses a session on this node for sending transactions.
func NewUnlockedUser ¶
func NewUnlockedUser(wb perun.WalletBackend, cfg UserConfig) (User, perun.APIError)
NewUnlockedUser initializes a user and unlocks onChaina and offChain accounts.
type UserConfig ¶
type UserConfig struct { Alias string OnChainAddr string OnChainWallet WalletConfig PartAddrs []string OffChainAddr string OffChainWallet WalletConfig CommAddr string CommType string }
UserConfig defines the parameters required to configure a user. Address strings should be parsed using the wallet backend.
type WalletConfig ¶
WalletConfig defines the parameters required to configure a wallet.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package sessiontest implements test helpers for functionalities defined in session.
|
Package sessiontest implements test helpers for functionalities defined in session. |