Skip to content

Commit

Permalink
wallet: Add CloneAddress(es)
Browse files Browse the repository at this point in the history
Signed-off-by: Sebastian Stammler <[email protected]>
  • Loading branch information
sebastianst committed Mar 16, 2022
1 parent 5441eed commit 9659076
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
27 changes: 27 additions & 0 deletions wallet/address.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (

"github.com/pkg/errors"

"perun.network/go-perun/log"
"perun.network/go-perun/wire/perunio"
)

Expand Down Expand Up @@ -58,6 +59,32 @@ func IndexOfAddr(addrs []Address, addr Address) int {
return -1
}

// CloneAddress returns a clone of an Address using its binary marshaling
// implementation. It panics if an error occurs during binary (un)marshaling.
func CloneAddress(a Address) Address {
data, err := a.MarshalBinary()
if err != nil {
log.WithError(err).Panic("error binary-marshaling Address")
}

clone := NewAddress()
if err := clone.UnmarshalBinary(data); err != nil {
log.WithError(err).Panic("error binary-unmarshaling Address")
}
return clone
}

// CloneAddresses returns a clone of a slice of Addresses using their binary
// marshaling implementation. It panics if an error occurs during binary
// (un)marshaling.
func CloneAddresses(as []Address) []Address {
clones := make([]Address, 0, len(as))
for _, a := range as {
clones = append(clones, CloneAddress(a))
}
return clones
}

// AddressPredicate is a function for filtering Addresses.
type AddressPredicate = func(Address) bool

Expand Down
19 changes: 19 additions & 0 deletions wallet/address_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,22 @@ func TestAddrKey(t *testing.T) {
require.True(t, a.Equal(wallet.FromKey(wallet.Key(a))))
}
}

func TestCloneAddress(t *testing.T) {
rng := pkgtest.Prng(t)
addr := wallettest.NewRandomAddress(rng)
addr0 := wallet.CloneAddress(addr)
require.Equal(t, addr, addr0)
require.NotSame(t, addr, addr0)
}

func TestCloneAddresses(t *testing.T) {
rng := pkgtest.Prng(t)
addrs := wallettest.NewRandomAddresses(rng, 3)
addrs0 := wallet.CloneAddresses(addrs)
require.Equal(t, addrs, addrs0)
require.NotSame(t, addrs, addrs0)
for i, a := range addrs {
require.NotSame(t, a, addrs0[i])
}
}

0 comments on commit 9659076

Please sign in to comment.