github.com/ethersphere/bee/v2@v2.2.0/pkg/swarm/test_helpers_test.go (about) 1 // Copyright 2023 The Swarm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package swarm_test 6 7 import ( 8 "encoding/binary" 9 "testing" 10 11 "github.com/ethersphere/bee/v2/pkg/swarm" 12 ) 13 14 func Test_RandAddress(t *testing.T) { 15 t.Parallel() 16 17 addr := swarm.RandAddress(t) 18 assertNotZeroAddress(t, addr) 19 } 20 21 // TestRandAddressAt checks that RandAddressAt generates a correct random address 22 // at a given proximity order. It compares the number of leading equal bits in the generated 23 // address to the base address. 24 func Test_RandAddressAt(t *testing.T) { 25 t.Parallel() 26 27 base := swarm.MustParseHexAddress("ca1e9f3938cc1425c6061b96ad9eb93e134dfe8734ad490164ef20af9d1cf59c") 28 b0 := base.Bytes() 29 hw0 := []byte{b0[0], b0[1], 0, 0} // highest words of base address 30 hw0int := binary.BigEndian.Uint32(hw0) 31 32 for bitsInCommon := 0; bitsInCommon < 30; bitsInCommon++ { 33 addr := swarm.RandAddressAt(t, base, bitsInCommon) 34 assertNotZeroAddress(t, addr) 35 36 b1 := addr.Bytes() 37 hw1 := []byte{b1[0], b1[1], 0, 0} // highest words of 1 38 hw1int := binary.BigEndian.Uint32(hw1) 39 40 //bb0 is the bit mask to AND with hw0 and hw1 41 bb0 := uint32(0) 42 for i := 0; i < bitsInCommon; i++ { 43 bb0 |= (1 << (31 - i)) 44 } 45 46 andhw0 := hw0int & bb0 47 andhw1 := hw1int & bb0 48 49 // the result of the AND with both highest words of b0 and b1 should be equal 50 if andhw0 != andhw1 { 51 t.Fatalf("hw0 %08b hw1 %08b mask %08b &0 %08b &1 %08b", hw0int, hw1int, bb0, andhw0, andhw1) 52 } 53 } 54 } 55 56 func Test_RandAddresses(t *testing.T) { 57 t.Parallel() 58 59 count := 20 60 addrs := swarm.RandAddresses(t, count) 61 62 if got := len(addrs); got != count { 63 t.Fatalf("expected %d, got %d", count, got) 64 } 65 for i := 0; i < count; i++ { 66 assertNotZeroAddress(t, addrs[i]) 67 } 68 } 69 70 func assertNotZeroAddress(t *testing.T, addr swarm.Address) { 71 t.Helper() 72 73 if got := len(addr.Bytes()); got != swarm.HashSize { 74 t.Fatalf("expected %d, got %d", swarm.HashSize, got) 75 } 76 77 if addr.Equal(swarm.ZeroAddress) { 78 t.Fatalf("should not be zero address") 79 } 80 }