github.com/ethersphere/bee/v2@v2.2.0/pkg/util/nbhdutil/miner_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 nbhdutil_test 6 7 import ( 8 "context" 9 "math/rand" 10 "testing" 11 12 "github.com/ethersphere/bee/v2/pkg/crypto" 13 "github.com/ethersphere/bee/v2/pkg/swarm" 14 "github.com/ethersphere/bee/v2/pkg/util/nbhdutil" 15 ) 16 17 func TestMiner(t *testing.T) { 18 t.Parallel() 19 20 k, err := crypto.GenerateSecp256k1Key() 21 if err != nil { 22 t.Fatal(err) 23 } 24 25 const ( 26 networkID uint64 = 1 27 ) 28 prox := rand.Intn(16) 29 30 randomAddr := swarm.RandAddress(t) 31 prefix := bitStr(randomAddr.Bytes(), prox) 32 33 addr, nonce, err := nbhdutil.MineOverlay(context.Background(), k.PublicKey, networkID, prefix) 34 if err != nil { 35 t.Fatal(err) 36 } 37 38 if got := swarm.Proximity(randomAddr.Bytes(), addr.Bytes()); got < uint8(prox) { 39 t.Fatalf("mined overlay address has wrong proximity, got %d want %d", got, prox) 40 } 41 42 recoveredAddr, err := crypto.NewOverlayAddress(k.PublicKey, networkID, nonce) 43 if err != nil { 44 t.Fatal(err) 45 } 46 47 if !recoveredAddr.Equal(addr) { 48 t.Fatalf("mined overlay address does not match, got %s want %s", addr, recoveredAddr) 49 } 50 } 51 52 func bitStr(src []byte, bits int) string { 53 54 ret := "" 55 56 for _, b := range src { 57 for i := 7; i >= 0; i-- { 58 if b&(1<<i) > 0 { 59 ret += "1" 60 } else { 61 ret += "0" 62 } 63 bits-- 64 if bits == 0 { 65 return ret 66 } 67 } 68 } 69 70 return ret 71 }