aboutsummaryrefslogtreecommitdiffstats
path: root/swarm/services
diff options
context:
space:
mode:
authorethersphere <thesw@rm.eth>2018-06-20 20:06:27 +0800
committerethersphere <thesw@rm.eth>2018-06-22 03:10:31 +0800
commite187711c6545487d4cac3701f0f506bb536234e2 (patch)
treed2f6150f70b84b36e49a449082aeda267b4b9046 /swarm/services
parent574378edb50c907b532946a1d4654dbd6701b20a (diff)
downloaddexon-e187711c6545487d4cac3701f0f506bb536234e2.tar
dexon-e187711c6545487d4cac3701f0f506bb536234e2.tar.gz
dexon-e187711c6545487d4cac3701f0f506bb536234e2.tar.bz2
dexon-e187711c6545487d4cac3701f0f506bb536234e2.tar.lz
dexon-e187711c6545487d4cac3701f0f506bb536234e2.tar.xz
dexon-e187711c6545487d4cac3701f0f506bb536234e2.tar.zst
dexon-e187711c6545487d4cac3701f0f506bb536234e2.zip
swarm: network rewrite merge
Diffstat (limited to 'swarm/services')
-rw-r--r--swarm/services/swap/swap.go143
-rw-r--r--swarm/services/swap/swap/swap.go180
-rw-r--r--swarm/services/swap/swap/swap_test.go42
3 files changed, 185 insertions, 180 deletions
diff --git a/swarm/services/swap/swap.go b/swarm/services/swap/swap.go
index 1eac111be..91fa54fcf 100644
--- a/swarm/services/swap/swap.go
+++ b/swarm/services/swap/swap.go
@@ -33,7 +33,7 @@ import (
"github.com/ethereum/go-ethereum/contracts/chequebook/contract"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
- "github.com/ethereum/go-ethereum/log"
+ "github.com/ethereum/go-ethereum/swarm/log"
"github.com/ethereum/go-ethereum/swarm/services/swap/swap"
)
@@ -60,16 +60,19 @@ const (
chequebookDeployDelay = 1 * time.Second // delay between retries
)
-type SwapParams struct {
+// LocalProfile combines a PayProfile with *swap.Params
+type LocalProfile struct {
*swap.Params
*PayProfile
}
-type SwapProfile struct {
+// RemoteProfile combines a PayProfile with *swap.Profile
+type RemoteProfile struct {
*swap.Profile
*PayProfile
}
+// PayProfile is a container for relevant chequebook and beneficiary options
type PayProfile struct {
PublicKey string // check against signature of promise
Contract common.Address // address of chequebook contract
@@ -81,9 +84,9 @@ type PayProfile struct {
lock sync.RWMutex
}
-//create params with default values
-func NewDefaultSwapParams() *SwapParams {
- return &SwapParams{
+// NewDefaultSwapParams create params with default values
+func NewDefaultSwapParams() *LocalProfile {
+ return &LocalProfile{
PayProfile: &PayProfile{},
Params: &swap.Params{
Profile: &swap.Profile{
@@ -103,12 +106,12 @@ func NewDefaultSwapParams() *SwapParams {
}
}
-//this can only finally be set after all config options (file, cmd line, env vars)
-//have been evaluated
-func (self *SwapParams) Init(contract common.Address, prvkey *ecdsa.PrivateKey) {
+// Init this can only finally be set after all config options (file, cmd line, env vars)
+// have been evaluated
+func (lp *LocalProfile) Init(contract common.Address, prvkey *ecdsa.PrivateKey) {
pubkey := &prvkey.PublicKey
- self.PayProfile = &PayProfile{
+ lp.PayProfile = &PayProfile{
PublicKey: common.ToHex(crypto.FromECDSAPub(pubkey)),
Contract: contract,
Beneficiary: crypto.PubkeyToAddress(*pubkey),
@@ -118,7 +121,7 @@ func (self *SwapParams) Init(contract common.Address, prvkey *ecdsa.PrivateKey)
}
}
-// swap constructor, parameters
+// NewSwap constructor, parameters
// * global chequebook, assume deployed service and
// * the balance is at buffer.
// swap.Add(n) called in netstore
@@ -126,8 +129,7 @@ func (self *SwapParams) Init(contract common.Address, prvkey *ecdsa.PrivateKey)
// OR sending cheques.
// n < 0 called when receiving chunks = receiving delivery responses
// OR receiving cheques.
-
-func NewSwap(local *SwapParams, remote *SwapProfile, backend chequebook.Backend, proto swap.Protocol) (self *swap.Swap, err error) {
+func NewSwap(localProfile *LocalProfile, remoteProfile *RemoteProfile, backend chequebook.Backend, proto swap.Protocol) (swapInstance *swap.Swap, err error) {
var (
ctx = context.TODO()
ok bool
@@ -135,31 +137,31 @@ func NewSwap(local *SwapParams, remote *SwapProfile, backend chequebook.Backend,
out *chequebook.Outbox
)
- remotekey, err := crypto.UnmarshalPubkey(common.FromHex(remote.PublicKey))
+ remotekey, err := crypto.UnmarshalPubkey(common.FromHex(remoteProfile.PublicKey))
if err != nil {
return nil, errors.New("invalid remote public key")
}
- // check if remote chequebook is valid
+ // check if remoteProfile chequebook is valid
// insolvent chequebooks suicide so will signal as invalid
// TODO: monitoring a chequebooks events
- ok, err = chequebook.ValidateCode(ctx, backend, remote.Contract)
+ ok, err = chequebook.ValidateCode(ctx, backend, remoteProfile.Contract)
if !ok {
- log.Info(fmt.Sprintf("invalid contract %v for peer %v: %v)", remote.Contract.Hex()[:8], proto, err))
+ log.Info(fmt.Sprintf("invalid contract %v for peer %v: %v)", remoteProfile.Contract.Hex()[:8], proto, err))
} else {
- // remote contract valid, create inbox
- in, err = chequebook.NewInbox(local.privateKey, remote.Contract, local.Beneficiary, remotekey, backend)
+ // remoteProfile contract valid, create inbox
+ in, err = chequebook.NewInbox(localProfile.privateKey, remoteProfile.Contract, localProfile.Beneficiary, remotekey, backend)
if err != nil {
- log.Warn(fmt.Sprintf("unable to set up inbox for chequebook contract %v for peer %v: %v)", remote.Contract.Hex()[:8], proto, err))
+ log.Warn(fmt.Sprintf("unable to set up inbox for chequebook contract %v for peer %v: %v)", remoteProfile.Contract.Hex()[:8], proto, err))
}
}
- // check if local chequebook contract is valid
- ok, err = chequebook.ValidateCode(ctx, backend, local.Contract)
+ // check if localProfile chequebook contract is valid
+ ok, err = chequebook.ValidateCode(ctx, backend, localProfile.Contract)
if !ok {
- log.Warn(fmt.Sprintf("unable to set up outbox for peer %v: chequebook contract (owner: %v): %v)", proto, local.owner.Hex(), err))
+ log.Warn(fmt.Sprintf("unable to set up outbox for peer %v: chequebook contract (owner: %v): %v)", proto, localProfile.owner.Hex(), err))
} else {
- out = chequebook.NewOutbox(local.Chequebook(), remote.Beneficiary)
+ out = chequebook.NewOutbox(localProfile.Chequebook(), remoteProfile.Beneficiary)
}
pm := swap.Payment{
@@ -168,20 +170,20 @@ func NewSwap(local *SwapParams, remote *SwapProfile, backend chequebook.Backend,
Buys: out != nil,
Sells: in != nil,
}
- self, err = swap.New(local.Params, pm, proto)
+ swapInstance, err = swap.New(localProfile.Params, pm, proto)
if err != nil {
return
}
- // remote profile given (first) in handshake
- self.SetRemote(remote.Profile)
+ // remoteProfile profile given (first) in handshake
+ swapInstance.SetRemote(remoteProfile.Profile)
var buy, sell string
- if self.Buys {
- buy = "purchase from peer enabled at " + remote.SellAt.String() + " wei/chunk"
+ if swapInstance.Buys {
+ buy = "purchase from peer enabled at " + remoteProfile.SellAt.String() + " wei/chunk"
} else {
buy = "purchase from peer disabled"
}
- if self.Sells {
- sell = "selling to peer enabled at " + local.SellAt.String() + " wei/chunk"
+ if swapInstance.Sells {
+ sell = "selling to peer enabled at " + localProfile.SellAt.String() + " wei/chunk"
} else {
sell = "selling to peer disabled"
}
@@ -190,66 +192,69 @@ func NewSwap(local *SwapParams, remote *SwapProfile, backend chequebook.Backend,
return
}
-func (self *SwapParams) Chequebook() *chequebook.Chequebook {
- defer self.lock.Unlock()
- self.lock.Lock()
- return self.chbook
+// Chequebook get's chequebook from the localProfile
+func (lp *LocalProfile) Chequebook() *chequebook.Chequebook {
+ defer lp.lock.Unlock()
+ lp.lock.Lock()
+ return lp.chbook
}
-func (self *SwapParams) PrivateKey() *ecdsa.PrivateKey {
- return self.privateKey
+// PrivateKey accessor
+func (lp *LocalProfile) PrivateKey() *ecdsa.PrivateKey {
+ return lp.privateKey
}
-// func (self *SwapParams) PublicKey() *ecdsa.PublicKey {
+// func (self *LocalProfile) PublicKey() *ecdsa.PublicKey {
// return self.publicKey
// }
-func (self *SwapParams) SetKey(prvkey *ecdsa.PrivateKey) {
- self.privateKey = prvkey
- self.publicKey = &prvkey.PublicKey
+// SetKey set's private and public key on localProfile
+func (lp *LocalProfile) SetKey(prvkey *ecdsa.PrivateKey) {
+ lp.privateKey = prvkey
+ lp.publicKey = &prvkey.PublicKey
}
-// setChequebook(path, backend) wraps the
-// chequebook initialiser and sets up autoDeposit to cover spending.
-func (self *SwapParams) SetChequebook(ctx context.Context, backend chequebook.Backend, path string) error {
- self.lock.Lock()
- contract := self.Contract
- self.lock.Unlock()
+// SetChequebook wraps the chequebook initialiser and sets up autoDeposit to cover spending.
+func (lp *LocalProfile) SetChequebook(ctx context.Context, backend chequebook.Backend, path string) error {
+ lp.lock.Lock()
+ swapContract := lp.Contract
+ lp.lock.Unlock()
- valid, err := chequebook.ValidateCode(ctx, backend, contract)
+ valid, err := chequebook.ValidateCode(ctx, backend, swapContract)
if err != nil {
return err
} else if valid {
- return self.newChequebookFromContract(path, backend)
+ return lp.newChequebookFromContract(path, backend)
}
- return self.deployChequebook(ctx, backend, path)
+ return lp.deployChequebook(ctx, backend, path)
}
-func (self *SwapParams) deployChequebook(ctx context.Context, backend chequebook.Backend, path string) error {
- opts := bind.NewKeyedTransactor(self.privateKey)
- opts.Value = self.AutoDepositBuffer
+// deployChequebook deploys the localProfile Chequebook
+func (lp *LocalProfile) deployChequebook(ctx context.Context, backend chequebook.Backend, path string) error {
+ opts := bind.NewKeyedTransactor(lp.privateKey)
+ opts.Value = lp.AutoDepositBuffer
opts.Context = ctx
log.Info(fmt.Sprintf("Deploying new chequebook (owner: %v)", opts.From.Hex()))
- contract, err := deployChequebookLoop(opts, backend)
+ address, err := deployChequebookLoop(opts, backend)
if err != nil {
log.Error(fmt.Sprintf("unable to deploy new chequebook: %v", err))
return err
}
- log.Info(fmt.Sprintf("new chequebook deployed at %v (owner: %v)", contract.Hex(), opts.From.Hex()))
+ log.Info(fmt.Sprintf("new chequebook deployed at %v (owner: %v)", address.Hex(), opts.From.Hex()))
// need to save config at this point
- self.lock.Lock()
- self.Contract = contract
- err = self.newChequebookFromContract(path, backend)
- self.lock.Unlock()
+ lp.lock.Lock()
+ lp.Contract = address
+ err = lp.newChequebookFromContract(path, backend)
+ lp.lock.Unlock()
if err != nil {
log.Warn(fmt.Sprintf("error initialising cheque book (owner: %v): %v", opts.From.Hex(), err))
}
return err
}
-// repeatedly tries to deploy a chequebook.
+// deployChequebookLoop repeatedly tries to deploy a chequebook.
func deployChequebookLoop(opts *bind.TransactOpts, backend chequebook.Backend) (addr common.Address, err error) {
var tx *types.Transaction
for try := 0; try < chequebookDeployRetries; try++ {
@@ -269,28 +274,28 @@ func deployChequebookLoop(opts *bind.TransactOpts, backend chequebook.Backend) (
return addr, err
}
-// initialise the chequebook from a persisted json file or create a new one
+// newChequebookFromContract - initialise the chequebook from a persisted json file or create a new one
// caller holds the lock
-func (self *SwapParams) newChequebookFromContract(path string, backend chequebook.Backend) error {
- hexkey := common.Bytes2Hex(self.Contract.Bytes())
+func (lp *LocalProfile) newChequebookFromContract(path string, backend chequebook.Backend) error {
+ hexkey := common.Bytes2Hex(lp.Contract.Bytes())
err := os.MkdirAll(filepath.Join(path, "chequebooks"), os.ModePerm)
if err != nil {
return fmt.Errorf("unable to create directory for chequebooks: %v", err)
}
chbookpath := filepath.Join(path, "chequebooks", hexkey+".json")
- self.chbook, err = chequebook.LoadChequebook(chbookpath, self.privateKey, backend, true)
+ lp.chbook, err = chequebook.LoadChequebook(chbookpath, lp.privateKey, backend, true)
if err != nil {
- self.chbook, err = chequebook.NewChequebook(chbookpath, self.Contract, self.privateKey, backend)
+ lp.chbook, err = chequebook.NewChequebook(chbookpath, lp.Contract, lp.privateKey, backend)
if err != nil {
- log.Warn(fmt.Sprintf("unable to initialise chequebook (owner: %v): %v", self.owner.Hex(), err))
- return fmt.Errorf("unable to initialise chequebook (owner: %v): %v", self.owner.Hex(), err)
+ log.Warn(fmt.Sprintf("unable to initialise chequebook (owner: %v): %v", lp.owner.Hex(), err))
+ return fmt.Errorf("unable to initialise chequebook (owner: %v): %v", lp.owner.Hex(), err)
}
}
- self.chbook.AutoDeposit(self.AutoDepositInterval, self.AutoDepositThreshold, self.AutoDepositBuffer)
- log.Info(fmt.Sprintf("auto deposit ON for %v -> %v: interval = %v, threshold = %v, buffer = %v)", crypto.PubkeyToAddress(*(self.publicKey)).Hex()[:8], self.Contract.Hex()[:8], self.AutoDepositInterval, self.AutoDepositThreshold, self.AutoDepositBuffer))
+ lp.chbook.AutoDeposit(lp.AutoDepositInterval, lp.AutoDepositThreshold, lp.AutoDepositBuffer)
+ log.Info(fmt.Sprintf("auto deposit ON for %v -> %v: interval = %v, threshold = %v, buffer = %v)", crypto.PubkeyToAddress(*(lp.publicKey)).Hex()[:8], lp.Contract.Hex()[:8], lp.AutoDepositInterval, lp.AutoDepositThreshold, lp.AutoDepositBuffer))
return nil
}
diff --git a/swarm/services/swap/swap/swap.go b/swarm/services/swap/swap/swap.go
index a78f1f0e2..0afca9ab3 100644
--- a/swarm/services/swap/swap/swap.go
+++ b/swarm/services/swap/swap/swap.go
@@ -22,14 +22,14 @@ import (
"sync"
"time"
- "github.com/ethereum/go-ethereum/log"
+ "github.com/ethereum/go-ethereum/swarm/log"
)
// SwAP Swarm Accounting Protocol with
// Swift Automatic Payments
// a peer to peer micropayment system
-// public swap profile
+// Profile - public swap profile
// public parameters for SWAP, serializable config struct passed in handshake
type Profile struct {
BuyAt *big.Int // accepted max price for chunk
@@ -55,34 +55,33 @@ type Params struct {
*Strategy
}
-// Promise
-// 3rd party Provable Promise of Payment
+// Promise - 3rd party Provable Promise of Payment
// issued by outPayment
-// serialisable to send with Protocol
+// serializable to send with Protocol
type Promise interface{}
-// interface for the peer protocol for testing or external alternative payment
+// Protocol interface for the peer protocol for testing or external alternative payment
type Protocol interface {
Pay(int, Promise) // units, payment proof
Drop()
String() string
}
-// interface for the (delayed) ougoing payment system with autodeposit
+// OutPayment interface for the (delayed) outgoing payment system with auto-deposit
type OutPayment interface {
Issue(amount *big.Int) (promise Promise, err error)
AutoDeposit(interval time.Duration, threshold, buffer *big.Int)
Stop()
}
-// interface for the (delayed) incoming payment system with autocash
+// InPayment interface for the (delayed) incoming payment system with autocash
type InPayment interface {
Receive(promise Promise) (*big.Int, error)
AutoCash(cashInterval time.Duration, maxUncashed *big.Int)
Stop()
}
-// swap is the swarm accounting protocol instance
+// Swap is the swarm accounting protocol instance
// * pairwise accounting and payments
type Swap struct {
lock sync.Mutex // mutex for balance access
@@ -93,160 +92,161 @@ type Swap struct {
Payment
}
+// Payment handlers
type Payment struct {
Out OutPayment // outgoing payment handler
In InPayment // incoming payment handler
Buys, Sells bool
}
-// swap constructor
-func New(local *Params, pm Payment, proto Protocol) (self *Swap, err error) {
+// New - swap constructor
+func New(local *Params, pm Payment, proto Protocol) (swap *Swap, err error) {
- self = &Swap{
+ swap = &Swap{
local: local,
Payment: pm,
proto: proto,
}
- self.SetParams(local)
+ swap.SetParams(local)
return
}
-// entry point for setting remote swap profile (e.g from handshake or other message)
-func (self *Swap) SetRemote(remote *Profile) {
- defer self.lock.Unlock()
- self.lock.Lock()
+// SetRemote - entry point for setting remote swap profile (e.g from handshake or other message)
+func (swap *Swap) SetRemote(remote *Profile) {
+ defer swap.lock.Unlock()
+ swap.lock.Lock()
- self.remote = remote
- if self.Sells && (remote.BuyAt.Sign() <= 0 || self.local.SellAt.Sign() <= 0 || remote.BuyAt.Cmp(self.local.SellAt) < 0) {
- self.Out.Stop()
- self.Sells = false
+ swap.remote = remote
+ if swap.Sells && (remote.BuyAt.Sign() <= 0 || swap.local.SellAt.Sign() <= 0 || remote.BuyAt.Cmp(swap.local.SellAt) < 0) {
+ swap.Out.Stop()
+ swap.Sells = false
}
- if self.Buys && (remote.SellAt.Sign() <= 0 || self.local.BuyAt.Sign() <= 0 || self.local.BuyAt.Cmp(self.remote.SellAt) < 0) {
- self.In.Stop()
- self.Buys = false
+ if swap.Buys && (remote.SellAt.Sign() <= 0 || swap.local.BuyAt.Sign() <= 0 || swap.local.BuyAt.Cmp(swap.remote.SellAt) < 0) {
+ swap.In.Stop()
+ swap.Buys = false
}
- log.Debug(fmt.Sprintf("<%v> remote profile set: pay at: %v, drop at: %v, buy at: %v, sell at: %v", self.proto, remote.PayAt, remote.DropAt, remote.BuyAt, remote.SellAt))
+ log.Debug(fmt.Sprintf("<%v> remote profile set: pay at: %v, drop at: %v, buy at: %v, sell at: %v", swap.proto, remote.PayAt, remote.DropAt, remote.BuyAt, remote.SellAt))
}
-// to set strategy dynamically
-func (self *Swap) SetParams(local *Params) {
- defer self.lock.Unlock()
- self.lock.Lock()
- self.local = local
- self.setParams(local)
+// SetParams - to set strategy dynamically
+func (swap *Swap) SetParams(local *Params) {
+ defer swap.lock.Unlock()
+ swap.lock.Lock()
+ swap.local = local
+ swap.setParams(local)
}
-// caller holds the lock
+// setParams - caller holds the lock
+func (swap *Swap) setParams(local *Params) {
-func (self *Swap) setParams(local *Params) {
-
- if self.Sells {
- self.In.AutoCash(local.AutoCashInterval, local.AutoCashThreshold)
- log.Info(fmt.Sprintf("<%v> set autocash to every %v, max uncashed limit: %v", self.proto, local.AutoCashInterval, local.AutoCashThreshold))
+ if swap.Sells {
+ swap.In.AutoCash(local.AutoCashInterval, local.AutoCashThreshold)
+ log.Info(fmt.Sprintf("<%v> set autocash to every %v, max uncashed limit: %v", swap.proto, local.AutoCashInterval, local.AutoCashThreshold))
} else {
- log.Info(fmt.Sprintf("<%v> autocash off (not selling)", self.proto))
+ log.Info(fmt.Sprintf("<%v> autocash off (not selling)", swap.proto))
}
- if self.Buys {
- self.Out.AutoDeposit(local.AutoDepositInterval, local.AutoDepositThreshold, local.AutoDepositBuffer)
- log.Info(fmt.Sprintf("<%v> set autodeposit to every %v, pay at: %v, buffer: %v", self.proto, local.AutoDepositInterval, local.AutoDepositThreshold, local.AutoDepositBuffer))
+ if swap.Buys {
+ swap.Out.AutoDeposit(local.AutoDepositInterval, local.AutoDepositThreshold, local.AutoDepositBuffer)
+ log.Info(fmt.Sprintf("<%v> set autodeposit to every %v, pay at: %v, buffer: %v", swap.proto, local.AutoDepositInterval, local.AutoDepositThreshold, local.AutoDepositBuffer))
} else {
- log.Info(fmt.Sprintf("<%v> autodeposit off (not buying)", self.proto))
+ log.Info(fmt.Sprintf("<%v> autodeposit off (not buying)", swap.proto))
}
}
-// Add(n)
+// Add (n)
// n > 0 called when promised/provided n units of service
// n < 0 called when used/requested n units of service
-func (self *Swap) Add(n int) error {
- defer self.lock.Unlock()
- self.lock.Lock()
- self.balance += n
- if !self.Sells && self.balance > 0 {
- log.Trace(fmt.Sprintf("<%v> remote peer cannot have debt (balance: %v)", self.proto, self.balance))
- self.proto.Drop()
- return fmt.Errorf("[SWAP] <%v> remote peer cannot have debt (balance: %v)", self.proto, self.balance)
+func (swap *Swap) Add(n int) error {
+ defer swap.lock.Unlock()
+ swap.lock.Lock()
+ swap.balance += n
+ if !swap.Sells && swap.balance > 0 {
+ log.Trace(fmt.Sprintf("<%v> remote peer cannot have debt (balance: %v)", swap.proto, swap.balance))
+ swap.proto.Drop()
+ return fmt.Errorf("[SWAP] <%v> remote peer cannot have debt (balance: %v)", swap.proto, swap.balance)
}
- if !self.Buys && self.balance < 0 {
- log.Trace(fmt.Sprintf("<%v> we cannot have debt (balance: %v)", self.proto, self.balance))
- return fmt.Errorf("[SWAP] <%v> we cannot have debt (balance: %v)", self.proto, self.balance)
+ if !swap.Buys && swap.balance < 0 {
+ log.Trace(fmt.Sprintf("<%v> we cannot have debt (balance: %v)", swap.proto, swap.balance))
+ return fmt.Errorf("[SWAP] <%v> we cannot have debt (balance: %v)", swap.proto, swap.balance)
}
- if self.balance >= int(self.local.DropAt) {
- log.Trace(fmt.Sprintf("<%v> remote peer has too much debt (balance: %v, disconnect threshold: %v)", self.proto, self.balance, self.local.DropAt))
- self.proto.Drop()
- return fmt.Errorf("[SWAP] <%v> remote peer has too much debt (balance: %v, disconnect threshold: %v)", self.proto, self.balance, self.local.DropAt)
- } else if self.balance <= -int(self.remote.PayAt) {
- self.send()
+ if swap.balance >= int(swap.local.DropAt) {
+ log.Trace(fmt.Sprintf("<%v> remote peer has too much debt (balance: %v, disconnect threshold: %v)", swap.proto, swap.balance, swap.local.DropAt))
+ swap.proto.Drop()
+ return fmt.Errorf("[SWAP] <%v> remote peer has too much debt (balance: %v, disconnect threshold: %v)", swap.proto, swap.balance, swap.local.DropAt)
+ } else if swap.balance <= -int(swap.remote.PayAt) {
+ swap.send()
}
return nil
}
-func (self *Swap) Balance() int {
- defer self.lock.Unlock()
- self.lock.Lock()
- return self.balance
+// Balance accessor
+func (swap *Swap) Balance() int {
+ defer swap.lock.Unlock()
+ swap.lock.Lock()
+ return swap.balance
}
-// send(units) is called when payment is due
+// send (units) is called when payment is due
// In case of insolvency no promise is issued and sent, safe against fraud
// No return value: no error = payment is opportunistic = hang in till dropped
-func (self *Swap) send() {
- if self.local.BuyAt != nil && self.balance < 0 {
- amount := big.NewInt(int64(-self.balance))
- amount.Mul(amount, self.remote.SellAt)
- promise, err := self.Out.Issue(amount)
+func (swap *Swap) send() {
+ if swap.local.BuyAt != nil && swap.balance < 0 {
+ amount := big.NewInt(int64(-swap.balance))
+ amount.Mul(amount, swap.remote.SellAt)
+ promise, err := swap.Out.Issue(amount)
if err != nil {
- log.Warn(fmt.Sprintf("<%v> cannot issue cheque (amount: %v, channel: %v): %v", self.proto, amount, self.Out, err))
+ log.Warn(fmt.Sprintf("<%v> cannot issue cheque (amount: %v, channel: %v): %v", swap.proto, amount, swap.Out, err))
} else {
- log.Warn(fmt.Sprintf("<%v> cheque issued (amount: %v, channel: %v)", self.proto, amount, self.Out))
- self.proto.Pay(-self.balance, promise)
- self.balance = 0
+ log.Warn(fmt.Sprintf("<%v> cheque issued (amount: %v, channel: %v)", swap.proto, amount, swap.Out))
+ swap.proto.Pay(-swap.balance, promise)
+ swap.balance = 0
}
}
}
-// receive(units, promise) is called by the protocol when a payment msg is received
+// Receive (units, promise) is called by the protocol when a payment msg is received
// returns error if promise is invalid.
-func (self *Swap) Receive(units int, promise Promise) error {
+func (swap *Swap) Receive(units int, promise Promise) error {
if units <= 0 {
return fmt.Errorf("invalid units: %v <= 0", units)
}
price := new(big.Int).SetInt64(int64(units))
- price.Mul(price, self.local.SellAt)
+ price.Mul(price, swap.local.SellAt)
- amount, err := self.In.Receive(promise)
+ amount, err := swap.In.Receive(promise)
if err != nil {
err = fmt.Errorf("invalid promise: %v", err)
} else if price.Cmp(amount) != 0 {
// verify amount = units * unit sale price
- return fmt.Errorf("invalid amount: %v = %v * %v (units sent in msg * agreed sale unit price) != %v (signed in cheque)", price, units, self.local.SellAt, amount)
+ return fmt.Errorf("invalid amount: %v = %v * %v (units sent in msg * agreed sale unit price) != %v (signed in cheque)", price, units, swap.local.SellAt, amount)
}
if err != nil {
- log.Trace(fmt.Sprintf("<%v> invalid promise (amount: %v, channel: %v): %v", self.proto, amount, self.In, err))
+ log.Trace(fmt.Sprintf("<%v> invalid promise (amount: %v, channel: %v): %v", swap.proto, amount, swap.In, err))
return err
}
// credit remote peer with units
- self.Add(-units)
- log.Trace(fmt.Sprintf("<%v> received promise (amount: %v, channel: %v): %v", self.proto, amount, self.In, promise))
+ swap.Add(-units)
+ log.Trace(fmt.Sprintf("<%v> received promise (amount: %v, channel: %v): %v", swap.proto, amount, swap.In, promise))
return nil
}
-// stop() causes autocash loop to terminate.
+// Stop causes autocash loop to terminate.
// Called after protocol handle loop terminates.
-func (self *Swap) Stop() {
- defer self.lock.Unlock()
- self.lock.Lock()
- if self.Buys {
- self.Out.Stop()
+func (swap *Swap) Stop() {
+ defer swap.lock.Unlock()
+ swap.lock.Lock()
+ if swap.Buys {
+ swap.Out.Stop()
}
- if self.Sells {
- self.In.Stop()
+ if swap.Sells {
+ swap.In.Stop()
}
}
diff --git a/swarm/services/swap/swap/swap_test.go b/swarm/services/swap/swap/swap_test.go
index 222e0770f..d0e34f8a5 100644
--- a/swarm/services/swap/swap/swap_test.go
+++ b/swarm/services/swap/swap/swap_test.go
@@ -34,20 +34,20 @@ type testPromise struct {
amount *big.Int
}
-func (self *testInPayment) Receive(promise Promise) (*big.Int, error) {
+func (test *testInPayment) Receive(promise Promise) (*big.Int, error) {
p := promise.(*testPromise)
- self.received = append(self.received, p)
+ test.received = append(test.received, p)
return p.amount, nil
}
-func (self *testInPayment) AutoCash(interval time.Duration, limit *big.Int) {
- self.autocashInterval = interval
- self.autocashLimit = limit
+func (test *testInPayment) AutoCash(interval time.Duration, limit *big.Int) {
+ test.autocashInterval = interval
+ test.autocashLimit = limit
}
-func (self *testInPayment) Cash() (string, error) { return "", nil }
+func (test *testInPayment) Cash() (string, error) { return "", nil }
-func (self *testInPayment) Stop() {}
+func (test *testInPayment) Stop() {}
type testOutPayment struct {
deposits []*big.Int
@@ -56,22 +56,22 @@ type testOutPayment struct {
autodepositBuffer *big.Int
}
-func (self *testOutPayment) Issue(amount *big.Int) (promise Promise, err error) {
+func (test *testOutPayment) Issue(amount *big.Int) (promise Promise, err error) {
return &testPromise{amount}, nil
}
-func (self *testOutPayment) Deposit(amount *big.Int) (string, error) {
- self.deposits = append(self.deposits, amount)
+func (test *testOutPayment) Deposit(amount *big.Int) (string, error) {
+ test.deposits = append(test.deposits, amount)
return "", nil
}
-func (self *testOutPayment) AutoDeposit(interval time.Duration, threshold, buffer *big.Int) {
- self.autodepositInterval = interval
- self.autodepositThreshold = threshold
- self.autodepositBuffer = buffer
+func (test *testOutPayment) AutoDeposit(interval time.Duration, threshold, buffer *big.Int) {
+ test.autodepositInterval = interval
+ test.autodepositThreshold = threshold
+ test.autodepositBuffer = buffer
}
-func (self *testOutPayment) Stop() {}
+func (test *testOutPayment) Stop() {}
type testProtocol struct {
drop bool
@@ -79,18 +79,18 @@ type testProtocol struct {
promises []*testPromise
}
-func (self *testProtocol) Drop() {
- self.drop = true
+func (test *testProtocol) Drop() {
+ test.drop = true
}
-func (self *testProtocol) String() string {
+func (test *testProtocol) String() string {
return ""
}
-func (self *testProtocol) Pay(amount int, promise Promise) {
+func (test *testProtocol) Pay(amount int, promise Promise) {
p := promise.(*testPromise)
- self.promises = append(self.promises, p)
- self.amounts = append(self.amounts, amount)
+ test.promises = append(test.promises, p)
+ test.amounts = append(test.amounts, amount)
}
func TestSwap(t *testing.T) {