Skip to content
This repository has been archived by the owner on Aug 2, 2021. It is now read-only.

Commit

Permalink
swarm, swap: pass chequebook address at start-up (#1718)
Browse files Browse the repository at this point in the history
swarm, swap: use passed --chequebook param, swap: don't use chequebookAddress on swap.new, create function NewInstanceAt

- updated call to swap.New in tests
- swapEnabled err checking
- updated comment at NewInstanceAt
- error handling and renaming
- rename InstanceAt to BindToContract
- refactor => chequebook setup in swap, remove verifyContract
- err returning and err handling
  • Loading branch information
Eknir authored and zelig committed Sep 10, 2019
1 parent f8e4dc6 commit 1687d5f
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 24 deletions.
2 changes: 1 addition & 1 deletion swap/protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func (s *Swap) verifyHandshake(msg interface{}) error {
return ErrEmptyAddressInSignature
}

return s.verifyContract(context.Background(), handshake.ContractAddress)
return contract.ValidateCode(context.Background(), s.backend, handshake.ContractAddress)
}

// run is the actual swap protocol run method
Expand Down
51 changes: 40 additions & 11 deletions swap/swap.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,14 @@ func NewParams() *Params {
}

// New - swap constructor
func New(stateStore state.Store, prvkey *ecdsa.PrivateKey, contract common.Address, backend contract.Backend) *Swap {
func New(stateStore state.Store, prvkey *ecdsa.PrivateKey, backend contract.Backend) *Swap {
return &Swap{
store: stateStore,
balances: make(map[enode.ID]int64),
cheques: make(map[enode.ID]*Cheque),
peers: make(map[enode.ID]*Peer),
backend: backend,
owner: createOwner(prvkey, contract),
owner: createOwner(prvkey),
params: NewParams(),
paymentThreshold: DefaultPaymentThreshold,
disconnectThreshold: DefaultDisconnectThreshold,
Expand Down Expand Up @@ -127,13 +127,12 @@ func keyToID(key string, prefix string) enode.ID {
}

// createOwner assings keys and addresses
func createOwner(prvkey *ecdsa.PrivateKey, contract common.Address) *Owner {
func createOwner(prvkey *ecdsa.PrivateKey) *Owner {
pubkey := &prvkey.PublicKey
return &Owner{
address: crypto.PubkeyToAddress(*pubkey),
privateKey: prvkey,
publicKey: pubkey,
Contract: contract,
address: crypto.PubkeyToAddress(*pubkey),
}
}

Expand Down Expand Up @@ -522,9 +521,9 @@ func (s *Swap) GetParams() *swap.Params {
return s.contract.ContractParams()
}

// verifyContract checks if the bytecode found at address matches the expected bytecode
func (s *Swap) verifyContract(ctx context.Context, address common.Address) error {
return contract.ValidateCode(ctx, s.backend, address)
// setChequebookAddr sets the chequebook address
func (s *Swap) setChequebookAddr(chequebookAddr common.Address) {
s.owner.Contract = chequebookAddr
}

// getContractOwner retrieve the owner of the chequebook at address from the blockchain
Expand All @@ -537,8 +536,38 @@ func (s *Swap) getContractOwner(ctx context.Context, address common.Address) (co
return contr.Issuer(nil)
}

// Deploy deploys the Swap contract
func (s *Swap) Deploy(ctx context.Context, backend swap.Backend, path string) error {
// StartChequebook deploys a new instance of a chequebook if chequebookAddr is empty, otherwise it wil bind to an existing instance
func (s *Swap) StartChequebook(chequebookAddr common.Address) error {
if chequebookAddr != (common.Address{}) {
if err := s.BindToContractAt(chequebookAddr); err != nil {
return err
}
log.Info("Using the provided chequebook", "chequebookAddr", chequebookAddr)
} else {
if err := s.Deploy(context.Background(), s.backend); err != nil {
return err
}
log.Info("New SWAP contract deployed", "contract info", s.DeploySuccess())
}
return nil
}

// BindToContractAt binds an instance of an already existing chequebook contract at address and sets chequebookAddr
func (s *Swap) BindToContractAt(address common.Address) (err error) {

if err := contract.ValidateCode(context.Background(), s.backend, address); err != nil {
return fmt.Errorf("contract validation for %v failed: %v", address, err)
}
s.contract, err = contract.InstanceAt(address, s.backend)
if err != nil {
return err
}
s.setChequebookAddr(address)
return nil
}

// Deploy deploys the Swap contract and sets the contract address
func (s *Swap) Deploy(ctx context.Context, backend swap.Backend) error {
opts := bind.NewKeyedTransactor(s.owner.privateKey)
// initial topup value
opts.Value = big.NewInt(int64(s.params.InitialDepositAmount))
Expand All @@ -550,7 +579,7 @@ func (s *Swap) Deploy(ctx context.Context, backend swap.Backend, path string) er
log.Error("unable to deploy swap", "error", err)
return err
}
s.owner.Contract = address
s.setChequebookAddr(address)
log.Info("swap deployed", "address", address.Hex(), "owner", opts.From.Hex())

return err
Expand Down
14 changes: 7 additions & 7 deletions swap/swap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,7 @@ func newBaseTestSwap(t *testing.T, key *ecdsa.PrivateKey) (*Swap, string) {
}
log.Debug("creating simulated backend")

swap := New(stateStore, key, common.Address{}, testBackend)
swap := New(stateStore, key, testBackend)
return swap, dir
}

Expand Down Expand Up @@ -644,8 +644,8 @@ func TestVerifyChequeInvalidSignature(t *testing.T) {
}
}

// tests if verifyContract accepts an address with the correct bytecode
func TestVerifyContract(t *testing.T) {
// tests if TestValidateCode accepts an address with the correct bytecode
func TestValidateCode(t *testing.T) {
swap, clean := newTestSwap(t, ownerKey)
defer clean()

Expand All @@ -658,13 +658,13 @@ func TestVerifyContract(t *testing.T) {

testBackend.Commit()

if err = swap.verifyContract(context.TODO(), addr); err != nil {
if err = cswap.ValidateCode(context.TODO(), swap.backend, addr); err != nil {
t.Fatalf("Contract verification failed: %v", err)
}
}

// tests if verifyContract rejects an address with different bytecode
func TestVerifyContractWrongContract(t *testing.T) {
// tests if ValidateCode rejects an address with different bytecode
func TestValidateWrongCode(t *testing.T) {
swap, clean := newTestSwap(t, ownerKey)
defer clean()

Expand All @@ -679,7 +679,7 @@ func TestVerifyContractWrongContract(t *testing.T) {
testBackend.Commit()

// since the bytecode is different this should throw an error
if err = swap.verifyContract(context.TODO(), addr); err != cswap.ErrNotASwapContract {
if err = cswap.ValidateCode(context.TODO(), swap.backend, addr); err != cswap.ErrNotASwapContract {
t.Fatalf("Contract verification verified wrong contract: %v", err)
}
}
Expand Down
8 changes: 3 additions & 5 deletions swarm.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ func NewSwarm(config *api.Config, mockStore *mock.NodeStore) (self *Swarm, err e
return nil, err
}
// create the accounting objects
self.swap = swap.New(swapStore, self.privateKey, self.config.Contract, self.backend)
self.swap = swap.New(swapStore, self.privateKey, self.backend)
// start anonymous metrics collection
self.accountingMetrics = protocols.SetupAccountingMetrics(10*time.Second, filepath.Join(config.Path, "metrics.db"))
}
Expand Down Expand Up @@ -374,11 +374,9 @@ func (s *Swarm) Start(srv *p2p.Server) error {
log.Info("Updated bzz local addr", "oaddr", fmt.Sprintf("%x", newaddr.OAddr), "uaddr", fmt.Sprintf("%s", newaddr.UAddr))

if s.config.SwapEnabled {
err := s.swap.Deploy(context.Background(), s.backend, s.config.Path)
if err != nil {
return fmt.Errorf("Unable to deploy swap contract: %v", err)
if err := s.swap.StartChequebook(s.config.Contract); err != nil {
return err
}
log.Info("SWAP contract deployed", "contract info", s.swap.DeploySuccess())
} else {
log.Info("SWAP disabled: no chequebook set")
}
Expand Down

0 comments on commit 1687d5f

Please sign in to comment.