github.com/ethersphere/bee/v2@v2.2.0/pkg/swarm/test_helpers.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 6 7 import ( 8 "math/rand" 9 "testing" 10 11 "github.com/ethersphere/bee/v2/pkg/util/testutil" 12 ) 13 14 // RandAddress generates a random address. 15 func RandAddress(tb testing.TB) Address { 16 tb.Helper() 17 18 return NewAddress(testutil.RandBytes(tb, HashSize)) 19 } 20 21 // RandAddressAt generates a random address at proximity order prox relative to address. 22 func RandAddressAt(tb testing.TB, self Address, prox int) Address { 23 tb.Helper() 24 25 addr := make([]byte, len(self.Bytes())) 26 copy(addr, self.Bytes()) 27 pos := -1 28 if prox >= 0 { 29 pos = prox / 8 30 trans := prox % 8 31 transbytea := byte(0) 32 for j := 0; j <= trans; j++ { 33 transbytea |= 1 << uint8(7-j) 34 } 35 flipbyte := byte(1 << uint8(7-trans)) 36 transbyteb := transbytea ^ byte(255) 37 randbyte := byte(rand.Intn(255)) 38 addr[pos] = ((addr[pos] & transbytea) ^ flipbyte) | randbyte&transbyteb 39 } 40 41 for i := pos + 1; i < len(addr); i++ { 42 addr[i] = byte(rand.Intn(255)) 43 } 44 45 a := NewAddress(addr) 46 if a.Equal(self) { 47 tb.Fatalf("generated same address") 48 } 49 50 return a 51 } 52 53 // RandAddresses generates slice with a random address. 54 func RandAddresses(tb testing.TB, count int) []Address { 55 tb.Helper() 56 57 result := make([]Address, count) 58 for i := 0; i < count; i++ { 59 result[i] = RandAddress(tb) 60 } 61 return result 62 } 63 64 // RandBatchID generates a random BatchID. 65 func RandBatchID(tb testing.TB) []byte { 66 tb.Helper() 67 68 return testutil.RandBytes(tb, HashSize) 69 }