• acud's avatar
    [bee #47, #56]: kademlia phase 0+1 (#155) · 8f780e3a
    acud authored
    * initial kademlia implementation
    * implement `ClosestPeer` so that retrievals and push sync will work on kademlia
    * hook up kademlia to be the default topology, instead of `full`
    * add peer broadcasting functionality upon connecting to a peer
    * add peer announcement on dial-in
    8f780e3a
mock.go 1.16 KB
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package mock

import (
	"context"
	"sync"

	"github.com/ethersphere/bee/pkg/swarm"
)

type Discovery struct {
	mtx     sync.Mutex
	ctr     int //how many ops
	records map[string][]swarm.Address
}

func NewDiscovery() *Discovery {
	return &Discovery{
		records: make(map[string][]swarm.Address),
	}
}

func (d *Discovery) BroadcastPeers(ctx context.Context, addressee swarm.Address, peers ...swarm.Address) error {
	for _, peer := range peers {
		d.mtx.Lock()
		d.records[addressee.String()] = append(d.records[addressee.String()], peer)
		d.mtx.Unlock()
	}
	d.mtx.Lock()
	d.ctr++
	d.mtx.Unlock()
	return nil
}

func (d *Discovery) Broadcasts() int {
	d.mtx.Lock()
	defer d.mtx.Unlock()
	return d.ctr
}

func (d *Discovery) AddresseeRecords(addressee swarm.Address) (peers []swarm.Address, exists bool) {
	d.mtx.Lock()
	defer d.mtx.Unlock()
	peers, exists = d.records[addressee.String()]
	return
}

func (d *Discovery) Reset() {
	d.mtx.Lock()
	defer d.mtx.Unlock()
	d.ctr = 0
	d.records = make(map[string][]swarm.Address)
}