prnm

package module
v0.0.0-...-72d13f4 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2021 License: Apache-2.0 Imports: 27 Imported by: 0

README

Perun mobile bindings

This project provides Android bindings for go-perun called prnm.
Right now, it supports two-party single-asset ledger payment channels.

Security Disclaimer

The authors take no responsibility for any loss of digital assets or other damage caused by the use of this software.
Do not use this software with real funds.

Getting Started

# Install gomobile, see https://godoc.org/golang.org/x/mobile/cmd/gomobile
go get golang.org/x/mobile/cmd/gomobile
gomobile init
# Get perun-eth-mobile
git clone https://github.com/perun-network/perun-eth-mobile
# Generate the bindings
cd perun-eth-mobile
gomobile bind -o android/app/prnm.aar -target=android

👉 More in-depth instructions can be found in DEVELOPING.md.

Structure

The android/ folder is an Android Studio Project, the only two important files are:

  • android/app/src/main/java/network/perun/app/MainActivity.java contains the Apps logic, exemplifying the use of go-perun.
    The MainActivity uses a Node to propose and accept payment channels. The Node is started with a prnm.Config which contains all needed configuration for the underlying prnm.Client. Its contructor creates a ProposalHandler that accepts all incomming channel proposals and forwards the new channels to Node.accept. Node.accept then starts two threads; one with an UpdateHandler that accepts all updates and one as on-chain watcher that reacts to disputes and settling. To propose a channel, Node.propose can be used.
  • android/app/src/main/AndroidManifest.xml lists the needed App permissions; INTERNET,ACCESS_NETWORK_STATE,WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE

After importing the android/ folder in Android Studio, run it in the Emulator or on a real phone.
The opposite party can be either also an App, or a perun-eth-demo-node.

Copyright © 2020 Chair of Applied Cryptography, Technische Universität Darmstadt, Germany. All rights reserved. Use of the source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

Contact us at info@perun.network.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetLogLevel

func SetLogLevel(level int)

SetLogLevel takes a logrus.Level argument. See https://godoc.org/github.com/sirupsen/logrus#Level

Types

type Address

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

Address wraps a go-perun ethereum Address.

func NewAddressFromHex

func NewAddressFromHex(str string) (*Address, error)

NewAddressFromHex creates an Address from the given string. String must be in the form 0x32be343b94f860124dc5fee278fdcbd38c102d88

func (*Address) ToHex

func (a *Address) ToHex() string

ToHex returns the hexadecimal representation of the Address as string. Example: 0x32be343b94f860124dc5fee278fdcbd38c102d88

type Addresses

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

Addresses is a slice of Address'es

func NewAddresses

func NewAddresses(length int) *Addresses

NewAddresses creates a new Addresses with the given length.

func (*Addresses) Get

func (as *Addresses) Get(index int) (*Address, error)

Get returns the element at the given index.

func (*Addresses) Length

func (as *Addresses) Length() int

Length returns the length of the Addresses slice.

func (*Addresses) Set

func (as *Addresses) Set(index int, value *Address) error

Set sets the element at the given index.

type BigInt

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

BigInt wraps a golang math/big.Int. All functions on BigInt have their equivalent in the documentation below. See https://golang.org/pkg/math/big/#Int If we do this as embedding, the functions are skipped because of the wrong return type.

func NewBigIntFromBytes

func NewBigIntFromBytes(data []byte) *BigInt

NewBigIntFromBytes creates a BigInt from a byte slice.

func NewBigIntFromInt64

func NewBigIntFromInt64(v int64) *BigInt

NewBigIntFromInt64 creates a BigInt from an int64.

func NewBigIntFromString

func NewBigIntFromString(data string) (*BigInt, error)

NewBigIntFromString creates a BigInt by parsing a string. A prefix of "0b" or "0B" selects base 2, "0", "0o" or "0O" selects base 8, and "0x" or "0X" selects base 16. Otherwise, the selected base is 10 and no prefix is accepted. Read documentation of https://pkg.go.dev/math/big?tab=doc#Int.SetString for more details.

func NewBigIntFromStringBase

func NewBigIntFromStringBase(data string, base int) (*BigInt, error)

NewBigIntFromStringBase creates a BigInt by parsing a string containing a number of given base.

func (*BigInt) Add

func (b *BigInt) Add(x *BigInt) *BigInt

Add returns the result of the receiver + x. Does not change the reveiver.

func (*BigInt) BigInt

func (b *BigInt) BigInt() *big.Int

BigInt can not be called from Java, only here to improve reusability.

func (*BigInt) Cmp

func (b *BigInt) Cmp(x *BigInt) int

Cmp wraps math/big.Int.Cmp

func (*BigInt) IsWithin

func (b *BigInt) IsWithin(x *BigInt, delta *BigInt) bool

IsWithin returns whether the receiver deviates at most `delta` from `x`.

func (*BigInt) String

func (b *BigInt) String() string

String wraps math/big.Int.String

func (*BigInt) StringBase

func (b *BigInt) StringBase(base int) string

StringBase wraps math/big.Int.Text

func (*BigInt) Sub

func (b *BigInt) Sub(x *BigInt) *BigInt

Sub returns the result of the receiver - x. Does not change the reveiver.

func (*BigInt) ToBytesArray

func (b *BigInt) ToBytesArray() []byte

ToBytesArray wraps math/big.Int.Bytes

func (*BigInt) ToInt64

func (b *BigInt) ToInt64() int64

ToInt64 wraps math/big.Int.Int64

type BigInts

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

BigInts is a slice of BigInt's

func NewBalances

func NewBalances(first, second *BigInt) *BigInts

NewBalances creates a new BigInts of length two with the given values.

func NewBigInts

func NewBigInts(length int) *BigInts

NewBigInts creates a new BitInts with the given length.

func (*BigInts) Data

func (bs *BigInts) Data() []*big.Int

Data can not be called from Java, only here to improve reusability.

func (*BigInts) Get

func (bs *BigInts) Get(index int) (*BigInt, error)

Get returns the element at the given index.

func (*BigInts) Length

func (bs *BigInts) Length() int

Length returns the length of the BigInts slice.

func (*BigInts) Set

func (bs *BigInts) Set(index int, value *BigInt) error

Set sets the element at the given index.

type ChannelProposal

type ChannelProposal struct {
	Peer              *Address // The peer proposing the channel.
	ChallengeDuration int64    // Proposed challenge duration in case of disputes, in seconds.
	InitBals          *BigInts // Initial channel balances.
}

A ChannelProposal describes a proposal to open a new channel.

The proposer has index 0 and proposee index 1.

type ChannelUpdate

type ChannelUpdate struct {
	Last     *State // State before the update.
	State    *State // Proposed new state.
	ActorIdx int    // Who is transferring funds.
}

ChannelUpdate is a channel update proposal. If the ActorIdx is the own channel index, this is a payment request. If State.IsFinal() is true, this is a request to finalize the channel.

type Client

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

Client is a state channel client. It is the central controller to interact with a state channel network. It can be used to propose channels to other channel network peers. ref https://pkg.go.dev/perun.network/go-perun/client?tab=doc#Client

func NewClient

func NewClient(ctx *Context, cfg *Config, w *Wallet) (*Client, error)

NewClient sets up a new Client with configuration `cfg`. The Client:

  • imports the keystore and unlocks the account
  • listens on IP:port
  • connects to the eth node
  • in case either the Adjudicator and AssetHolder of the `cfg` are nil, it deploys needed contract. There is currently no check that the correct bytecode is deployed to the given addresses if they are not nil.
  • sets the `cfg`s Adjudicator and AssetHolder to the deployed contracts addresses in case they were deployed.

func (*Client) AddPeer

func (c *Client) AddPeer(perunID *Address, host string, port int)

AddPeer adds a new peer to the client. Must be called before proposing a new channel with said peer. Wraps go-perun/peer/net/Dialer.Register. ref https://pkg.go.dev/perun.network/go-perun/peer/net?tab=doc#Dialer.Register

func (*Client) EnablePersistence

func (c *Client) EnablePersistence(dbPath string) (err error)

EnablePersistence loads or creates a levelDB database at the given `dbPath` and tries to restore all channels from it. After this function was successfully called, all changes to the Client are saved to the database. This function is not thread safe. ref https://pkg.go.dev/perun.network/go-perun/client?tab=doc#Client.EnablePersistence

func (*Client) Handle

func (c *Client) Handle(ph ProposalHandler, uh UpdateHandler)

Handle is the handler routine for channel proposals and channel updates. It must only be started at most once by the user. Incoming proposals and updates are forwarded to the passed handlers. ref https://pkg.go.dev/perun.network/go-perun/client?tab=doc#Client.Handle

func (*Client) OnChainBalance

func (c *Client) OnChainBalance(ctx *Context, address *Address) (*BigInt, error)

OnChainBalance returns the on-chain balance for `address` in Wei.

func (*Client) OnNewChannel

func (c *Client) OnNewChannel(callback NewChannelCallback)

OnNewChannel sets a handler to be called whenever a new channel is created or restored. Only one such handler can be set at a time, and repeated calls to this function will overwrite the currently existing handler. This function may be safely called at any time. Start the watcher routine here, if needed. ref https://pkg.go.dev/perun.network/go-perun/client?tab=doc#Client.OnNewChannel

func (*Client) ProposeChannel

func (c *Client) ProposeChannel(
	ctx *Context,
	perunID *Address,
	challengeDuration int64,
	initialBals *BigInts,
) (*PaymentChannel, error)

ProposeChannel proposes a new channel to the given peer (perunID) with challengeDuration seconds as the challenge duration in case of disputes and initialBals as the initial channel balances. Returns the newly created channel controller if the channel was successfully created and funded.

After the channel got successfully created, the user is required to start the update handler with PaymentChannel.HandleUpdates(UpdateHandler) and to start the channel watcher with PaymentChannel.Watch() on the returned channel controller.

It is important that the passed context does not cancel before twice the ChallengeDuration has passed (at least for real blockchain backends with wall time), or the channel cannot be settled if a peer times out funding.

The remote peer must have been added to the Client via AddPeer prior to the call to ProposeChannel. Should the connected peer have a different `perunID` than the one given in AddPeer, an error in the form of "Dialed impersonator" will be thrown.

func (*Client) Restore

func (c *Client) Restore(ctx *Context) error

Restore restores all channels from persistence. Channels are restored in parallel. Newly restored channels should be acquired through the OnNewChannel callback. Note that connections are currently established serially, so allow for enough time in the passed context. ref https://pkg.go.dev/perun.network/go-perun/client?tab=doc#Client.Restore

type ConcludedEventHandler

type ConcludedEventHandler interface {
	HandleConcluded(id []byte)
}

ConcludedEventHandler handles channel conclusions.

type ConcludedWatcher

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

ConcludedWatcher implements the AdjudicatorEventHandler and notifies the ConcludedEventHandler if an channel is concluded.

func (*ConcludedWatcher) HandleAdjudicatorEvent

func (w *ConcludedWatcher) HandleAdjudicatorEvent(e channel.AdjudicatorEvent)

HandleAdjudicatorEvent handles channel events emitted by the Adjudicator.

type Config

type Config struct {
	// Name to be used in state channels.
	Alias   string
	Address *Address // OnChain address and PerunID.
	// On-chain addresses of the Adjudicator and AssetHolder Contract.
	// In case any of them is nil, the Client will deploy the contract in its
	// NewClient constructor.
	Adjudicator, AssetHolder *Address
	ETHNodeURL               string // URL of the ETH node. Example: ws://127.0.0.1:8545
	IP                       string // Ip to listen on.
	Port                     uint16 // Port to listen on.
	// TxFinalityDepth how many blocks a Transaction needs to be included
	// in to be considered final.
	TxFinalityDepth uint64
}

Config complete configuration needed to operate the Client.

func NewConfig

func NewConfig(alias string, address, adjudicator, assetHolder *Address, ETHNodeURL, ip string, port int, txFinalityDepth int) *Config

NewConfig creates a new configuration.

type Context

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

Context wraps a golang context/Context with a cancel function when available. See https://golang.org/pkg/context/#Context

func ContextBackground

func ContextBackground() *Context

ContextBackground returns the Background context that is never cancelled. ref https://golang.org/pkg/context/#Background

func ContextWithCancel

func ContextWithCancel() *Context

ContextWithCancel returns a new Context that can be cancelled with Context.Cancel() from the Background Context. ref https://golang.org/pkg/context/#WithCancel

func ContextWithTimeout

func ContextWithTimeout(seconds int) *Context

ContextWithTimeout returns a new Context that is automatically cancelled after `seconds` pass. It can still be cancelled beforehand with Cancel(). ref https://golang.org/pkg/context/#WithTimeout

func (*Context) Cancel

func (c *Context) Cancel()

Cancel cancels the context. Does not work on ContextBackground(). It is safe to call Cancel() more than once, even from different threads.

func (*Context) Context

func (c *Context) Context() (context.Context, context.CancelFunc)

Context can not be called from Java, only here to improve reusability.

func (*Context) WithCancel

func (c *Context) WithCancel() *Context

WithCancel returns a new Context that can cancelled with Context.Cancel() from the given Context. ref https://golang.org/pkg/context/#WithCancel

func (*Context) WithTimeout

func (c *Context) WithTimeout(seconds int) *Context

WithTimeout returns a new Context that is automatically cancelled after `seconds` pass or when its parent context is cancelled. It can still be cancelled beforehand with Cancel(). ref https://golang.org/pkg/context/#WithTimeout

type NewChannelCallback

type NewChannelCallback interface {
	OnNew(*PaymentChannel)
}

NewChannelCallback wraps a `func(*PaymentChannel)` function pointer for the `Client.OnNewChannel` callback.

type Params

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

Params wraps a go-perun/channel.Params ref https://pkg.go.dev/perun.network/go-perun/channel?tab=doc#Params

func (*Params) GetChallengeDuration

func (p *Params) GetChallengeDuration() int64

GetChallengeDuration how many seconds an on-chain dispute of a non-final channel can be refuted.

func (*Params) GetID

func (p *Params) GetID() []byte

GetID returns the channelID of this channel. ref https://pkg.go.dev/perun.network/go-perun/channel?tab=doc#Params.ID

func (*Params) GetParts

func (p *Params) GetParts() *Addresses

GetParts returns the channel participants.

type PaymentChannel

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

PaymentChannel is a convenience wrapper for go-perun/client.Channel which provides all necessary functionality of a two-party payment channel. ref https://pkg.go.dev/perun.network/go-perun/client?tab=doc#Channel

func (*PaymentChannel) Close

func (c *PaymentChannel) Close() error

Close releases all resources that are associated with the channel and ensures that the watcher will return. `Close` should only be called on settled channels to prevent loss of funds. ref https://pkg.go.dev/perun.network/go-perun/client?tab=doc#Channel.Close

func (*PaymentChannel) Finalize

func (c *PaymentChannel) Finalize(ctx *Context) error

Finalize finalizes the channel with the current state.

func (*PaymentChannel) GetIdx

func (c *PaymentChannel) GetIdx() int

GetIdx returns our index in the channel. ref https://pkg.go.dev/perun.network/go-perun/client?tab=doc#Channel.Idx

func (*PaymentChannel) GetParams

func (c *PaymentChannel) GetParams() *Params

GetParams returns the channel parameters. ref https://pkg.go.dev/perun.network/go-perun/client?tab=doc#Channel.Params

func (*PaymentChannel) GetState

func (c *PaymentChannel) GetState() *State

GetState returns the current state. Do not modify it. ref https://pkg.go.dev/perun.network/go-perun/client?tab=doc#Channel.State

func (*PaymentChannel) Send

func (c *PaymentChannel) Send(ctx *Context, amount *BigInt) error

Send pays `amount` to the counterparty. Only positive amounts are supported.

func (*PaymentChannel) Settle

func (c *PaymentChannel) Settle(ctx *Context, secondary bool) error

Settle settles the channel: it is made sure that the current state is registered and the final balance withdrawn. This call blocks until the channel has been successfully withdrawn. Call Finalize before settling a channel to avoid waiting a full challenge duration. If the `secondary` flag is set to true, the Adjudicator runs an optimized protocol, where it is assumed that the other peer also settles the channel. ref https://pkg.go.dev/perun.network/go-perun/client?tab=doc#Channel.Settle

func (*PaymentChannel) Watch

Watch starts the channel watcher routine. It subscribes to RegisteredEvents on the adjudicator. If an event is registered, it is handled by making sure the latest state is registered and then all funds withdrawn to the receiver specified in the adjudicator that was passed to the channel. In case of a channel conclusion event, the given handler `h` is called.

If handling failed, the watcher routine returns the respective error. It is the user's job to restart the watcher after the cause of the error got fixed. ref https://pkg.go.dev/perun.network/go-perun/client?tab=doc#Channel.Watch

type ProposalHandler

type ProposalHandler interface {
	// HandleProposal is the user callback called by the Client on an
	// incoming channel proposal.
	HandleProposal(*ChannelProposal, *ProposalResponder)
}

A ProposalHandler decides how to handle incoming channel proposals from other channel network peers.

type ProposalResponder

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

A ProposalResponder lets the user respond to a channel proposal. If the user wants to accept the proposal, they should call Accept(), otherwise Reject(). Only a single function must be called and every further call causes a panic.

func (*ProposalResponder) Accept

func (r *ProposalResponder) Accept(ctx *Context) (*PaymentChannel, error)

Accept lets the user signal that they want to accept the channel proposal. Returns the newly created channel controller if the channel was successfully created and funded. Panics if the proposal was already accepted or rejected.

After the channel got successfully created, the user is required to start the update handler with PaymentChannel.HandleUpdates(UpdateHandler) and to start the channel watcher with PaymentChannel.Watch() on the returned channel controller.

It is important that the passed context does not cancel before twice the ChallengeDuration has passed (at least for real blockchain backends with wall time), or the channel cannot be settled if a peer times out funding.

func (*ProposalResponder) Reject

func (r *ProposalResponder) Reject(ctx *Context, reason string) error

Reject lets the user signal that they reject the channel proposal. Returns whether the rejection message was successfully sent. Panics if the proposal was already accepted or rejected.

type State

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

State wraps a go-perun/channel.State ref https://pkg.go.dev/perun.network/go-perun/channel?tab=doc#State

func (*State) GetBalances

func (s *State) GetBalances() *BigInts

GetBalances returns a BigInts with length two containing the current balances.

func (*State) GetID

func (s *State) GetID() []byte

GetID returns the immutable id of the channel this state belongs to.

func (*State) GetVersion

func (s *State) GetVersion() int64

GetVersion returns the version counter.

func (*State) IsFinal

func (s *State) IsFinal() bool

IsFinal indicates that the channel is in its final state. Such a state can immediately be settled on the blockchain. A final state cannot be further progressed.

type UpdateHandler

type UpdateHandler interface {
	// HandleUpdate is the user callback called by the channel controller
	// on an incoming update request.
	HandleUpdate(*ChannelUpdate, *UpdateResponder)
}

An UpdateHandler decides how to handle incoming channel update requests from other channel participants.

type UpdateResponder

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

An UpdateResponder lets the user respond to a channel update. If the user wants to accept the update, they should call Accept(), otherwise Reject(). Only a single function must be called and every further call causes a panic.

func (*UpdateResponder) Accept

func (r *UpdateResponder) Accept(ctx *Context) error

Accept lets the user signal that they want to accept the channel update.

func (*UpdateResponder) Reject

func (r *UpdateResponder) Reject(ctx *Context, reason string) error

Reject lets the user signal that they reject the channel update.

type Wallet

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

Wallet represents an ethereum wallet. It uses the go-ethereum keystore to store keys. Accessing the wallet is threadsafe, however you should not create two wallets from the same key directory. ref https://pkg.go.dev/perun.network/go-perun/backend/ethereum/wallet?tab=doc#Wallet

func NewWallet

func NewWallet(path, password string) (*Wallet, error)

NewWallet returns a new wallet with the given path and password.

func (*Wallet) CreateAccount

func (w *Wallet) CreateAccount() *Address

CreateAccount returns the Address of a new randomly created Account. ref https://pkg.go.dev/perun.network/go-perun/backend/ethereum/wallet?tab=doc#Wallet.NewAccount

func (*Wallet) ImportAccount

func (w *Wallet) ImportAccount(secretKey string) (*Address, error)

ImportAccount imports an Ethereum secret key into the Wallet and returns the corresponding Address of it. Secret key example: 0x6aeeb7f09e757baa9d3935a042c3d0d46a2eda19e9b676283dce4eaf32e29dc9 Accounts can safely be imported more than once.

Jump to

Keyboard shortcuts

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