Skip to content

Commit

Permalink
Merge pull request ethereum#587 from dleonard00/swarm-network-rewrite…
Browse files Browse the repository at this point in the history
…-golint-warnings

golint warnings
  • Loading branch information
nonsense authored May 24, 2018
2 parents 3d7e57b + 8f584c8 commit 9386c44
Show file tree
Hide file tree
Showing 4 changed files with 183 additions and 178 deletions.
2 changes: 1 addition & 1 deletion swarm/api/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ type Config struct {
*storage.DPAParams
*storage.LocalStoreParams
*network.HiveParams
Swap *swap.SwapParams
Swap *swap.LocalProfile
Pss *pss.PssParams
//*network.SyncParams
Contract common.Address
Expand Down
139 changes: 72 additions & 67 deletions swarm/services/swap/swap.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,16 +59,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
Expand All @@ -80,9 +83,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{
Expand All @@ -102,12 +105,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),
Expand All @@ -117,43 +120,42 @@ 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
// n > 0 called when sending chunks = receiving retrieve requests
// 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
in *chequebook.Inbox
out *chequebook.Outbox
)

// 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, crypto.ToECDSAPub(common.FromHex(remote.PublicKey)), backend)
// remoteProfile contract valid, create inbox
in, err = chequebook.NewInbox(localProfile.privateKey, remoteProfile.Contract, localProfile.Beneficiary, crypto.ToECDSAPub(common.FromHex(remoteProfile.PublicKey)), 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{
Expand All @@ -162,20 +164,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"
}
Expand All @@ -184,66 +186,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++ {
Expand All @@ -263,28 +268,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
}
Loading

0 comments on commit 9386c44

Please sign in to comment.