Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(wire): add ecdsa authentication to wire #51

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
181 changes: 181 additions & 0 deletions client/client_net_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
// Copyright 2020 - See NOTICE file for copyright holders.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package client_test

import (
"context"
"math/big"
"sync"
"testing"

"github.com/ethereum/go-ethereum/common"
ethchannel "github.com/perun-network/perun-eth-backend/channel"
"github.com/perun-network/perun-eth-backend/channel/test"
ctest "github.com/perun-network/perun-eth-backend/client/test"
ethwallet "github.com/perun-network/perun-eth-backend/wallet"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"perun.network/go-perun/channel"
chtest "perun.network/go-perun/channel/test"
"perun.network/go-perun/client"
clienttest "perun.network/go-perun/client/test"
"perun.network/go-perun/log"
"perun.network/go-perun/wire"
pkgtest "polycry.pt/poly-go/test"
)

func TestNetProgression(t *testing.T) {
rng := pkgtest.Prng(t)

names := []string{"Paul", "Paula"}
backendSetup := test.NewSetup(t, rng, 2, ctest.BlockInterval, TxFinalityDepth)
roleSetups := ctest.MakeNetRoleSetups(t, rng, backendSetup, names)
clients := [2]clienttest.Executer{
clienttest.NewPaul(t, roleSetups[0]),
clienttest.NewPaula(t, roleSetups[1]),
}

appAddress := deployMockApp(t, backendSetup)
appAddrBackend := appAddress.(*ethwallet.Address)
appID := &ethchannel.AppID{Address: appAddrBackend}
app := channel.NewMockApp(appID)
channel.RegisterApp(app)

execConfig := &clienttest.ProgressionExecConfig{
BaseExecConfig: clienttest.MakeBaseExecConfig(
clientAddresses(roleSetups),
backendSetup.Asset,
[2]*big.Int{big.NewInt(99), big.NewInt(1)},
client.WithApp(app, channel.NewMockOp(channel.OpValid)),
),
}

ctx, cancel := context.WithTimeout(context.Background(), twoPartyTestTimeout)
defer cancel()
clienttest.ExecuteTwoPartyTest(ctx, t, clients, execConfig)
}

func TestNetPaymentHappy(t *testing.T) {
log.Info("Starting happy test")
rng := pkgtest.Prng(t)

const A, B = 0, 1 // Indices of Alice and Bob
var (
name = [2]string{"Alice", "Bob"}
role [2]clienttest.Executer
)

s := test.NewSetup(t, rng, 2, ctest.BlockInterval, TxFinalityDepth)
setup := ctest.MakeNetRoleSetups(t, rng, s, name[:])

role[A] = clienttest.NewAlice(t, setup[A])
role[B] = clienttest.NewBob(t, setup[B])
// enable stages synchronization
stages := role[A].EnableStages()
role[B].SetStages(stages)

execConfig := &clienttest.AliceBobExecConfig{
BaseExecConfig: clienttest.MakeBaseExecConfig(
[2]wire.Address{setup[A].Identity.Address(), setup[B].Identity.Address()},
s.Asset,
[2]*big.Int{big.NewInt(100), big.NewInt(100)},
client.WithApp(chtest.NewRandomAppAndData(rng)),
),
NumPayments: [2]int{2, 2},
TxAmounts: [2]*big.Int{big.NewInt(5), big.NewInt(3)},
}

var wg sync.WaitGroup
wg.Add(2)
for i := 0; i < 2; i++ {
go func(i int) {
defer wg.Done()
log.Infof("Starting %s.Execute", name[i])
role[i].Execute(execConfig)
}(i)
}

wg.Wait()

// Assert correct final balances
aliceToBob := big.NewInt(int64(execConfig.NumPayments[A])*execConfig.TxAmounts[A].Int64() -
int64(execConfig.NumPayments[B])*execConfig.TxAmounts[B].Int64())
finalBalAlice := new(big.Int).Sub(execConfig.InitBals()[A], aliceToBob)
finalBalBob := new(big.Int).Add(execConfig.InitBals()[B], aliceToBob)
// reset context timeout
ctx, cancel := context.WithTimeout(context.Background(), ctest.DefaultTimeout)
defer cancel()
assertBal := func(addr *ethwallet.Address, bal *big.Int) {
b, err := s.SimBackend.BalanceAt(ctx, common.Address(*addr), nil)
require.NoError(t, err)
assert.Zero(t, bal.Cmp(b), "ETH balance mismatch")
}

assertBal(s.Recvs[A], finalBalAlice)
assertBal(s.Recvs[B], finalBalBob)

log.Info("Happy test done")
}

func TestNetPaymentDispute(t *testing.T) {
log.Info("Starting dispute test")
rng := pkgtest.Prng(t)

const A, B = 0, 1 // Indices of Mallory and Carol
var (
name = [2]string{"Mallory", "Carol"}
role [2]clienttest.Executer
)

s := test.NewSetup(t, rng, 2, ctest.BlockInterval, TxFinalityDepth)
setup := ctest.MakeNetRoleSetups(t, rng, s, name[:])

role[A] = clienttest.NewMallory(t, setup[A])
role[B] = clienttest.NewCarol(t, setup[B])

execConfig := &clienttest.MalloryCarolExecConfig{
BaseExecConfig: clienttest.MakeBaseExecConfig(
[2]wire.Address{setup[A].Identity.Address(), setup[B].Identity.Address()},
s.Asset,
[2]*big.Int{big.NewInt(100), big.NewInt(1)},
client.WithoutApp(),
),
NumPayments: [2]int{5, 0},
TxAmounts: [2]*big.Int{big.NewInt(20), big.NewInt(0)},
}

ctx, cancel := context.WithTimeout(context.Background(), twoPartyTestTimeout)
defer cancel()
clienttest.ExecuteTwoPartyTest(ctx, t, role, execConfig)

// Assert correct final balances
netTransfer := big.NewInt(int64(execConfig.NumPayments[A])*execConfig.TxAmounts[A].Int64() -
int64(execConfig.NumPayments[B])*execConfig.TxAmounts[B].Int64())
finalBal := [2]*big.Int{
new(big.Int).Sub(execConfig.InitBals()[A], netTransfer),
new(big.Int).Add(execConfig.InitBals()[B], netTransfer),
}
// reset context timeout
ctx, cancel = context.WithTimeout(context.Background(), ctest.DefaultTimeout)
defer cancel()
for i, bal := range finalBal {
b, err := s.SimBackend.BalanceAt(ctx, common.Address(*s.Recvs[i]), nil)
require.NoError(t, err)
assert.Zero(t, b.Cmp(bal), "ETH balance mismatch")
}

log.Info("Dispute test done")
}
94 changes: 93 additions & 1 deletion client/test/setup.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2021 - See NOTICE file for copyright holders.
// Copyright 2024 - See NOTICE file for copyright holders.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -15,15 +15,23 @@
package test

import (
"crypto/tls"
"fmt"
"math/rand"
"net"
"testing"
"time"

ethctest "github.com/perun-network/perun-eth-backend/channel/test"
ethwtest "github.com/perun-network/perun-eth-backend/wallet/test"
"github.com/stretchr/testify/assert"

clienttest "perun.network/go-perun/client/test"
"perun.network/go-perun/watcher/local"
"perun.network/go-perun/wire"
perunnet "perun.network/go-perun/wire/net"
"perun.network/go-perun/wire/net/simple"
perunio "perun.network/go-perun/wire/perunio/serializer"
wiretest "perun.network/go-perun/wire/test"
)

Expand All @@ -34,6 +42,9 @@ const (
BlockInterval = 200 * time.Millisecond
// challenge duration in blocks that is used by MakeRoleSetups.
challengeDurationBlocks = 90

// dialerTimeout is the timeout for dialing a connection.
dialerTimeout = 15 * time.Second
)

// MakeRoleSetups creates a two party client test setup with the provided names.
Expand Down Expand Up @@ -62,3 +73,84 @@ func MakeRoleSetups(rng *rand.Rand, s *ethctest.Setup, names []string) []clientt
}
return setups
}

// MakeNetRoleSetups creates a two party client test setup with the provided names and uses the default TLS-bus from go-perun.
func MakeNetRoleSetups(t *testing.T, rng *rand.Rand, s *ethctest.Setup, names []string) []clienttest.RoleSetup {
t.Helper()
setups := make([]clienttest.RoleSetup, len(names))
commonName := "127.0.0.1"
sans := []string{"127.0.0.1", "localhost"}
tlsConfigs, err := GenerateSelfSignedCertConfigs(commonName, sans, len(names))
if err != nil {
panic("Error generating TLS configs: " + err.Error())
}

hosts := make([]string, len(names))
for i := 0; i < len(names); i++ {
port, err := findFreePort()
assert.NoError(t, err, "Error finding free port")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Auf lange Sicht wird es vermutlich besser sein eine Funktion zum listener hinzuzufügen (wenn er nicht schon eine hat) um den Port zu bekommen. Einen tcp listener aufzumachen nur um den Port zu bekommen erscheint mir unnötig.

Also effektiv erst die listener erdstellen und dann für jeden listener den Port abfragen (wie es in findFreePorts gemacht wird) + evtl. kleine Anpassung am perun code um diese Funktionalität bereitzustellen.

hosts[i] = fmt.Sprintf("127.0.0.1:%d", port)
}

dialers, listeners := makeSimpleDialersListeners(t, tlsConfigs, hosts)

for i := 0; i < len(setups); i++ {
watcher, err := local.NewWatcher(s.Adjs[i])
if err != nil {
panic("Error initializing watcher: " + err.Error())
}

acc := wiretest.NewRandomAccount(rng)

for j := 0; j < len(setups); j++ {
dialers[j].Register(acc.Address(), hosts[i])
}

bus := perunnet.NewBus(acc, dialers[i], perunio.Serializer())
go bus.Listen(listeners[i])

setups[i] = clienttest.RoleSetup{
Name: names[i],
Identity: acc,
Bus: bus,
Funder: s.Funders[i],
Adjudicator: s.Adjs[i],
Watcher: watcher,
Wallet: ethwtest.NewTmpWallet(),
Timeout: DefaultTimeout,
// Scaled due to simbackend automining progressing faster than real time.
ChallengeDuration: challengeDurationBlocks * uint64(time.Second/BlockInterval),
Errors: make(chan error),
BalanceReader: s.SimBackend.NewBalanceReader(s.Accs[i].Address()),
}
}
return setups
}

func makeSimpleDialersListeners(t *testing.T, tlsConfigs []*tls.Config, hosts []string) ([]*simple.Dialer, []*simple.Listener) {
t.Helper()
dialers := make([]*simple.Dialer, len(tlsConfigs))
listeners := make([]*simple.Listener, len(tlsConfigs))

var err error
for i, tlsConfig := range tlsConfigs {
dialers[i] = simple.NewTCPDialer(dialerTimeout, tlsConfig)
listeners[i], err = simple.NewTCPListener(hosts[i], tlsConfig)
assert.NoError(t, err, "Error creating listener")
}

return dialers, listeners
}

func findFreePort() (int, error) {
// Create a listener on a random port to get an available port.
l, err := net.Listen("tcp", "127.0.0.1:0") // Use ":0" to bind to a random free port
if err != nil {
return 0, err
}
defer l.Close()

// Get the port from the listener's address
addr := l.Addr().(*net.TCPAddr)
return addr.Port, nil
}
Loading
Loading