session

package module
v0.2.6 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2023 License: Apache-2.0 Imports: 32 Imported by: 5

README

NKN Tuna Session

NKN Tuna Session is an overlay peer to peer connection based on multiple concurrent tuna connections and ncp protocol.

A few feature highlights:

  • Performance: Use multiple parallel paths to boost overall throughput.

  • Network agnostic: Neither dialer nor listener needs to have public IP address or NAT traversal. They are guaranteed to be connected regardless of their network conditions.

  • Security: Using public key as address, which enables built-in end to end encryption while being invulnerable to man-in-the-middle attack.

A simple illustration of a session between Alice and Bob:

        X
      /   \
Alice - Y - Bob
      \   /
        Z

Listener (Bob for example) will pay relayers in the middle (X, Y, Z) for relaying the traffic using NKN tokens. The payment will be based on bandwidth usage of the session.

Usage

You first need to import both nkn-sdk-go and nkn-tuna-session:

import (
	nkn "github.com/nknorg/nkn-sdk-go"
	ts "github.com/nknorg/nkn-tuna-session"
)

Create a multi-client and wallet (see nkn-sdk-go for details) or re-use your existing ones:

multiclient, err := nkn.NewMultiClient(...)
// wallet is only needed for listener side
wallet, err := nkn.NewWallet(...)

Then you can create a tuna session client:

// wallet is only needed for listener side and will be used for payment
// price is in unit of NKN token per MB
c, err := ts.NewTunaSessionClient(account, multiclient, wallet, &ts.Config{TunaMaxPrice: "0"})

A tuna session client can start listening for incoming session where the remote address match any of the given regexp:

// Accepting any address, equivalent to c.Listen(nkn.NewStringArray(".*"))
err = c.Listen(nil)
// Only accepting pubkey 25d660916021ab1d182fb6b52d666b47a0f181ed68cf52a056041bdcf4faaf99 but with any identifiers
err = c.Listen(nkn.NewStringArray("25d660916021ab1d182fb6b52d666b47a0f181ed68cf52a056041bdcf4faaf99$"))
// Only accepting address alice.25d660916021ab1d182fb6b52d666b47a0f181ed68cf52a056041bdcf4faaf99
err = c.Listen(nkn.NewStringArray("^alice\\.25d660916021ab1d182fb6b52d666b47a0f181ed68cf52a056041bdcf4faaf99$"))

Wait for tuna to connect:

<-c.OnConnect()

Then it can start accepting sessions:

session, err := c.Accept()

Tuna session client implements net.Listener interface, so one can use it as a drop-in replacement when net.Listener is needed, e.g. http.Serve.

On the other hand, any tuna session client can dial a session to a remote NKN address:

session, err := c.Dial("another nkn address")

Session implements net.Conn interface, so it can be used as a drop-in replacement when net.Conn is needed:

buf := make([]byte, 1024)
n, err := session.Read(buf)
n, err := session.Write(buf)

A few more complicated examples can be found at examples

Usage on iOS/Android

This library is designed to work with gomobile and run natively on iOS/Android without any modification. You can use gomobile bind to compile it to Objective-C framework for iOS:

gomobile bind -target=ios -ldflags "-s -w" github.com/nknorg/nkn-tuna-session github.com/nknorg/nkn-sdk-go github.com/nknorg/ncp-go github.com/nknorg/tuna github.com/nknorg/nkngomobile

and Java AAR for Android:

gomobile bind -target=android -ldflags "-s -w" github.com/nknorg/nkn-tuna-session github.com/nknorg/nkn-sdk-go github.com/nknorg/ncp-go github.com/nknorg/tuna github.com/nknorg/nkngomobile

Contributing

Can I submit a bug, suggestion or feature request?

Yes. Please open an issue for that.

Can I contribute patches?

Yes, we appreciate your help! To make contributions, please fork the repo, push your changes to the forked repo with signed-off commits, and open a pull request here.

Please sign off your commit. This means adding a line "Signed-off-by: Name " at the end of each commit, indicating that you wrote the code and have the right to pass it on as an open source patch. This can be done automatically by adding -s when committing:

git commit -s

Community

Documentation

Index

Constants

View Source
const (
	DefaultSessionAllowAddr = nkn.DefaultSessionAllowAddr
	SessionIDSize           = nkn.SessionIDSize
)
View Source
const (
	ActionGetPubAddr = "getPubAddr"
)

Variables

View Source
var (
	ErrClosed             = errors.New("tuna session is closed")
	ErrNoPubAddr          = errors.New("no public address avalaible")
	ErrRemoteAddrRejected = errors.New("remote address is rejected")
	ErrWrongMsgFormat     = errors.New("wrong message format")
	ErrWrongAddr          = errors.New("wrong address")
	ErrOnlyDailer         = errors.New("this function only for dialer")
	ErrNilConn            = errors.New("conn is nil")
)

Functions

func DefaultSessionConfig

func DefaultSessionConfig() *ncp.Config

func GetFreePort added in v0.2.6

func GetFreePort(port int) (int, error)

Types

type Config

type Config struct {
	NumTunaListeners             int
	TunaDialTimeout              int // in millisecond
	TunaMaxPrice                 string
	TunaNanoPayFee               string
	TunaMinNanoPayFee            string
	TunaNanoPayFeeRatio          float64
	TunaServiceName              string
	TunaSubscriptionPrefix       string
	TunaIPFilter                 *geo.IPFilter
	TunaNknFilter                *filter.NknFilter
	TunaDownloadGeoDB            bool
	TunaGeoDBPath                string
	TunaMeasureBandwidth         bool
	TunaMeasureStoragePath       string
	TunaMeasurementBytesDownLink int32
	TunaMinBalance               string
	SessionConfig                *ncp.Config
	ReconnectRetries             int // negative value: unlimited retries, 0: no reconnect, positive value: limit retries.
	ReconnectInterval            int // millisecond
	UDPRecvBufferSize            int // UDP user data receive buffer size, bytes
	MaxUdpDatagramBuffered       int // Maximum udp datagrams can be buffered. It works with UDPRecvBufferSize together go decide if a datagram is buffered.
	Verbose                      bool
}

func DefaultConfig

func DefaultConfig() *Config

func MergedConfig

func MergedConfig(conf *Config) (*Config, error)

type Conn added in v0.1.4

type Conn struct {
	net.Conn
	ReadLock  sync.Mutex
	WriteLock sync.Mutex
}

type PubAddr

type PubAddr struct {
	IP       string `json:"ip"`
	Port     uint32 `json:"port"`
	InPrice  string `json:"inPrice,omitempty"`
	OutPrice string `json:"outPrice,omitempty"`
}

func (*PubAddr) String added in v0.2.6

func (pa *PubAddr) String() string

type PubAddrs

type PubAddrs struct {
	Addrs         []*PubAddr `json:"addrs"`
	SessionClosed bool       `json:"sessionClosed"`
}

type Request

type Request struct {
	Action    string `json:"action"`
	SessionID []byte `json:"sessionID"`
}

type TunaSessionClient

type TunaSessionClient struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewTunaSessionClient

func NewTunaSessionClient(clientAccount *nkn.Account, m *nkn.MultiClient, wallet *nkn.Wallet, config *Config) (*TunaSessionClient, error)

func (*TunaSessionClient) Accept

func (c *TunaSessionClient) Accept() (net.Conn, error)

func (*TunaSessionClient) AcceptSession

func (c *TunaSessionClient) AcceptSession() (*ncp.Session, error)

func (*TunaSessionClient) Addr

func (c *TunaSessionClient) Addr() net.Addr

func (*TunaSessionClient) Address

func (c *TunaSessionClient) Address() string

func (*TunaSessionClient) Close

func (c *TunaSessionClient) Close() error

func (*TunaSessionClient) CloseOneConn added in v0.2.6

func (c *TunaSessionClient) CloseOneConn(sess *ncp.Session, connId string)

func (*TunaSessionClient) Dial

func (c *TunaSessionClient) Dial(remoteAddr string) (net.Conn, error)

func (*TunaSessionClient) DialSession

func (c *TunaSessionClient) DialSession(remoteAddr string) (*ncp.Session, error)

func (*TunaSessionClient) DialUDP added in v0.2.6

func (c *TunaSessionClient) DialUDP(remoteAddr string) (*UdpSession, error)

func (*TunaSessionClient) DialUDPWithConfig added in v0.2.6

func (c *TunaSessionClient) DialUDPWithConfig(remoteAddr string, config *nkn.DialConfig) (*UdpSession, error)

func (*TunaSessionClient) DialWithConfig

func (c *TunaSessionClient) DialWithConfig(remoteAddr string, config *nkn.DialConfig) (*ncp.Session, error)

func (*TunaSessionClient) GetPubAddrs added in v0.1.9

func (c *TunaSessionClient) GetPubAddrs() *PubAddrs

func (*TunaSessionClient) IsClosed

func (c *TunaSessionClient) IsClosed() bool

func (*TunaSessionClient) IsSessClosed added in v0.2.6

func (c *TunaSessionClient) IsSessClosed(sessKey string) bool

func (*TunaSessionClient) Listen

func (c *TunaSessionClient) Listen(addrsRe *nkngomobile.StringArray) error

func (*TunaSessionClient) ListenUDP added in v0.2.6

func (c *TunaSessionClient) ListenUDP() (*UdpSession, error)

Start UDP server listening. Because UDP is connectionless, we use TCP to track the connection status. So we need to start a TCP server first, and then start a UDP server. Meanwhile, Tuna session server hase two modes: TCP only, or TCP + UDP.

func (*TunaSessionClient) OnConnect added in v0.2.6

func (c *TunaSessionClient) OnConnect() chan struct{}

OnConnect returns a channel that will be closed when at least one tuna exit is connected after Listen() is first called.

func (*TunaSessionClient) RotateAll added in v0.2.1

func (c *TunaSessionClient) RotateAll() error

RotateAll create and replace all tuna exit. New connections accepted will use new tuna exit, existing connections will not be affected.

func (*TunaSessionClient) RotateOne added in v0.2.1

func (c *TunaSessionClient) RotateOne(i int) error

RotateOne create a new tuna exit and replace the i-th one. New connections accepted will use new tuna exit, existing connections will not be affected.

func (*TunaSessionClient) SetConfig added in v0.2.1

func (c *TunaSessionClient) SetConfig(conf *Config) error

SetConfig will set any non-empty value in conf to tuna session config.

func (*TunaSessionClient) SetTunaNode added in v0.2.6

func (c *TunaSessionClient) SetTunaNode(node *types.Node)

type UdpSession added in v0.2.6

type UdpSession struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

UDP session, it is a UDP listener or dialer endpoint for reading and writing udp data. After tuna session set up UDP connection, it return UpdSession to applications. Applications use this end point to read and write data. If there is a node break down between UDP listener and dialer, udp session will reconenct automatically without interrupting application usage.

func (*UdpSession) Close added in v0.2.6

func (us *UdpSession) Close() (err error)

The endpoint close session actively.

func (*UdpSession) CloseTcp added in v0.2.6

func (us *UdpSession) CloseTcp(i int)

for test only.

func (*UdpSession) DialUpSession added in v0.2.6

func (us *UdpSession) DialUpSession(listenerNknAddr string, sessionID []byte, config *nkn.DialConfig) (err error)

func (*UdpSession) GetEstablishedUDPConn added in v0.2.6

func (us *UdpSession) GetEstablishedUDPConn() (*tuna.EncryptUDPConn, error)

func (*UdpSession) GetUDPConn added in v0.2.6

func (us *UdpSession) GetUDPConn() *tuna.EncryptUDPConn

func (*UdpSession) IsClosed added in v0.2.6

func (us *UdpSession) IsClosed() bool

func (*UdpSession) LocalAddr added in v0.2.6

func (us *UdpSession) LocalAddr() net.Addr

func (*UdpSession) Read added in v0.2.6

func (us *UdpSession) Read(b []byte) (int, error)

func (*UdpSession) ReadFrom added in v0.2.6

func (us *UdpSession) ReadFrom(b []byte) (n int, addr net.Addr, err error)

ReadFrom, implement of standard library function: net.UDPConn.ReadFrom

func (*UdpSession) RemoteAddr added in v0.2.6

func (us *UdpSession) RemoteAddr() net.Addr

func (*UdpSession) SetDeadline added in v0.2.6

func (us *UdpSession) SetDeadline(t time.Time) error

func (*UdpSession) SetReadBuffer added in v0.2.6

func (us *UdpSession) SetReadBuffer(size int) error

func (*UdpSession) SetReadDeadline added in v0.2.6

func (us *UdpSession) SetReadDeadline(t time.Time) error

func (*UdpSession) SetWriteBuffer added in v0.2.6

func (us *UdpSession) SetWriteBuffer(size int) error

func (*UdpSession) SetWriteDeadline added in v0.2.6

func (us *UdpSession) SetWriteDeadline(t time.Time) error

func (*UdpSession) Write added in v0.2.6

func (us *UdpSession) Write(b []byte) (int, error)

func (*UdpSession) WriteTo added in v0.2.6

func (us *UdpSession) WriteTo(b []byte, addr net.Addr) (n int, err error)

ReadFrom, implement of standard library net.UDPConn.WriteTo Only for user data write

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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