diff --git a/.gitignore b/.gitignore index 2d97e788..f1c181ec 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,3 @@ # Output of the go coverage tool, specifically when used with LiteIDE *.out - -# Go generate output -*.bin-runtime diff --git a/backend/sim/init.go b/backend/sim/init.go index 54567891..a52baa1a 100644 --- a/backend/sim/init.go +++ b/backend/sim/init.go @@ -17,4 +17,5 @@ package sim import ( _ "perun.network/go-perun/backend/sim/channel" // backend init _ "perun.network/go-perun/backend/sim/wallet" // backend init + _ "perun.network/go-perun/backend/sim/wire" // backend init ) diff --git a/backend/sim/wire/account.go b/backend/sim/wire/account.go new file mode 100644 index 00000000..ec5facba --- /dev/null +++ b/backend/sim/wire/account.go @@ -0,0 +1,38 @@ +// Copyright 2022 - 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 wire + +import ( + "math/rand" + + "perun.network/go-perun/wire" +) + +// Account is a wire account. +type Account struct { + addr wire.Address +} + +// Address returns the account's address. +func (acc *Account) Address() wire.Address { + return acc.addr +} + +// NewRandomAccount generates a new random account. +func NewRandomAccount(rng *rand.Rand) *Account { + return &Account{ + addr: NewRandomAddress(rng), + } +} diff --git a/backend/sim/wire/address.go b/backend/sim/wire/address.go new file mode 100644 index 00000000..5db6d7d2 --- /dev/null +++ b/backend/sim/wire/address.go @@ -0,0 +1,73 @@ +// Copyright 2022 - 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 wire + +import ( + "bytes" + "math/rand" + + "perun.network/go-perun/wire" +) + +// AddrLen is the length of an address in byte. +const AddrLen = 32 + +// Address is a wire address. +type Address [AddrLen]byte + +// NewAddress returns a new address. +func NewAddress() *Address { + return &Address{} +} + +// MarshalBinary marshals the address to binary. +func (a Address) MarshalBinary() (data []byte, err error) { + return a[:], nil +} + +// UnmarshalBinary unmarshals an address from binary. +func (a *Address) UnmarshalBinary(data []byte) error { + copy(a[:], data) + return nil +} + +// Equal returns whether the two addresses are equal. +func (a Address) Equal(b wire.Address) bool { + bTyped, ok := b.(*Address) + if !ok { + return false + } + return bytes.Equal(a[:], bTyped[:]) +} + +// Cmp compares the byte representation of two addresses. For `a.Cmp(b)` +// returns -1 if a < b, 0 if a == b, 1 if a > b. +func (a Address) Cmp(b wire.Address) int { + bTyped, ok := b.(*Address) + if !ok { + panic("wrong type") + } + return bytes.Compare(a[:], bTyped[:]) +} + +// NewRandomAddress returns a new random peer address. +func NewRandomAddress(rng *rand.Rand) *Address { + addr := Address{} + _, err := rng.Read(addr[:]) + if err != nil { + panic(err) + } + return &addr +} diff --git a/backend/sim/wire/address_test.go b/backend/sim/wire/address_test.go new file mode 100644 index 00000000..28de9054 --- /dev/null +++ b/backend/sim/wire/address_test.go @@ -0,0 +1,32 @@ +// Copyright 2022 - 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 wire_test + +import ( + "math/rand" + "testing" + + simwire "perun.network/go-perun/backend/sim/wire" + "perun.network/go-perun/wire" + "perun.network/go-perun/wire/test" +) + +func TestAddress(t *testing.T) { + test.TestAddressImplementation(t, func() wire.Address { + return simwire.NewAddress() + }, func(rng *rand.Rand) wire.Address { + return simwire.NewRandomAddress(rng) + }) +} diff --git a/backend/sim/wire/doc.go b/backend/sim/wire/doc.go new file mode 100644 index 00000000..fe538651 --- /dev/null +++ b/backend/sim/wire/doc.go @@ -0,0 +1,16 @@ +// 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 wire contains the implementation of the wire interfaces. +package wire // import "perun.network/go-perun/backend/sim/wire" diff --git a/backend/sim/wire/init.go b/backend/sim/wire/init.go new file mode 100644 index 00000000..bfd54431 --- /dev/null +++ b/backend/sim/wire/init.go @@ -0,0 +1,34 @@ +// Copyright 2022 - 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 wire + +import ( + "math/rand" + + "perun.network/go-perun/wire" + "perun.network/go-perun/wire/test" +) + +func init() { + wire.SetNewAddressFunc(func() wire.Address { + return NewAddress() + }) + test.SetNewRandomAddress(func(rng *rand.Rand) wire.Address { + return NewRandomAddress(rng) + }) + test.SetNewRandomAccount(func(rng *rand.Rand) wire.Account { + return NewRandomAccount(rng) + }) +} diff --git a/channel/persistence/keyvalue/persistrestorer_internal_test.go b/channel/persistence/keyvalue/persistrestorer_internal_test.go index 478924f5..bafd808c 100644 --- a/channel/persistence/keyvalue/persistrestorer_internal_test.go +++ b/channel/persistence/keyvalue/persistrestorer_internal_test.go @@ -22,7 +22,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - _ "perun.network/go-perun/backend/sim" + _ "perun.network/go-perun/backend/sim" // backend init "perun.network/go-perun/channel/persistence/test" "polycry.pt/poly-go/sortedkv" "polycry.pt/poly-go/sortedkv/leveldb" diff --git a/channel/persistence/keyvalue/restorer.go b/channel/persistence/keyvalue/restorer.go index 1319fda8..6dfea22c 100644 --- a/channel/persistence/keyvalue/restorer.go +++ b/channel/persistence/keyvalue/restorer.go @@ -17,7 +17,6 @@ package keyvalue import ( "bytes" "context" - "io" "strings" "github.com/pkg/errors" @@ -45,14 +44,14 @@ type ChannelIterator struct { func (pr *PersistRestorer) ActivePeers(ctx context.Context) ([]wire.Address, error) { it := sortedkv.NewTable(pr.db, prefix.PeerDB).NewIterator() - peermap := make(map[wallet.AddrKey]wire.Address) + peermap := make(map[wire.AddrKey]wire.Address) for it.Next() { addr := wire.NewAddress() err := perunio.Decode(bytes.NewBufferString(it.Key()), addr) if err != nil { return nil, errors.WithMessagef(err, "decoding peer key (%x)", it.Key()) } - peermap[wallet.Key(addr)] = addr + peermap[wire.Key(addr)] = addr } peers := make([]wire.Address, 0, len(peermap)) @@ -133,38 +132,6 @@ func (pr *PersistRestorer) RestoreChannel(ctx context.Context, id channel.ID) (* return nil, errors.Errorf("could not find channel %x", id) } -// decodePeerChanID decodes the channel.ID and peer.Address from a key. -//nolint:deadcode,unused -func decodePeerChanID(key string) (wire.Address, channel.ID, error) { - buf := bytes.NewBufferString(key) - addr := wire.NewAddress() - err := perunio.Decode(buf, addr) - if err != nil { - return addr, channel.ID{}, errors.WithMessage(err, "decode peer address") - } - - if err = eatExpect(buf, ":channel:"); err != nil { - return nil, channel.ID{}, errors.WithMessagef(err, "key: %x", key) - } - - var id channel.ID - return addr, id, errors.WithMessage(perunio.Decode(buf, &id), "decode channel id") -} - -// eatExpect consumes bytes from a Reader and asserts that they are equal to -// the expected string. -//nolint:unused -func eatExpect(r io.Reader, tok string) error { - buf := make([]byte, len(tok)) - if _, err := io.ReadFull(r, buf); err != nil { - return errors.WithMessage(err, "reading") - } - if string(buf) != tok { - return errors.Errorf("expected %s, got %s", tok, string(buf)) - } - return nil -} - type decOpts uint8 const ( diff --git a/channel/persistence/test/persistrestorertest.go b/channel/persistence/test/persistrestorertest.go index 97c2f2ef..bc555293 100644 --- a/channel/persistence/test/persistrestorertest.go +++ b/channel/persistence/test/persistrestorertest.go @@ -25,8 +25,8 @@ import ( "perun.network/go-perun/channel" "perun.network/go-perun/channel/persistence" "perun.network/go-perun/log" - wtest "perun.network/go-perun/wallet/test" "perun.network/go-perun/wire" + "perun.network/go-perun/wire/test" pkgtest "polycry.pt/poly-go/test" ) @@ -46,7 +46,7 @@ const channelNumPeers = 2 func NewClient(ctx context.Context, t *testing.T, rng *rand.Rand, pr persistence.PersistRestorer) *Client { t.Helper() return &Client{ - addr: wtest.NewRandomAddress(rng), + addr: test.NewRandomAddress(rng), rng: rng, pr: pr, ctx: ctx, @@ -94,7 +94,7 @@ func GenericPersistRestorerTest( ct := pkgtest.NewConcurrent(t) c := NewClient(ctx, t, rng, pr) - peers := wtest.NewRandomAddresses(rng, numPeers) + peers := test.NewRandomAddresses(rng, numPeers) channels := make([]map[channel.ID]*Channel, numPeers) var prevCh *Channel diff --git a/client/client_internal_test.go b/client/client_internal_test.go index a38ef04a..fee1f27a 100644 --- a/client/client_internal_test.go +++ b/client/client_internal_test.go @@ -20,7 +20,7 @@ import ( "github.com/stretchr/testify/assert" channeltest "perun.network/go-perun/channel/test" - wallettest "perun.network/go-perun/wallet/test" + wiretest "perun.network/go-perun/wire/test" "polycry.pt/poly-go/test" ) @@ -28,7 +28,7 @@ func TestClient_Channel(t *testing.T) { rng := test.Prng(t) // dummy client that only has an id and a registry c := &Client{ - address: wallettest.NewRandomAddress(rng), + address: wiretest.NewRandomAddress(rng), channels: makeChanRegistry(), } diff --git a/client/client_role_test.go b/client/client_role_test.go index 1a603533..09f128fc 100644 --- a/client/client_role_test.go +++ b/client/client_role_test.go @@ -27,6 +27,7 @@ import ( chtest "perun.network/go-perun/channel/test" "perun.network/go-perun/client" ctest "perun.network/go-perun/client/test" + "perun.network/go-perun/wallet" wtest "perun.network/go-perun/wallet/test" "perun.network/go-perun/watcher/local" "perun.network/go-perun/wire" @@ -54,7 +55,7 @@ func NewSetups(rng *rand.Rand, names []string) []ctest.RoleSetup { } setup[i] = ctest.RoleSetup{ Name: names[i], - Identity: wtest.NewRandomAccount(rng), + Identity: wiretest.NewRandomAccount(rng), Bus: bus, Funder: backend, Adjudicator: backend, @@ -73,18 +74,20 @@ func NewSetups(rng *rand.Rand, names []string) []ctest.RoleSetup { type Client struct { *client.Client ctest.RoleSetup + WalletAddress wallet.Address } func NewClients(t *testing.T, rng *rand.Rand, setups []ctest.RoleSetup) []*Client { t.Helper() clients := make([]*Client, len(setups)) for i, setup := range setups { - setup.Identity = setup.Wallet.NewRandomAccount(rng) + setup.Identity = wiretest.NewRandomAccount(rng) cl, err := client.New(setup.Identity.Address(), setup.Bus, setup.Funder, setup.Adjudicator, setup.Wallet, setup.Watcher) assert.NoError(t, err) clients[i] = &Client{ - Client: cl, - RoleSetup: setup, + Client: cl, + RoleSetup: setup, + WalletAddress: setup.Wallet.NewRandomAccount(rng).Address(), } } return clients diff --git a/client/client_test.go b/client/client_test.go index 87ab9358..4694ba82 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -28,6 +28,7 @@ import ( wtest "perun.network/go-perun/wallet/test" "perun.network/go-perun/watcher/local" "perun.network/go-perun/wire" + wiretest "perun.network/go-perun/wire/test" "polycry.pt/poly-go/test" ) @@ -46,7 +47,7 @@ func (d DummyBus) SubscribeClient(wire.Consumer, wire.Address) error { func TestClient_New_NilArgs(t *testing.T) { rng := test.Prng(t) - id := wtest.NewRandomAddress(rng) + id := wiretest.NewRandomAddress(rng) backend := &ctest.MockBackend{} b, f, a, w := &DummyBus{t}, backend, backend, wtest.RandomWallet() watcher, err := local.NewWatcher(backend) @@ -64,7 +65,7 @@ func TestClient_Handle_NilArgs(t *testing.T) { backend := &ctest.MockBackend{} watcher, err := local.NewWatcher(backend) require.NoError(t, err, "initializing the watcher should not error") - c, err := client.New(wtest.NewRandomAddress(rng), + c, err := client.New(wiretest.NewRandomAddress(rng), &DummyBus{t}, backend, backend, wtest.RandomWallet(), watcher) require.NoError(t, err) @@ -79,7 +80,7 @@ func TestClient_New(t *testing.T) { backend := &ctest.MockBackend{} watcher, err := local.NewWatcher(backend) require.NoError(t, err, "initializing the watcher should not error") - c, err := client.New(wtest.NewRandomAddress(rng), + c, err := client.New(wiretest.NewRandomAddress(rng), &DummyBus{t}, backend, backend, wtest.RandomWallet(), watcher) assert.NoError(t, err) require.NotNil(t, c) diff --git a/client/failing_funding_test.go b/client/failing_funding_test.go index 7ef69991..003996b2 100644 --- a/client/failing_funding_test.go +++ b/client/failing_funding_test.go @@ -73,13 +73,14 @@ func runFredFridaTest(t *testing.T, rng *rand.Rand, setups []ctest.RoleSetup) { clients := NewClients(t, rng, setups) frida, fred := clients[fridaIdx], clients[fredIdx] - fridaAddr, fredAddr := frida.Identity.Address(), fred.Identity.Address() + fridaWireAddr, fredWireAddr := frida.Identity.Address(), fred.Identity.Address() + fridaWalletAddr, fredWalletAddr := frida.WalletAddress, fred.WalletAddress // The channel into which Fred's created ledger channel is sent into. chsFred := make(chan *client.Channel, 1) errsFred := make(chan error, 1) go fred.Handle( - ctest.AlwaysAcceptChannelHandler(ctx, fredAddr, chsFred, errsFred), + ctest.AlwaysAcceptChannelHandler(ctx, fredWalletAddr, chsFred, errsFred), ctest.AlwaysRejectUpdateHandler(ctx, errsFred), ) @@ -87,10 +88,10 @@ func runFredFridaTest(t *testing.T, rng *rand.Rand, setups []ctest.RoleSetup) { asset := chtest.NewRandomAsset(rng) initAlloc := channel.NewAllocation(2, asset) initAlloc.SetAssetBalances(asset, []*big.Int{big.NewInt(fridaInitBal), big.NewInt(fredInitBal)}) - parts := []wire.Address{fridaAddr, fredAddr} + parts := []wire.Address{fridaWireAddr, fredWireAddr} prop, err := client.NewLedgerChannelProposal( challengeDuration, - fridaAddr, + fridaWalletAddr, initAlloc, parts, ) @@ -112,9 +113,9 @@ func runFredFridaTest(t *testing.T, rng *rand.Rand, setups []ctest.RoleSetup) { require.NoError(t, chFred.Settle(ctx, false)) // Test the final balances. - fridaFinalBal := frida.BalanceReader.Balance(fridaAddr, asset) + fridaFinalBal := frida.BalanceReader.Balance(fridaWalletAddr, asset) assert.Truef(t, fridaFinalBal.Cmp(big.NewInt(fridaInitBal)) == 0, "frida: wrong final balance: got %v, expected %v", fridaFinalBal, fridaInitBal) - fredFinalBal := fred.BalanceReader.Balance(fredAddr, asset) + fredFinalBal := fred.BalanceReader.Balance(fredWalletAddr, asset) assert.Truef(t, fredFinalBal.Cmp(big.NewInt(fredInitBal)) == 0, "fred: wrong final balance: got %v, expected %v", fredFinalBal, fredInitBal) } diff --git a/client/multiledger_dispute_test.go b/client/multiledger_dispute_test.go index ab301621..f8845da5 100644 --- a/client/multiledger_dispute_test.go +++ b/client/multiledger_dispute_test.go @@ -53,7 +53,7 @@ func TestMultiLedgerDispute(t *testing.T) { initAlloc.Balances = initBals prop, err := client.NewLedgerChannelProposal( challengeDuration, - alice.WireAddress, + alice.WalletAddress, initAlloc, parts, ) @@ -67,7 +67,7 @@ func TestMultiLedgerDispute(t *testing.T) { ctest.AlwaysAcceptUpdateHandler(ctx, errs), ) go bob.Handle( - ctest.AlwaysAcceptChannelHandler(ctx, bob.WireAddress, channels, errs), + ctest.AlwaysAcceptChannelHandler(ctx, bob.WalletAddress, channels, errs), ctest.AlwaysAcceptUpdateHandler(ctx, errs), ) @@ -117,6 +117,6 @@ func TestMultiLedgerDispute(t *testing.T) { require.NoError(err) // Check final balances. - require.True(mlt.L1.Balance(mlt.C2.WireAddress, mlt.A1).Cmp(updateBals1[0][1]) == 0) - require.True(mlt.L2.Balance(mlt.C2.WireAddress, mlt.A2).Cmp(updateBals1[1][1]) == 0) + require.True(mlt.L1.Balance(mlt.C2.WalletAddress, mlt.A1).Cmp(updateBals1[0][1]) == 0) + require.True(mlt.L2.Balance(mlt.C2.WalletAddress, mlt.A2).Cmp(updateBals1[1][1]) == 0) } diff --git a/client/multiledger_happy_test.go b/client/multiledger_happy_test.go index 6e0737ce..e3af5b54 100644 --- a/client/multiledger_happy_test.go +++ b/client/multiledger_happy_test.go @@ -56,7 +56,7 @@ func TestMultiLedgerHappy(t *testing.T) { initAlloc.Balances = initBals prop, err := client.NewLedgerChannelProposal( challengeDuration, - alice.WireAddress, + alice.WalletAddress, initAlloc, parts, ) @@ -70,7 +70,7 @@ func TestMultiLedgerHappy(t *testing.T) { ctest.AlwaysAcceptUpdateHandler(ctx, errs), ) go bob.Handle( - ctest.AlwaysAcceptChannelHandler(ctx, bob.WireAddress, channels, errs), + ctest.AlwaysAcceptChannelHandler(ctx, bob.WalletAddress, channels, errs), ctest.AlwaysAcceptUpdateHandler(ctx, errs), ) diff --git a/client/proposal.go b/client/proposal.go index ad147fc3..4b94fdb9 100644 --- a/client/proposal.go +++ b/client/proposal.go @@ -387,7 +387,7 @@ func (c *Client) proposeTwoPartyChannel( func (c *Client) validTwoPartyProposal( proposal ChannelProposal, ourIdx channel.Index, - peerAddr wallet.Address, + peerAddr wire.Address, ) error { if err := proposal.Valid(); err != nil { return err diff --git a/client/proposal_internal_test.go b/client/proposal_internal_test.go index 82159d7e..981ea8f8 100644 --- a/client/proposal_internal_test.go +++ b/client/proposal_internal_test.go @@ -24,7 +24,6 @@ import ( "perun.network/go-perun/channel" channeltest "perun.network/go-perun/channel/test" - "perun.network/go-perun/wallet" wallettest "perun.network/go-perun/wallet/test" "perun.network/go-perun/wire" wiretest "perun.network/go-perun/wire/test" @@ -36,7 +35,7 @@ func TestClient_validTwoPartyProposal(t *testing.T) { // dummy client that only has an id c := &Client{ - address: wallettest.NewRandomAddress(rng), + address: wiretest.NewRandomAddress(rng), } validProp := NewRandomLedgerChannelProposal(rng, channeltest.WithNumParts(2)) validProp.Peers[0] = c.address // set us as the proposer @@ -52,7 +51,7 @@ func TestClient_validTwoPartyProposal(t *testing.T) { tests := []struct { prop *LedgerChannelProposalMsg ourIdx channel.Index - peerAddr wallet.Address + peerAddr wire.Address valid bool }{ { diff --git a/client/test/handler.go b/client/test/handler.go index 4bb78238..b0813985 100644 --- a/client/test/handler.go +++ b/client/test/handler.go @@ -21,12 +21,12 @@ import ( "perun.network/go-perun/channel" "perun.network/go-perun/client" - "perun.network/go-perun/wire" + "perun.network/go-perun/wallet" ) // AlwaysAcceptChannelHandler returns a channel proposal handler that accepts // all channel proposals. -func AlwaysAcceptChannelHandler(ctx context.Context, addr wire.Address, channels chan *client.Channel, errs chan<- error) client.ProposalHandlerFunc { +func AlwaysAcceptChannelHandler(ctx context.Context, addr wallet.Address, channels chan *client.Channel, errs chan<- error) client.ProposalHandlerFunc { return func(cp client.ChannelProposal, pr *client.ProposalResponder) { switch cp := cp.(type) { case *client.LedgerChannelProposalMsg: diff --git a/client/test/multiledger.go b/client/test/multiledger.go index 7dfee3a9..01b94c0a 100644 --- a/client/test/multiledger.go +++ b/client/test/multiledger.go @@ -26,10 +26,12 @@ import ( chtest "perun.network/go-perun/channel/test" "perun.network/go-perun/client" "perun.network/go-perun/log" + "perun.network/go-perun/wallet" wtest "perun.network/go-perun/wallet/test" "perun.network/go-perun/watcher/local" "perun.network/go-perun/wire" "perun.network/go-perun/wire/perunio" + wiretest "perun.network/go-perun/wire/test" "polycry.pt/poly-go/test" ) @@ -118,8 +120,9 @@ func (a *MultiLedgerAsset) UnmarshalBinary(data []byte) error { type testClient struct { *client.Client - WireAddress wire.Address - Events chan channel.AdjudicatorEvent + WireAddress wire.Address + WalletAddress wallet.Address + Events chan channel.AdjudicatorEvent } func (c testClient) HandleAdjudicatorEvent(e channel.AdjudicatorEvent) { @@ -134,6 +137,9 @@ func setupClient( t.Helper() require := require.New(t) + // Setup identity. + wireAddr := wiretest.NewRandomAddress(rng) + // Setup wallet and account. w := wtest.NewWallet() acc := w.NewRandomAccount(rng) @@ -153,7 +159,7 @@ func setupClient( require.NoError(err) c, err := client.New( - acc.Address(), + wireAddr, bus, funder, adj, @@ -163,8 +169,9 @@ func setupClient( require.NoError(err) return testClient{ - Client: c, - WireAddress: acc.Address(), - Events: make(chan channel.AdjudicatorEvent), + Client: c, + WireAddress: wireAddr, + WalletAddress: acc.Address(), + Events: make(chan channel.AdjudicatorEvent), } } diff --git a/client/virtual_channel_test.go b/client/virtual_channel_test.go index 8beb56fc..d069239c 100644 --- a/client/virtual_channel_test.go +++ b/client/virtual_channel_test.go @@ -105,11 +105,11 @@ func (vct *virtualChannelTest) testFinalBalancesDispute(t *testing.T) { t.Helper() assert := assert.New(t) backend, asset := vct.balanceReader, vct.asset - got, expected := backend.Balance(vct.alice.Identity.Address(), asset), vct.finalBalsAlice[0] + got, expected := backend.Balance(vct.alice.WalletAddress, asset), vct.finalBalsAlice[0] assert.Truef(got.Cmp(expected) == 0, "alice: wrong final balance: got %v, expected %v", got, expected) - got, expected = backend.Balance(vct.bob.Identity.Address(), asset), vct.finalBalsBob[0] + got, expected = backend.Balance(vct.bob.WalletAddress, asset), vct.finalBalsBob[0] assert.Truef(got.Cmp(expected) == 0, "bob: wrong final balance: got %v, expected %v", got, expected) - got, expected = backend.Balance(vct.ingrid.Identity.Address(), asset), vct.finalBalIngrid + got, expected = backend.Balance(vct.ingrid.WalletAddress, asset), vct.finalBalIngrid assert.Truef(got.Cmp(expected) == 0, "ingrid: wrong final balance: got %v, expected %v", got, expected) } @@ -160,7 +160,7 @@ func setupVirtualChannelTest(t *testing.T, ctx context.Context) (vct virtualChan var openingProposalHandlerIngrid client.ProposalHandlerFunc = func(cp client.ChannelProposal, pr *client.ProposalResponder) { switch cp := cp.(type) { case *client.LedgerChannelProposalMsg: - ch, err := pr.Accept(ctx, cp.Accept(ingrid.Identity.Address(), client.WithRandomNonce())) + ch, err := pr.Accept(ctx, cp.Accept(ingrid.WalletAddress, client.WithRandomNonce())) if err != nil { vct.errs <- errors.WithMessage(err, "accepting ledger channel proposal") } @@ -181,7 +181,7 @@ func setupVirtualChannelTest(t *testing.T, ctx context.Context) (vct virtualChan initAllocAlice.SetAssetBalances(asset, initBalsAlice) lcpAlice, err := client.NewLedgerChannelProposal( challengeDuration, - alice.Identity.Address(), + alice.WalletAddress, initAllocAlice, peersAlice, ) @@ -201,7 +201,7 @@ func setupVirtualChannelTest(t *testing.T, ctx context.Context) (vct virtualChan initAllocBob.SetAssetBalances(asset, initBalsBob) lcpBob, err := client.NewLedgerChannelProposal( challengeDuration, - bob.Identity.Address(), + bob.WalletAddress, initAllocBob, peersBob, ) @@ -222,7 +222,7 @@ func setupVirtualChannelTest(t *testing.T, ctx context.Context) (vct virtualChan ) { switch cp := cp.(type) { case *client.VirtualChannelProposalMsg: - ch, err := pr.Accept(ctx, cp.Accept(bob.Identity.Address())) + ch, err := pr.Accept(ctx, cp.Accept(bob.WalletAddress)) if err != nil { vct.errs <- errors.WithMessage(err, "accepting virtual channel proposal") } @@ -250,7 +250,7 @@ func setupVirtualChannelTest(t *testing.T, ctx context.Context) (vct virtualChan indexMapBob := []channel.Index{1, 0} vcp, err := client.NewVirtualChannelProposal( challengeDuration, - alice.Identity.Address(), + alice.WalletAddress, &initAllocVirtual, []wire.Address{alice.Identity.Address(), bob.Identity.Address()}, []channel.ID{vct.chAliceIngrid.ID(), vct.chBobIngrid.ID()}, diff --git a/wallet/address.go b/wallet/address.go index 122d1511..56e5ca55 100644 --- a/wallet/address.go +++ b/wallet/address.go @@ -42,9 +42,6 @@ type Address interface { // Equal returns wether the two addresses are equal. The implementation // must be equivalent to checking `Address.Cmp(Address) == 0`. Equal(Address) bool - // Cmp compares the byte representation of two addresses. For `a.Cmp(b)` - // returns -1 if a < b, 0 if a == b, 1 if a > b. - Cmp(Address) int } // IndexOfAddr returns the index of the given address in the address slice, diff --git a/wallet/test/address.go b/wallet/test/address.go index cb14faaa..99b9efde 100644 --- a/wallet/test/address.go +++ b/wallet/test/address.go @@ -42,11 +42,6 @@ func TestAddress(t *testing.T, s *Setup) { //nolint:revive // `test.Test...` stu assert.False(t, addr.Equal(null), "Expected inequality of zero, nonzero address") assert.True(t, null.Equal(null), "Expected equality of zero address to itself") //nolint:gocritic - // Test Address.Cmp. - assert.Positive(t, addr.Cmp(null), "Expected addr > zero") - assert.Zero(t, null.Cmp(null), "Expected zero = zero") //nolint:gocritic - assert.Negative(t, null.Cmp(addr), "Expected null < addr") - // Test Address.Bytes. addrBytes, err := addr.MarshalBinary() assert.NoError(t, err, "Marshaling address should not error") diff --git a/wire/account.go b/wire/account.go index ae9f694e..19547617 100644 --- a/wire/account.go +++ b/wire/account.go @@ -16,8 +16,6 @@ package wire import ( "io" - - "perun.network/go-perun/wallet" ) func init() { @@ -29,9 +27,11 @@ func init() { } // Account is a node's permanent Perun identity, which is used to establish -// authenticity within the Perun peer-to-peer network. For now, it is just a -// stub. -type Account = wallet.Account +// authenticity within the Perun peer-to-peer network. +type Account interface { + // Address used by this account. + Address() Address +} var _ Msg = (*AuthResponseMsg)(nil) diff --git a/wire/address.go b/wire/address.go index ae28dcbf..890436d0 100644 --- a/wire/address.go +++ b/wire/address.go @@ -15,9 +15,11 @@ package wire import ( + "encoding" stdio "io" + "strings" - "perun.network/go-perun/wallet" + "github.com/pkg/errors" "perun.network/go-perun/wire/perunio" ) @@ -30,7 +32,15 @@ var ( // identity within the Perun peer-to-peer network. For now, it is based on type // wallet.Address. type Address interface { - wallet.Address + // BinaryMarshaler marshals the address to binary. + encoding.BinaryMarshaler + // BinaryUnmarshaler unmarshals an address from binary. + encoding.BinaryUnmarshaler + // Equal returns wether the two addresses are equal. + Equal(Address) bool + // Cmp compares the byte representation of two addresses. For `a.Cmp(b)` + // returns -1 if a < b, 0 if a == b, 1 if a > b. + Cmp(Address) int } // Addresses is a helper type for encoding and decoding address slices in @@ -41,54 +51,47 @@ type Addresses []Address // of unknown length. type AddressesWithLen []Address -// NewAddress returns a variable of type Address, which can be used -// for unmarshalling an address from its binary representation. -func NewAddress() Address { - return wallet.NewAddress() -} +type addressSliceLen = uint16 // Encode encodes wire addresses. func (a Addresses) Encode(w stdio.Writer) error { - return wallet.Addresses(asWalletAddresses(a)).Encode(w) + for i, addr := range a { + if err := perunio.Encode(w, addr); err != nil { + return errors.WithMessagef(err, "encoding %d-th address", i) + } + } + + return nil } // Encode encodes wire addresses with length. func (a AddressesWithLen) Encode(w stdio.Writer) error { - return wallet.AddressesWithLen(asWalletAddresses(a)).Encode(w) -} - -// asWalletAddresses converts wire addresses to wallet addresses. -func asWalletAddresses(a []Address) []wallet.Address { - b := make([]wallet.Address, len(a)) - for i, x := range a { - b[i] = x - } - return b + return perunio.Encode(w, + addressSliceLen(len(a)), + (Addresses)(a)) } // Decode decodes wallet addresses. func (a Addresses) Decode(r stdio.Reader) error { - b := wallet.Addresses(make([]wallet.Address, len(a))) - if err := b.Decode(r); err != nil { - return err - } - for i, x := range b { - a[i] = x + for i := range a { + a[i] = NewAddress() + err := perunio.Decode(r, a[i]) + if err != nil { + return errors.WithMessagef(err, "decoding %d-th address", i) + } } return nil } // Decode decodes a wallet address slice of unknown length. func (a *AddressesWithLen) Decode(r stdio.Reader) error { - var b wallet.AddressesWithLen - if err := b.Decode(r); err != nil { - return err - } - *a = make(AddressesWithLen, len(b)) - for i, x := range b { - (*a)[i] = x + var n addressSliceLen + if err := perunio.Decode(r, &n); err != nil { + return errors.WithMessage(err, "decoding count") } - return nil + + *a = make(AddressesWithLen, n) + return (*Addresses)(a).Decode(r) } // IndexOfAddr returns the index of the given address in the address slice, @@ -102,3 +105,18 @@ func IndexOfAddr(addrs []Address, addr Address) int { return -1 } + +// AddrKey is a non-human readable representation of an `Address`. +// It can be compared and therefore used as a key in a map. +type AddrKey string + +// Key returns the `AddrKey` corresponding to the passed `Address`. +// The `Address` can be retrieved with `FromKey`. +// Panics when the `Address` can't be encoded. +func Key(a Address) AddrKey { + var buff strings.Builder + if err := perunio.Encode(&buff, a); err != nil { + panic("Could not encode address in AddrKey: " + err.Error()) + } + return AddrKey(buff.String()) +} diff --git a/wire/cache_internal_test.go b/wire/cache_internal_test.go index 4dc8fb18..8d45d6b7 100644 --- a/wire/cache_internal_test.go +++ b/wire/cache_internal_test.go @@ -15,36 +15,31 @@ package wire import ( - "math/rand" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - wtest "perun.network/go-perun/wallet/test" - "polycry.pt/poly-go/test" ) -// newRandomEnvelope - copy from wire/test for internal tests. -func newRandomEnvelope(rng *rand.Rand, m Msg) *Envelope { +func newEnvelope(m Msg) *Envelope { return &Envelope{ - Sender: wtest.NewRandomAddress(rng), - Recipient: wtest.NewRandomAddress(rng), + Sender: nil, + Recipient: nil, Msg: m, } } func TestCache(t *testing.T) { assert, require := assert.New(t), require.New(t) - rng := test.Prng(t) - c := MakeCache() require.Zero(c.Size()) - ping0 := newRandomEnvelope(rng, NewPingMsg()) - pong := newRandomEnvelope(rng, NewPongMsg()) - ping1 := newRandomEnvelope(rng, NewPingMsg()) - ping2 := newRandomEnvelope(rng, NewPingMsg()) + ping0 := newEnvelope(NewPingMsg()) + pong := newEnvelope(NewPongMsg()) + time.Sleep(1 * time.Millisecond) // Sleep to ensure unique timestamps. + ping1 := newEnvelope(NewPingMsg()) + ping2 := newEnvelope(NewPingMsg()) // we want to uniquely identify messages by their timestamp require.False(ping0.Msg.(*PingMsg).Created.Equal(ping1.Msg.(*PingMsg).Created)) diff --git a/wire/generate.go b/wire/generate.go new file mode 100644 index 00000000..ec893c47 --- /dev/null +++ b/wire/generate.go @@ -0,0 +1,30 @@ +// Copyright 2022 - 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 wire + +// NewAddressFunc is an address generator function. +type NewAddressFunc = func() Address + +var newAddress NewAddressFunc + +// SetNewAddressFunc sets the address generator function. +func SetNewAddressFunc(f NewAddressFunc) { + newAddress = f +} + +// NewAddress returns a new address. +func NewAddress() Address { + return newAddress() +} diff --git a/wire/init_test.go b/wire/init_test.go new file mode 100644 index 00000000..a257315b --- /dev/null +++ b/wire/init_test.go @@ -0,0 +1,19 @@ +// Copyright 2022 - 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 wire_test + +import ( + _ "perun.network/go-perun/backend/sim/wire" // backend init +) diff --git a/wire/localbus.go b/wire/localbus.go index a4144d21..499c24c4 100644 --- a/wire/localbus.go +++ b/wire/localbus.go @@ -21,7 +21,6 @@ import ( "github.com/pkg/errors" "perun.network/go-perun/log" - "perun.network/go-perun/wallet" ) type localBusReceiver struct { @@ -34,13 +33,13 @@ var _ Bus = (*LocalBus)(nil) // LocalBus is a bus that only sends message in the same process. type LocalBus struct { mutex sync.RWMutex - recvs map[wallet.AddrKey]*localBusReceiver + recvs map[AddrKey]*localBusReceiver } // NewLocalBus creates a new local bus, which only targets receivers that lie // within the same process. func NewLocalBus() *LocalBus { - return &LocalBus{recvs: make(map[wallet.AddrKey]*localBusReceiver)} + return &LocalBus{recvs: make(map[AddrKey]*localBusReceiver)} } // Publish implements wire.Bus.Publish. It returns only once the recipient @@ -67,7 +66,7 @@ func (h *LocalBus) SubscribeClient(c Consumer, receiver Address) error { c.OnCloseAlways(func() { h.mutex.Lock() defer h.mutex.Unlock() - delete(h.recvs, wallet.Key(receiver)) + delete(h.recvs, Key(receiver)) log.WithField("id", receiver).Debug("Client unsubscribed.") }) @@ -79,7 +78,7 @@ func (h *LocalBus) SubscribeClient(c Consumer, receiver Address) error { // bus' receiver map, and returns it. If it creates a new receiver, it is only // a placeholder until a subscription appears. func (h *LocalBus) ensureRecv(a Address) *localBusReceiver { - key := wallet.Key(a) + key := Key(a) // First, we only use a read lock, hoping that the receiver already exists. h.mutex.RLock() recv, ok := h.recvs[key] diff --git a/wire/net/bus.go b/wire/net/bus.go index 6d89b1ac..90161aad 100644 --- a/wire/net/bus.go +++ b/wire/net/bus.go @@ -22,7 +22,6 @@ import ( "github.com/pkg/errors" "perun.network/go-perun/log" - "perun.network/go-perun/wallet" "perun.network/go-perun/wire" ) @@ -30,7 +29,7 @@ import ( type Bus struct { reg *EndpointRegistry mainRecv *wire.Receiver - recvs map[wallet.AddrKey]wire.Consumer + recvs map[wire.AddrKey]wire.Consumer mutex sync.RWMutex // Protects reg, recv. } @@ -48,7 +47,7 @@ const ( func NewBus(id wire.Account, d Dialer, s wire.EnvelopeSerializer) *Bus { b := &Bus{ mainRecv: wire.NewReceiver(), - recvs: make(map[wallet.AddrKey]wire.Consumer), + recvs: make(map[wire.AddrKey]wire.Consumer), } onNewEndpoint := func(wire.Address) wire.Consumer { return b.mainRecv } @@ -119,11 +118,11 @@ func (b *Bus) addSubscriber(c wire.Consumer, addr wire.Address) { b.mutex.Lock() defer b.mutex.Unlock() - if _, ok := b.recvs[wallet.Key(addr)]; ok { + if _, ok := b.recvs[wire.Key(addr)]; ok { log.Panic("duplicate SubscribeClient") } - b.recvs[wallet.Key(addr)] = c + b.recvs[wire.Key(addr)] = c } // ctx returns the context of the bus' registry. @@ -141,7 +140,7 @@ func (b *Bus) dispatchMsgs() { } b.mutex.Lock() - r, ok := b.recvs[wallet.Key(e.Recipient)] + r, ok := b.recvs[wire.Key(e.Recipient)] b.mutex.Unlock() if !ok { log.WithField("sender", e.Sender). @@ -157,9 +156,9 @@ func (b *Bus) removeSubscriber(addr wire.Address) { b.mutex.Lock() defer b.mutex.Unlock() - if _, ok := b.recvs[wallet.Key(addr)]; !ok { + if _, ok := b.recvs[wire.Key(addr)]; !ok { log.Panic("deleting nonexisting subscriber") } - delete(b.recvs, wallet.Key(addr)) + delete(b.recvs, wire.Key(addr)) } diff --git a/wire/net/endpoint.go b/wire/net/endpoint.go index 485f7925..5b0b5d8b 100644 --- a/wire/net/endpoint.go +++ b/wire/net/endpoint.go @@ -16,6 +16,7 @@ package net import ( "context" + "fmt" "io" "github.com/pkg/errors" @@ -104,5 +105,5 @@ func newEndpoint(addr wire.Address, conn Conn) *Endpoint { // String returns the Endpoint's address string. func (p *Endpoint) String() string { - return p.Address.String() + return fmt.Sprint(p.Address) } diff --git a/wire/net/endpoint_internal_test.go b/wire/net/endpoint_internal_test.go index f5d3b81a..d1ca3f69 100644 --- a/wire/net/endpoint_internal_test.go +++ b/wire/net/endpoint_internal_test.go @@ -25,7 +25,6 @@ import ( "github.com/stretchr/testify/assert" _ "perun.network/go-perun/backend/sim" // backend init - wallettest "perun.network/go-perun/wallet/test" "perun.network/go-perun/wire" perunio "perun.network/go-perun/wire/perunio/serializer" wiretest "perun.network/go-perun/wire/test" @@ -98,12 +97,12 @@ type client struct { // makeClient creates a simulated test client. func makeClient(conn Conn, rng *rand.Rand, dialer Dialer) *client { receiver := wire.NewReceiver() - registry := NewEndpointRegistry(wallettest.NewRandomAccount(rng), func(wire.Address) wire.Consumer { + registry := NewEndpointRegistry(wiretest.NewRandomAccount(rng), func(wire.Address) wire.Consumer { return receiver }, dialer, perunio.Serializer()) return &client{ - endpoint: registry.addEndpoint(wallettest.NewRandomAddress(rng), conn, true), + endpoint: registry.addEndpoint(wiretest.NewRandomAddress(rng), conn, true), Registry: registry, Receiver: receiver, } @@ -202,7 +201,7 @@ func TestEndpoint_ClosedByRecvLoopOnConnClose(t *testing.T) { eofReceived := make(chan struct{}) rng := test.Prng(t) - addr := wallettest.NewRandomAddress(rng) + addr := wiretest.NewRandomAddress(rng) conn0, conn1 := newPipeConnPair() peer := newEndpoint(addr, conn0) diff --git a/wire/net/endpoint_registry.go b/wire/net/endpoint_registry.go index 9d9a75ba..149edf1b 100644 --- a/wire/net/endpoint_registry.go +++ b/wire/net/endpoint_registry.go @@ -24,7 +24,6 @@ import ( "github.com/pkg/errors" "perun.network/go-perun/log" - "perun.network/go-perun/wallet" "perun.network/go-perun/wire" perunsync "polycry.pt/poly-go/sync" ) @@ -69,8 +68,8 @@ type EndpointRegistry struct { onNewEndpoint func(wire.Address) wire.Consumer // Selects Consumer for new Endpoints' receive loop. ser wire.EnvelopeSerializer - endpoints map[wallet.AddrKey]*fullEndpoint // The list of all of all established Endpoints. - dialing map[wallet.AddrKey]*dialingEndpoint + endpoints map[wire.AddrKey]*fullEndpoint // The list of all of all established Endpoints. + dialing map[wire.AddrKey]*dialingEndpoint mutex sync.RWMutex // protects peers and dialing. log.Embedding @@ -94,8 +93,8 @@ func NewEndpointRegistry( dialer: dialer, ser: ser, - endpoints: make(map[wallet.AddrKey]*fullEndpoint), - dialing: make(map[wallet.AddrKey]*dialingEndpoint), + endpoints: make(map[wire.AddrKey]*fullEndpoint), + dialing: make(map[wire.AddrKey]*dialingEndpoint), Embedding: log.MakeEmbedding(log.WithField("id", id.Address())), } @@ -190,7 +189,7 @@ func (r *EndpointRegistry) setupConn(conn Conn) error { // context is closed. func (r *EndpointRegistry) Endpoint(ctx context.Context, addr wire.Address) (*Endpoint, error) { log := r.Log().WithField("peer", addr) - key := wallet.Key(addr) + key := wire.Key(addr) if addr.Equal(r.id.Address()) { log.Panic("tried to dial self") @@ -222,7 +221,7 @@ func (r *EndpointRegistry) authenticatedDial( de *dialingEndpoint, created bool, ) (ret *Endpoint, _ error) { - key := wallet.Key(addr) + key := wire.Key(addr) // Short cut: another dial for that peer is already in progress. if !created { @@ -262,8 +261,8 @@ func (r *EndpointRegistry) authenticatedDial( } // dialingEndpoint retrieves or creates a dialingEndpoint for the passed address. -func (r *EndpointRegistry) dialingEndpoint(a wallet.Address) (_ *dialingEndpoint, created bool) { - key := wallet.Key(a) +func (r *EndpointRegistry) dialingEndpoint(a wire.Address) (_ *dialingEndpoint, created bool) { + key := wire.Key(a) entry, ok := r.dialing[key] if !ok { entry = newDialingEndpoint(a) @@ -288,7 +287,7 @@ func (r *EndpointRegistry) Has(addr wire.Address) bool { r.mutex.Lock() defer r.mutex.Unlock() - _, ok := r.endpoints[wallet.Key(addr)] + _, ok := r.endpoints[wire.Key(addr)] return ok } @@ -319,7 +318,7 @@ func (r *EndpointRegistry) addEndpoint(addr wire.Address, conn Conn, dialer bool // fullEndpoint retrieves or creates a fullEndpoint for the passed address. func (r *EndpointRegistry) fullEndpoint(addr wire.Address, e *Endpoint) (_ *fullEndpoint, created bool) { - key := wallet.Key(addr) + key := wire.Key(addr) r.mutex.Lock() defer r.mutex.Unlock() entry, ok := r.endpoints[key] @@ -373,7 +372,7 @@ func (p *fullEndpoint) delete(expectedOldValue *Endpoint) { func (r *EndpointRegistry) find(addr wire.Address) *Endpoint { r.mutex.RLock() defer r.mutex.RUnlock() - if e, ok := r.endpoints[wallet.Key(addr)]; ok { + if e, ok := r.endpoints[wire.Key(addr)]; ok { return e.Endpoint() } return nil diff --git a/wire/net/endpoint_registry_external_test.go b/wire/net/endpoint_registry_external_test.go index 057bc8c9..486ade7e 100644 --- a/wire/net/endpoint_registry_external_test.go +++ b/wire/net/endpoint_registry_external_test.go @@ -22,11 +22,11 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - wallettest "perun.network/go-perun/wallet/test" "perun.network/go-perun/wire" "perun.network/go-perun/wire/net" nettest "perun.network/go-perun/wire/net/test" perunio "perun.network/go-perun/wire/perunio/serializer" + wiretest "perun.network/go-perun/wire/test" ctxtest "polycry.pt/poly-go/context/test" "polycry.pt/poly-go/sync" "polycry.pt/poly-go/test" @@ -42,8 +42,8 @@ func TestEndpointRegistry_Get_Pair(t *testing.T) { assert, require := assert.New(t), require.New(t) rng := test.Prng(t) var hub nettest.ConnHub - dialerID := wallettest.NewRandomAccount(rng) - listenerID := wallettest.NewRandomAccount(rng) + dialerID := wiretest.NewRandomAccount(rng) + listenerID := wiretest.NewRandomAccount(rng) dialerReg := net.NewEndpointRegistry(dialerID, nilConsumer, hub.NewNetDialer(), perunio.Serializer()) listenerReg := net.NewEndpointRegistry(listenerID, nilConsumer, nil, perunio.Serializer()) listener := hub.NewNetListener(listenerID.Address()) @@ -82,8 +82,8 @@ func TestEndpointRegistry_Get_Multiple(t *testing.T) { assert := assert.New(t) rng := test.Prng(t) var hub nettest.ConnHub - dialerID := wallettest.NewRandomAccount(rng) - listenerID := wallettest.NewRandomAccount(rng) + dialerID := wiretest.NewRandomAccount(rng) + listenerID := wiretest.NewRandomAccount(rng) dialer := hub.NewNetDialer() logPeer := func(addr wire.Address) wire.Consumer { t.Logf("subscribing %s\n", addr) diff --git a/wire/net/endpoint_registry_internal_test.go b/wire/net/endpoint_registry_internal_test.go index 4a66a032..34160e1e 100644 --- a/wire/net/endpoint_registry_internal_test.go +++ b/wire/net/endpoint_registry_internal_test.go @@ -25,8 +25,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "perun.network/go-perun/wallet" - wallettest "perun.network/go-perun/wallet/test" "perun.network/go-perun/wire" perunio "perun.network/go-perun/wire/perunio/serializer" wiretest "perun.network/go-perun/wire/test" @@ -116,8 +114,8 @@ func nilConsumer(wire.Address) wire.Consumer { return nil } func TestRegistry_Get(t *testing.T) { t.Parallel() rng := test.Prng(t) - id := wallettest.NewRandomAccount(rng) - peerID := wallettest.NewRandomAccount(rng) + id := wiretest.NewRandomAccount(rng) + peerID := wiretest.NewRandomAccount(rng) peerAddr := peerID.Address() t.Run("peer already in progress (existing)", func(t *testing.T) { @@ -127,7 +125,7 @@ func TestRegistry_Get(t *testing.T) { r := NewEndpointRegistry(id, nilConsumer, dialer, perunio.Serializer()) existing := newEndpoint(peerAddr, newMockConn()) - r.endpoints[wallet.Key(peerAddr)] = newFullEndpoint(existing) + r.endpoints[wire.Key(peerAddr)] = newFullEndpoint(existing) ctxtest.AssertTerminates(t, timeout, func() { p, err := r.Endpoint(context.Background(), peerAddr) assert.NoError(t, err) @@ -181,15 +179,15 @@ func TestRegistry_Get(t *testing.T) { func TestRegistry_authenticatedDial(t *testing.T) { t.Parallel() rng := test.Prng(t) - id := wallettest.NewRandomAccount(rng) + id := wiretest.NewRandomAccount(rng) d := &mockDialer{dial: make(chan Conn)} r := NewEndpointRegistry(id, nilConsumer, d, perunio.Serializer()) - remoteID := wallettest.NewRandomAccount(rng) + remoteID := wiretest.NewRandomAccount(rng) remoteAddr := remoteID.Address() t.Run("dial fail", func(t *testing.T) { - addr := wallettest.NewRandomAddress(rng) + addr := wiretest.NewRandomAddress(rng) de, created := r.dialingEndpoint(addr) go d.put(nil) ctx, cancel := context.WithTimeout(context.Background(), timeout) @@ -230,7 +228,7 @@ func TestRegistry_authenticatedDial(t *testing.T) { a, b := newPipeConnPair() go ct.Stage("passive", func(rt test.ConcT) { d.put(a) - _, err := ExchangeAddrsPassive(ctx, wallettest.NewRandomAccount(rng), b) + _, err := ExchangeAddrsPassive(ctx, wiretest.NewRandomAccount(rng), b) require.True(rt, IsAuthenticationError(err)) }) de, created := r.dialingEndpoint(remoteAddr) @@ -263,8 +261,8 @@ func TestRegistry_authenticatedDial(t *testing.T) { func TestRegistry_setupConn(t *testing.T) { t.Parallel() rng := test.Prng(t) - id := wallettest.NewRandomAccount(rng) - remoteID := wallettest.NewRandomAccount(rng) + id := wiretest.NewRandomAccount(rng) + remoteID := wiretest.NewRandomAccount(rng) t.Run("ExchangeAddrs fail", func(t *testing.T) { d := &mockDialer{dial: make(chan Conn)} @@ -325,9 +323,9 @@ func TestRegistry_Listen(t *testing.T) { rng := test.Prng(t) - id := wallettest.NewRandomAccount(rng) + id := wiretest.NewRandomAccount(rng) addr := id.Address() - remoteID := wallettest.NewRandomAccount(rng) + remoteID := wiretest.NewRandomAccount(rng) remoteAddr := remoteID.Address() d := newMockDialer() @@ -367,14 +365,14 @@ func TestRegistry_addEndpoint_Subscribe(t *testing.T) { rng := test.Prng(t) called := false r := NewEndpointRegistry( - wallettest.NewRandomAccount(rng), + wiretest.NewRandomAccount(rng), func(wire.Address) wire.Consumer { called = true; return nil }, nil, perunio.Serializer(), ) assert.False(t, called, "onNewEndpoint must not have been called yet") - r.addEndpoint(wallettest.NewRandomAddress(rng), newMockConn(), false) + r.addEndpoint(wiretest.NewRandomAddress(rng), newMockConn(), false) assert.True(t, called, "onNewEndpoint must have been called") } @@ -385,7 +383,7 @@ func TestRegistry_Close(t *testing.T) { t.Run("double close error", func(t *testing.T) { r := NewEndpointRegistry( - wallettest.NewRandomAccount(rng), + wiretest.NewRandomAccount(rng), nilConsumer, nil, perunio.Serializer(), @@ -398,7 +396,7 @@ func TestRegistry_Close(t *testing.T) { d := &mockDialer{dial: make(chan Conn)} d.Close() r := NewEndpointRegistry( - wallettest.NewRandomAccount(rng), + wiretest.NewRandomAccount(rng), nilConsumer, d, perunio.Serializer(), diff --git a/wire/net/exchange_addr_internal_test.go b/wire/net/exchange_addr_internal_test.go index 78995c2e..4abf6f83 100644 --- a/wire/net/exchange_addr_internal_test.go +++ b/wire/net/exchange_addr_internal_test.go @@ -21,7 +21,6 @@ import ( "github.com/stretchr/testify/assert" - wallettest "perun.network/go-perun/wallet/test" "perun.network/go-perun/wire" wiretest "perun.network/go-perun/wire/test" ctxtest "polycry.pt/poly-go/context/test" @@ -32,7 +31,7 @@ func TestExchangeAddrs_ConnFail(t *testing.T) { rng := test.Prng(t) a, _ := newPipeConnPair() a.Close() - addr, err := ExchangeAddrsPassive(context.Background(), wallettest.NewRandomAccount(rng), a) + addr, err := ExchangeAddrsPassive(context.Background(), wiretest.NewRandomAccount(rng), a) assert.Nil(t, addr) assert.Error(t, err) } @@ -41,7 +40,7 @@ func TestExchangeAddrs_Success(t *testing.T) { rng := test.Prng(t) conn0, conn1 := newPipeConnPair() defer conn0.Close() - account0, account1 := wallettest.NewRandomAccount(rng), wallettest.NewRandomAccount(rng) + account0, account1 := wiretest.NewRandomAccount(rng), wiretest.NewRandomAccount(rng) var wg sync.WaitGroup wg.Add(1) @@ -67,7 +66,7 @@ func TestExchangeAddrs_Timeout(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() ctxtest.AssertTerminates(t, 2*timeout, func() { - addr, err := ExchangeAddrsPassive(ctx, wallettest.NewRandomAccount(rng), a) + addr, err := ExchangeAddrsPassive(ctx, wiretest.NewRandomAccount(rng), a) assert.Nil(t, addr) assert.Error(t, err) }) @@ -75,7 +74,7 @@ func TestExchangeAddrs_Timeout(t *testing.T) { func TestExchangeAddrs_BogusMsg(t *testing.T) { rng := test.Prng(t) - acc := wallettest.NewRandomAccount(rng) + acc := wiretest.NewRandomAccount(rng) conn := newMockConn() conn.recvQueue <- wiretest.NewRandomEnvelope(rng, wire.NewPingMsg()) addr, err := ExchangeAddrsPassive(context.Background(), acc, conn) diff --git a/wire/net/simple/dialer.go b/wire/net/simple/dialer.go index 3f5e617b..37de0d34 100644 --- a/wire/net/simple/dialer.go +++ b/wire/net/simple/dialer.go @@ -21,7 +21,6 @@ import ( "time" "github.com/pkg/errors" - "perun.network/go-perun/wallet" "perun.network/go-perun/wire" wirenet "perun.network/go-perun/wire/net" pkgsync "polycry.pt/poly-go/sync" @@ -30,10 +29,10 @@ import ( // Dialer is a simple lookup-table based dialer that can dial known peers. // New peer addresses can be added via Register(). type Dialer struct { - mutex sync.RWMutex // Protects peers. - peers map[wallet.AddrKey]string // Known peer addresses. - dialer net.Dialer // Used to dial connections. - network string // The socket type. + mutex sync.RWMutex // Protects peers. + peers map[wire.AddrKey]string // Known peer addresses. + dialer net.Dialer // Used to dial connections. + network string // The socket type. pkgsync.Closer } @@ -47,7 +46,7 @@ var _ wirenet.Dialer = (*Dialer)(nil) // `serializer` defines the message encoding. func NewNetDialer(network string, defaultTimeout time.Duration) *Dialer { return &Dialer{ - peers: make(map[wallet.AddrKey]string), + peers: make(map[wire.AddrKey]string), dialer: net.Dialer{Timeout: defaultTimeout}, network: network, } @@ -63,7 +62,7 @@ func NewUnixDialer(defaultTimeout time.Duration) *Dialer { return NewNetDialer("unix", defaultTimeout) } -func (d *Dialer) host(key wallet.AddrKey) (string, bool) { +func (d *Dialer) host(key wire.AddrKey) (string, bool) { d.mutex.RLock() defer d.mutex.RUnlock() @@ -76,7 +75,7 @@ func (d *Dialer) Dial(ctx context.Context, addr wire.Address, ser wire.EnvelopeS done := make(chan struct{}) defer close(done) - host, ok := d.host(wallet.Key(addr)) + host, ok := d.host(wire.Key(addr)) if !ok { return nil, errors.New("peer not found") } @@ -106,5 +105,5 @@ func (d *Dialer) Register(addr wire.Address, address string) { d.mutex.Lock() defer d.mutex.Unlock() - d.peers[wallet.Key(addr)] = address + d.peers[wire.Key(addr)] = address } diff --git a/wire/net/simple/dialer_internal_test.go b/wire/net/simple/dialer_internal_test.go index bc34bf44..b5e382b3 100644 --- a/wire/net/simple/dialer_internal_test.go +++ b/wire/net/simple/dialer_internal_test.go @@ -22,10 +22,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - simwallet "perun.network/go-perun/backend/sim/wallet" - "perun.network/go-perun/wallet" "perun.network/go-perun/wire" perunio "perun.network/go-perun/wire/perunio/serializer" + wiretest "perun.network/go-perun/wire/test" ctxtest "polycry.pt/poly-go/context/test" "polycry.pt/poly-go/test" ) @@ -42,8 +41,8 @@ func TestNewUnixDialer(t *testing.T) { func TestDialer_Register(t *testing.T) { rng := test.Prng(t) - addr := simwallet.NewRandomAddress(rng) - key := wallet.Key(addr) + addr := wiretest.NewRandomAddress(rng) + key := wire.Key(addr) d := NewTCPDialer(0) _, ok := d.host(key) @@ -60,7 +59,7 @@ func TestDialer_Dial(t *testing.T) { timeout := 100 * time.Millisecond rng := test.Prng(t) lhost := "127.0.0.1:7357" - laddr := simwallet.NewRandomAddress(rng) + laddr := wiretest.NewRandomAddress(rng) l, err := NewTCPListener(lhost) require.NoError(t, err) @@ -69,7 +68,7 @@ func TestDialer_Dial(t *testing.T) { ser := perunio.Serializer() d := NewTCPDialer(timeout) d.Register(laddr, lhost) - daddr := simwallet.NewRandomAddress(rng) + daddr := wiretest.NewRandomAddress(rng) defer d.Close() t.Run("happy", func(t *testing.T) { @@ -113,7 +112,7 @@ func TestDialer_Dial(t *testing.T) { }) t.Run("unknown host", func(t *testing.T) { - noHostAddr := simwallet.NewRandomAddress(rng) + noHostAddr := wiretest.NewRandomAddress(rng) d.Register(noHostAddr, "no such host") ctxtest.AssertTerminates(t, timeout, func() { @@ -125,7 +124,7 @@ func TestDialer_Dial(t *testing.T) { t.Run("unknown address", func(t *testing.T) { ctxtest.AssertTerminates(t, timeout, func() { - unkownAddr := simwallet.NewRandomAddress(rng) + unkownAddr := wiretest.NewRandomAddress(rng) conn, err := d.Dial(context.Background(), unkownAddr, ser) assert.Error(t, err) assert.Nil(t, conn) diff --git a/wire/net/simple/init_test.go b/wire/net/simple/init_test.go new file mode 100644 index 00000000..bb13faf2 --- /dev/null +++ b/wire/net/simple/init_test.go @@ -0,0 +1,19 @@ +// Copyright 2022 - 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 simple_test + +import ( + _ "perun.network/go-perun/backend/sim/wire" // backend init +) diff --git a/wire/net/test/connhub_internal_test.go b/wire/net/test/connhub_internal_test.go index 9e3e13bc..f061c765 100644 --- a/wire/net/test/connhub_internal_test.go +++ b/wire/net/test/connhub_internal_test.go @@ -22,7 +22,6 @@ import ( "github.com/stretchr/testify/require" _ "perun.network/go-perun/backend/sim" // backend init - wallettest "perun.network/go-perun/wallet/test" "perun.network/go-perun/wire" perunio "perun.network/go-perun/wire/perunio/serializer" wiretest "perun.network/go-perun/wire/test" @@ -38,7 +37,7 @@ func TestConnHub_Create(t *testing.T) { assert := assert.New(t) var c ConnHub - addr := wallettest.NewRandomAddress(rng) + addr := wiretest.NewRandomAddress(rng) d, l := c.NewNetDialer(), c.NewNetListener(addr) assert.NotNil(d) assert.NotNil(l) @@ -71,7 +70,7 @@ func TestConnHub_Create(t *testing.T) { assert := assert.New(t) var c ConnHub - addr := wallettest.NewRandomAddress(rng) + addr := wiretest.NewRandomAddress(rng) l := c.NewNetListener(addr) assert.NotNil(l) @@ -86,7 +85,7 @@ func TestConnHub_Create(t *testing.T) { d := c.NewNetDialer() ctxtest.AssertTerminates(t, timeout, func() { - conn, err := d.Dial(context.Background(), wallettest.NewRandomAddress(rng), ser) + conn, err := d.Dial(context.Background(), wiretest.NewRandomAddress(rng), ser) assert.Nil(conn) assert.Error(err) }) @@ -97,7 +96,7 @@ func TestConnHub_Create(t *testing.T) { var c ConnHub c.Close() - addr := wallettest.NewRandomAddress(rng) + addr := wiretest.NewRandomAddress(rng) assert.Panics(func() { c.NewNetDialer() }) assert.Panics(func() { c.NewNetListener(addr) }) @@ -110,7 +109,7 @@ func TestConnHub_Close(t *testing.T) { assert := assert.New(t) var c ConnHub - l := c.NewNetListener(wallettest.NewRandomAddress(rng)) + l := c.NewNetListener(wiretest.NewRandomAddress(rng)) assert.NoError(c.Close()) assert.True(l.IsClosed()) }) @@ -119,10 +118,10 @@ func TestConnHub_Close(t *testing.T) { assert := assert.New(t) var c ConnHub - l := c.NewNetListener(wallettest.NewRandomAddress(rng)) + l := c.NewNetListener(wiretest.NewRandomAddress(rng)) l2 := NewNetListener() l2.Close() - err := c.insert(wallettest.NewRandomAccount(rng).Address(), l2) + err := c.insert(wiretest.NewRandomAccount(rng).Address(), l2) assert.NoError(err) assert.Error(c.Close()) assert.True(l.IsClosed()) diff --git a/wire/net/test/dialer_internal_test.go b/wire/net/test/dialer_internal_test.go index db8066a6..e2474891 100644 --- a/wire/net/test/dialer_internal_test.go +++ b/wire/net/test/dialer_internal_test.go @@ -20,8 +20,8 @@ import ( "github.com/stretchr/testify/assert" - "perun.network/go-perun/wallet/test" perunio "perun.network/go-perun/wire/perunio/serializer" + "perun.network/go-perun/wire/test" pkgtest "polycry.pt/poly-go/test" ) diff --git a/wire/net/test/listenermap_internal_test.go b/wire/net/test/listenermap_internal_test.go index 6024da4b..05eff932 100644 --- a/wire/net/test/listenermap_internal_test.go +++ b/wire/net/test/listenermap_internal_test.go @@ -19,7 +19,7 @@ import ( "github.com/stretchr/testify/assert" - "perun.network/go-perun/wallet/test" + "perun.network/go-perun/wire/test" pkgtest "polycry.pt/poly-go/test" ) diff --git a/wire/perunio/test/serializertest.go b/wire/perunio/test/serializertest.go index 6d7bdcfa..ac5f04d8 100644 --- a/wire/perunio/test/serializertest.go +++ b/wire/perunio/test/serializertest.go @@ -34,8 +34,8 @@ func GenericSerializerTest(t *testing.T, serializers ...perunio.Serializer) { // genericDecodeEncodeTest tests whether encoding and then decoding // serializer values results in the original values. +//nolint:thelper // The linter thinks this is a helper, but it isn't. func genericDecodeEncodeTest(t *testing.T, serializers ...perunio.Serializer) { - t.Helper() for i, v := range serializers { r, w := io.Pipe() br := iotest.OneByteReader(r) @@ -58,9 +58,10 @@ func genericDecodeEncodeTest(t *testing.T, serializers ...perunio.Serializer) { } } -// GenericBrokenPipeTest tests that encoding and decoding on broken streams fails. +// GenericBrokenPipeTest tests that encoding and decoding on broken streams +// fails. +//nolint:thelper // The linter thinks this is a helper, but it isn't. func GenericBrokenPipeTest(t *testing.T, serializers ...perunio.Serializer) { - t.Helper() for i, v := range serializers { r, w := io.Pipe() _ = w.Close() diff --git a/wire/protobuf/init_test.go b/wire/protobuf/init_test.go new file mode 100644 index 00000000..fc6fffb5 --- /dev/null +++ b/wire/protobuf/init_test.go @@ -0,0 +1,19 @@ +// Copyright 2022 - 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 protobuf_test + +import ( + _ "perun.network/go-perun/backend/sim/wire" // backend init +) diff --git a/wire/protobuf/proposalmsgs.go b/wire/protobuf/proposalmsgs.go index b71bf8a9..59974a3e 100644 --- a/wire/protobuf/proposalmsgs.go +++ b/wire/protobuf/proposalmsgs.go @@ -121,7 +121,7 @@ func toWalletAddr(protoAddr []byte) (wallet.Address, error) { func toWalletAddrs(protoAddrs [][]byte) ([]wallet.Address, error) { addrs := make([]wallet.Address, len(protoAddrs)) for i := range protoAddrs { - addrs[i] = wire.NewAddress() + addrs[i] = wallet.NewAddress() err := addrs[i].UnmarshalBinary(protoAddrs[i]) if err != nil { return nil, errors.WithMessagef(err, "%d'th address", i) diff --git a/wire/protobuf/test/serializertest.go b/wire/protobuf/test/serializertest.go index 9e4b4cf4..7488d177 100644 --- a/wire/protobuf/test/serializertest.go +++ b/wire/protobuf/test/serializertest.go @@ -21,9 +21,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - wallettest "perun.network/go-perun/wallet/test" "perun.network/go-perun/wire" "perun.network/go-perun/wire/protobuf" + "perun.network/go-perun/wire/test" pkgtest "polycry.pt/poly-go/test" ) @@ -47,7 +47,7 @@ func MsgSerializerTest(t *testing.T, msg wire.Msg) { func newEnvelope(rng *rand.Rand) *wire.Envelope { return &wire.Envelope{ - Sender: wallettest.NewRandomAddress(rng), - Recipient: wallettest.NewRandomAddress(rng), + Sender: test.NewRandomAddress(rng), + Recipient: test.NewRandomAddress(rng), } } diff --git a/wire/receiver_internal_test.go b/wire/receiver_internal_test.go index 78e381dc..acf71245 100644 --- a/wire/receiver_internal_test.go +++ b/wire/receiver_internal_test.go @@ -22,7 +22,6 @@ import ( "github.com/stretchr/testify/assert" ctxtest "polycry.pt/poly-go/context/test" - "polycry.pt/poly-go/test" ) // timeout controls how long to wait until we decide that something will never @@ -39,7 +38,7 @@ func TestReceiver_Close(t *testing.T) { func TestReceiver_Next(t *testing.T) { t.Parallel() - e := newRandomEnvelope(test.Prng(t), NewPingMsg()) + e := newEnvelope(NewPingMsg()) t.Run("Happy case", func(t *testing.T) { t.Parallel() diff --git a/wire/relay_internal_test.go b/wire/relay_internal_test.go index dfb03756..3e6fcd6a 100644 --- a/wire/relay_internal_test.go +++ b/wire/relay_internal_test.go @@ -23,10 +23,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - wallettest "perun.network/go-perun/wallet/test" ctxtest "polycry.pt/poly-go/context/test" "polycry.pt/poly-go/sync" - "polycry.pt/poly-go/test" ) func TestProducer(t *testing.T) { @@ -49,18 +47,6 @@ func TestProducer(t *testing.T) { assert.Panics(t, func() { p.delete(r0) }) } -func TestProducer_produce_closed(t *testing.T) { - var missed *Envelope - p := NewRelay() - p.SetDefaultMsgHandler(func(e *Envelope) { missed = e }) - assert.NoError(t, p.Close()) - rng := test.Prng(t) - a := wallettest.NewRandomAddress(rng) - b := wallettest.NewRandomAddress(rng) - p.Put(&Envelope{a, b, NewPingMsg()}) - assert.Nil(t, missed, "produce() on closed producer shouldn't do anything") -} - func TestProducer_SetDefaultMsgHandler(t *testing.T) { fn := func(*Envelope) {} p := NewRelay() @@ -128,10 +114,9 @@ func TestProducer_caching(t *testing.T) { ctx := context.Background() prod.Cache(&isPing) - rng := test.Prng(t) - ping0 := newRandomEnvelope(rng, NewPingMsg()) - pong1 := newRandomEnvelope(rng, NewPongMsg()) - pong2 := newRandomEnvelope(rng, NewPongMsg()) + ping0 := newEnvelope(NewPingMsg()) + pong1 := newEnvelope(NewPongMsg()) + pong2 := newEnvelope(NewPongMsg()) prod.Put(ping0) assert.Equal(1, prod.cache.Size()) diff --git a/wire/relay_test.go b/wire/relay_test.go new file mode 100644 index 00000000..5f33ff09 --- /dev/null +++ b/wire/relay_test.go @@ -0,0 +1,36 @@ +// Copyright 2022 - 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 wire_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "perun.network/go-perun/wire" + wiretest "perun.network/go-perun/wire/test" + "polycry.pt/poly-go/test" +) + +func TestProducer_produce_closed(t *testing.T) { + var missed *wire.Envelope + p := wire.NewRelay() + p.SetDefaultMsgHandler(func(e *wire.Envelope) { missed = e }) + assert.NoError(t, p.Close()) + rng := test.Prng(t) + a := wiretest.NewRandomAddress(rng) + b := wiretest.NewRandomAddress(rng) + p.Put(&wire.Envelope{a, b, wire.NewPingMsg()}) + assert.Nil(t, missed, "produce() on closed producer shouldn't do anything") +} diff --git a/wire/test/address.go b/wire/test/address.go new file mode 100644 index 00000000..ce1ac570 --- /dev/null +++ b/wire/test/address.go @@ -0,0 +1,68 @@ +// Copyright 2022 - 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 test + +import ( + "bytes" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "perun.network/go-perun/wire" + "perun.network/go-perun/wire/perunio" + pkgtest "polycry.pt/poly-go/test" +) + +// TestAddressImplementation runs a test suite designed to test the general +// functionality of an address implementation. +//nolint:revive // The function name `test.Test...` stutters, but it is OK in this special case. +func TestAddressImplementation(t *testing.T, newAddress wire.NewAddressFunc, newRandomAddress NewRandomAddressFunc) { + rng := pkgtest.Prng(t) + require, assert := require.New(t), assert.New(t) + addr := newRandomAddress(rng) + + // Test Address.MarshalBinary and UnmarshalBinary. + data, err := addr.MarshalBinary() + assert.NoError(err) + assert.NoError(addr.UnmarshalBinary(data), "Byte deserialization of address should work") + + // Test Address.Equals. + null := newAddress() + assert.False(addr.Equal(null), "Expected inequality of zero, nonzero address") + assert.True(null.Equal(null), "Expected equality of zero address to itself") //nolint:gocritic + + // Test Address.Cmp. + assert.Positive(addr.Cmp(null), "Expected addr > zero") + assert.Zero(null.Cmp(null), "Expected zero = zero") //nolint:gocritic + assert.Negative(null.Cmp(addr), "Expected null < addr") + + // Test Address.Bytes. + addrBytes, err := addr.MarshalBinary() + assert.NoError(err, "Marshaling address should not error") + nullBytes, err := null.MarshalBinary() + assert.NoError(err, "Marshaling zero address should not error") + assert.False(bytes.Equal(addrBytes, nullBytes), "Expected inequality of byte representations of nonzero and zero address") + + // a.Equal(Decode(Encode(a))) + t.Run("Serialize Equal Test", func(t *testing.T) { + buff := new(bytes.Buffer) + require.NoError(perunio.Encode(buff, addr)) + addr2 := newAddress() + err := perunio.Decode(buff, addr2) + require.NoError(err) + + assert.True(addr.Equal(addr2)) + }) +} diff --git a/wire/test/bustest.go b/wire/test/bustest.go index 6b79a73e..ab8f34cb 100644 --- a/wire/test/bustest.go +++ b/wire/test/bustest.go @@ -21,7 +21,6 @@ import ( "github.com/stretchr/testify/require" - wallettest "perun.network/go-perun/wallet/test" "perun.network/go-perun/wire" "polycry.pt/poly-go/test" ) @@ -56,7 +55,7 @@ func GenericBusTest(t *testing.T, clients := make([]Client, numClients) for i := range clients { clients[i].r = wire.NewRelay() - clients[i].id = wallettest.NewRandomAccount(rng) + clients[i].id = NewRandomAccount(rng) clients[i].pub, clients[i].sub = busAssigner(clients[i].id) } diff --git a/wire/test/msgstest.go b/wire/test/msgstest.go index db0ecd5c..814bdb7e 100644 --- a/wire/test/msgstest.go +++ b/wire/test/msgstest.go @@ -18,7 +18,6 @@ import ( "math/rand" "testing" - wallettest "perun.network/go-perun/wallet/test" "perun.network/go-perun/wire" pkgtest "polycry.pt/poly-go/test" @@ -41,7 +40,7 @@ func AuthMsgsSerializationTest(t *testing.T, serializerTest func(t *testing.T, m t.Helper() rng := pkgtest.Prng(t) - serializerTest(t, wire.NewAuthResponseMsg(wallettest.NewRandomAccount(rng))) + serializerTest(t, wire.NewAuthResponseMsg(NewRandomAccount(rng))) } // newRandomASCIIString returns a random ascii string of length between minLen and diff --git a/wire/test/randomizer.go b/wire/test/randomizer.go index 5d899929..39b3f4c8 100644 --- a/wire/test/randomizer.go +++ b/wire/test/randomizer.go @@ -17,22 +17,46 @@ package test import ( "math/rand" - "perun.network/go-perun/wallet/test" "perun.network/go-perun/wire" ) -// NewRandomAddress returns a new random peer address. Currently still a stub -// until the crypto for peer addresses is decided. +type ( + // NewRandomAddressFunc is a address randomizer function. + NewRandomAddressFunc = func(*rand.Rand) wire.Address + // NewRandomAccountFunc is a account randomizer function. + NewRandomAccountFunc = func(*rand.Rand) wire.Account +) + +var ( + newRandomAddress NewRandomAddressFunc + newRandomAccount NewRandomAccountFunc +) + +// SetNewRandomAddress sets the address randomizer function. +func SetNewRandomAddress(f NewRandomAddressFunc) { + newRandomAddress = f +} + +// SetNewRandomAccount sets the account randomizer function. +func SetNewRandomAccount(f NewRandomAccountFunc) { + newRandomAccount = f +} + +// NewRandomAddress returns a new random address. func NewRandomAddress(rng *rand.Rand) wire.Address { - return test.NewRandomAddress(rng) + return newRandomAddress(rng) +} + +// NewRandomAccount returns a new random account. +func NewRandomAccount(rng *rand.Rand) wire.Account { + return newRandomAccount(rng) } // NewRandomAddresses returns a slice of random peer addresses. func NewRandomAddresses(rng *rand.Rand, n int) []wire.Address { - walletAddresses := test.NewRandomAddresses(rng, n) - addresses := make([]wire.Address, len(walletAddresses)) - for i, x := range walletAddresses { - addresses[i] = x + addresses := make([]wire.Address, n) + for i := range addresses { + addresses[i] = NewRandomAddress(rng) } return addresses } @@ -41,8 +65,8 @@ func NewRandomAddresses(rng *rand.Rand, n int) []wire.Address { // recipient generated using randomness from rng. func NewRandomEnvelope(rng *rand.Rand, m wire.Msg) *wire.Envelope { return &wire.Envelope{ - Sender: test.NewRandomAddress(rng), - Recipient: test.NewRandomAddress(rng), + Sender: NewRandomAddress(rng), + Recipient: NewRandomAddress(rng), Msg: m, } }