swap

package
v0.5.9-0...-ba7202b Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2022 License: GPL-3.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Thresholds which trigger payment or disconnection. The unit is in honey (internal accounting unit)
	// DefaultPaymentThreshold is set to be equivalent to requesting and serving 10mb of data (2441 chunks (4096 bytes) = 10 mb, 10^7 bytes = 10 mb)
	DefaultPaymentThreshold    = 2441*RetrieveRequestPrice + (10^7)*ChunkDeliveryPrice // 4096 * 2441 = 10 mb,
	DefaultDisconnectThreshold = 20 * DefaultPaymentThreshold
	// ChequeDebtTolerance is the lowest resulting balance a node is willing to accept when receiving a cheque
	// the value is meant to be used below 0, as positive resulting balances should always be accepted when receiving cheques
	ChequeDebtTolerance = DefaultPaymentThreshold * 20 / 100 // roughly 20% of the payment threshold
	// DefaultDepositAmount is the default amount to send to the contract when initially deploying
	// NOTE: deliberate value for now; needs experimentation
	DefaultDepositAmount = 0

	// Until we deploy swap officially, it's only allowed to be enabled under a specific network ID (use the --bzznetworkid flag to set it)
	AllowedNetworkID          = 5
	DefaultTransactionTimeout = 10 * time.Minute
)

These are currently arbitrary values which have not been verified nor tested Need experimentation to arrive to values which make sense

View Source
const (
	// InitAction used when starting swap
	InitAction string = "init"
	// StopAction used when stopping swap
	StopAction string = "stop"
	// UpdateBalanceAction used when updating swap balances
	UpdateBalanceAction string = "update_balance"
	// SendChequeAction used for grouping actions when sending a cheque with swap
	SendChequeAction string = "send_cheque"
	// HandleChequeAction used for grouping actions related to swap cheque events, received/processed/etc cheques
	HandleChequeAction string = "handle_cheque"
	// CashChequeAction used for grouping actions of swap cashed cheques
	CashChequeAction string = "cash_cheque"
	// DeployChequebookAction used when deploying chequebooks
	DeployChequebookAction string = "deploy_chequebook_contract"
)
View Source
const (
	RetrieveRequestPrice = uint64(8043036262)
	ChunkDeliveryPrice   = uint64(17672687)
)

TODO: this calculations make little sense now, after update to ERC20-enabled chequebook Placeholder prices Based on a very crude calculation: average monthly cost for bandwidth in the US / average monthly usage of bandwidth in the US $67 / 190GB = $0.35 / GB 0.35 / (1.073.741.824) = $3.259629e^-10 / byte 3.259629e^-10/ (166 * 10^18) = 19636319 Wei / byte, where 166 is the current Ether price in Dollar per byte of data transferred, we account for 1 chunkDelivery price (accounted per byte), and 1/4096 retrieveRequest (accounted per message) RetrieveRequestPrice = 0.1 * 19636319 * 4096 = 8043036262, where 0.1 is a bogus factor ChunkDeliveryPrice = 0.9 * 19636319 = 17672687, where 0.9 is a bogus factor

View Source
const CashChequeBeneficiaryTransactionCost = 50000

CashChequeBeneficiaryTransactionCost is the expected gas cost of a CashChequeBeneficiary transaction

View Source
const DefaultSwapLogLevel = 3

DefaultSwapLogLevel indicates default filter level of log messages

Variables

View Source
var (
	// ErrEmptyAddressInSignature is used when the empty address is used for the chequebook in the handshake
	ErrEmptyAddressInSignature = errors.New("empty address in handshake")

	// ErrDifferentChainID is used when the chain id exchanged during the handshake does not match
	ErrDifferentChainID = errors.New("different chain id")

	// ErrInvalidHandshakeMsg is used when the message received during handshake does not conform to the
	// structure of the HandshakeMsg
	ErrInvalidHandshakeMsg = errors.New("invalid handshake message")

	// Spec is the swap protocol specification
	Spec = &protocols.Spec{
		Name:       "swap",
		Version:    1,
		MaxMsgSize: 10 * 1024 * 1024,
		Messages: []interface{}{
			HandshakeMsg{},
			EmitChequeMsg{},
			ConfirmChequeMsg{},
		},
	}
)
View Source
var ErrDontOwe = errors.New("no negative balance")

ErrDontOwe indictates that no balance is actially owned

View Source
var ErrInvalidChequeSignature = errors.New("invalid cheque signature")

ErrInvalidChequeSignature indicates the signature on the cheque was invalid

View Source
var ErrSkipDeposit = errors.New("swap-deposit-amount non-zero, but swap-skip-deposit true")

ErrSkipDeposit indicates that the user has specified an amount to deposit (swap-deposit-amount) but also indicated that depositing should be skipped (swap-skip-deposit)

Functions

This section is empty.

Types

type API

type API struct {
	*contract.Params
	// contains filtered or unexported fields
}

API would be the API accessor for protocol methods

func NewAPI

func NewAPI(s *Swap) *API

NewAPI creates a new API instance

type ActiveCashout

type ActiveCashout struct {
	Request         CashoutRequest // the request that caused this cashout
	TransactionHash common.Hash    // the hash of the current transaction for this request
	Logger          Logger
}

ActiveCashout stores the necessary information for a cashout in progess

type CashoutProcessor

type CashoutProcessor struct {
	Logger Logger
	// contains filtered or unexported fields
}

CashoutProcessor holds all relevant fields needed for processing cashouts

type CashoutRequest

type CashoutRequest struct {
	Cheque      Cheque         // cheque to be cashed
	Destination common.Address // destination for the payout
	Logger      Logger
}

CashoutRequest represents a request for a cashout operation

type Cheque

type Cheque struct {
	ChequeParams
	Honey     uint64 // amount of honey which resulted in the cumulative currency difference
	Signature []byte // signature Sign(Keccak256(contract, beneficiary, amount), prvKey)
}

Cheque encapsulates the parameters and the signature

func (*Cheque) Equal

func (cheque *Cheque) Equal(other *Cheque) bool

Equal checks if other has the same fields

func (*Cheque) String

func (cheque *Cheque) String() string

func (*Cheque) VerifySig

func (cheque *Cheque) VerifySig(expectedSigner common.Address) error

VerifySig verifies the signature on the cheque

type ChequeParams

type ChequeParams struct {
	Contract         common.Address  // address of chequebook, needed to avoid cross-contract submission
	Beneficiary      common.Address  // address of the beneficiary, the contract which will redeem the cheque
	CumulativePayout *int256.Uint256 // cumulative amount of the cheque in currency
}

ChequeParams encapsulate all cheque parameters

func (*ChequeParams) Sign

func (cheque *ChequeParams) Sign(prv *ecdsa.PrivateKey) ([]byte, error)

Sign returns the cheque's signature with supplied private key

type ConfirmChequeMsg

type ConfirmChequeMsg struct {
	Cheque *Cheque
}

ConfirmChequeMsg is sent from the creditor to the debitor with the cheque to confirm successful processing

type EmitChequeMsg

type EmitChequeMsg struct {
	Cheque *Cheque
}

EmitChequeMsg is sent from the debitor to the creditor with the actual cheque

type HandshakeMsg

type HandshakeMsg struct {
	ChainID         uint64         // chain id of the blockchain the peer is connected to
	ContractAddress common.Address // chequebook contract address of the peer
}

HandshakeMsg is exchanged on peer handshake

type HoneyOracle

type HoneyOracle interface {
	GetPrice(honey uint64) (uint64, error)
}

HoneyOracle is the interface through which Oracles will deliver prices

func NewHoneyPriceOracle

func NewHoneyPriceOracle() HoneyOracle

NewHoneyPriceOracle returns the actual oracle to be used for discovering the price It will return a default one

type Logger

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

Logger wraps the ethereum logger with specific information for swap logging each log contains a context which will be printed on each message

func (Logger) Crit

func (sl Logger) Crit(action string, msg string, ctx ...interface{})

Crit is a convenient alias for log.Crit with a defined action context

func (Logger) Debug

func (sl Logger) Debug(action string, msg string, ctx ...interface{})

Debug is a convenient alias for log.Debug with a defined action context

func (Logger) Error

func (sl Logger) Error(action string, msg string, ctx ...interface{})

Error is a convenient alias for log.Error with a defined action context

func (Logger) Info

func (sl Logger) Info(action string, msg string, ctx ...interface{})

Info is a convenient alias for log.Info with a defined action context

func (Logger) Trace

func (sl Logger) Trace(action string, msg string, ctx ...interface{})

Trace is a convenient alias for log.Trace with a defined action context

func (Logger) Warn

func (sl Logger) Warn(action string, msg string, ctx ...interface{})

Warn is a convenient alias for log.Warn with a defined action context

type Owner

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

Owner encapsulates information related to accessing the contract

type Params

type Params struct {
	BaseAddrs           *network.BzzAddr // this node's base address
	LogPath             string           // optional audit log path
	LogLevel            int              // optional indicates audit filter level of swap log messages
	PaymentThreshold    int64            // honey amount at which a payment is triggered
	DisconnectThreshold int64            // honey amount at which a peer disconnects
}

Params encapsulates economic and operational parameters

type Peer

type Peer struct {
	*protocols.Peer
	// contains filtered or unexported fields
}

Peer is a devp2p peer for the Swap protocol

func NewPeer

func NewPeer(p *protocols.Peer, s *Swap, beneficiary common.Address, contractAddress common.Address) (peer *Peer, err error)

NewPeer creates a new swap Peer instance

type PeerCheques

type PeerCheques struct {
	PendingCheque      *Cheque
	LastSentCheque     *Cheque
	LastReceivedCheque *Cheque
}

PeerCheques contains the last cheque known to have been sent to a peer, as well as the last one received from the peer

type Swap

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

Swap represents the Swarm Accounting Protocol a peer to peer micropayment system A node maintains an individual balance with every peer Only messages which have a price will be accounted for

func New

func New(dbPath string, prvkey *ecdsa.PrivateKey, backendURL string, params *Params, chequebookAddressFlag common.Address, skipDepositFlag bool, depositAmountFlag uint64, factoryAddress common.Address) (swap *Swap, err error)

New prepares and creates all fields to create a swap instance: - sets up a SWAP database; - verifies whether the disconnect threshold is higher than the payment threshold; - connects to the blockchain backend; - verifies that we have not connected SWAP before on a different blockchain backend; - starts the chequebook; creates the swap instance

func (*Swap) APIs

func (s *Swap) APIs() []rpc.API

APIs is a node.Service interface method

func (*Swap) Add

func (s *Swap) Add(amount int64, peer *protocols.Peer) (err error)

Add is the (sole) accounting function Swap implements the protocols.Balance interface

func (*Swap) AvailableBalance

func (s *Swap) AvailableBalance() (*int256.Uint256, error)

AvailableBalance returns the total balance of the chequebook against which new cheques can be written

func (*Swap) Balances

func (s *Swap) Balances() (map[enode.ID]int64, error)

Balances returns the balances for all known SWAP peers

func (*Swap) Check

func (s *Swap) Check(amount int64, peer *protocols.Peer) (err error)

Check is called as a *dry run* before applying the actual accounting to an operation. It only checks that performing a given accounting operation would not incur in an error. If it returns no error, this signals to the caller that the operation is safe

func (*Swap) Cheques

func (s *Swap) Cheques() (map[enode.ID]*PeerCheques, error)

Cheques returns all known last sent and received cheques, grouped by peer

func (*Swap) Close

func (s *Swap) Close() error

Close cleans up swap

func (*Swap) Deploy

func (s *Swap) Deploy(ctx context.Context) (contract.Contract, error)

Deploy deploys the Swap contract

func (*Swap) Deposit

func (s *Swap) Deposit(ctx context.Context, amount *big.Int) error

Deposit deposits ERC20 into the chequebook contract

func (*Swap) GetParams

func (s *Swap) GetParams() *contract.Params

GetParams returns contract parameters (Bin, ABI, contractAddress) from the contract

func (*Swap) PeerBalance

func (s *Swap) PeerBalance(peer enode.ID) (balance int64, err error)

PeerBalance returns the balance for a given peer

func (*Swap) PeerCheques

func (s *Swap) PeerCheques(peer enode.ID) (PeerCheques, error)

PeerCheques returns the last sent and received cheques for a given peer

func (*Swap) Protocols

func (s *Swap) Protocols() []p2p.Protocol

Protocols is a node.Service interface method

func (*Swap) Start

func (s *Swap) Start(server *p2p.Server) error

Start is a node.Service interface method

func (*Swap) StartChequebook

func (s *Swap) StartChequebook(chequebookAddrFlag common.Address) (contract contract.Contract, err error)

StartChequebook starts the chequebook, taking into account the chequebookAddress passed in by the user and the chequebook addresses saved on the node's database

func (*Swap) Stop

func (s *Swap) Stop() error

Stop is a node.Service interface method

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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