go-waku/waku/v2/node/wakunode2.go

624 lines
14 KiB
Go
Raw Normal View History

2021-03-11 20:27:12 +00:00
package node
import (
"context"
"errors"
2021-03-11 20:27:12 +00:00
"fmt"
2021-11-17 16:19:42 +00:00
"net"
"strconv"
"sync"
2021-03-15 23:59:18 +00:00
"time"
2021-03-11 20:27:12 +00:00
"github.com/ethereum/go-ethereum/common/hexutil"
2021-03-22 16:45:13 +00:00
logging "github.com/ipfs/go-log"
2021-03-11 20:27:12 +00:00
"github.com/libp2p/go-libp2p"
2021-08-31 18:19:49 +00:00
2021-06-16 10:14:22 +00:00
"github.com/libp2p/go-libp2p-core/event"
2021-03-11 20:27:12 +00:00
"github.com/libp2p/go-libp2p-core/host"
2021-11-10 13:36:51 +00:00
"github.com/libp2p/go-libp2p-core/network"
2021-03-18 16:40:47 +00:00
"github.com/libp2p/go-libp2p-core/peer"
2021-08-31 18:19:49 +00:00
"github.com/libp2p/go-libp2p-core/peerstore"
p2pproto "github.com/libp2p/go-libp2p-core/protocol"
pubsub "github.com/libp2p/go-libp2p-pubsub"
2021-03-11 20:27:12 +00:00
ma "github.com/multiformats/go-multiaddr"
"go.opencensus.io/stats"
2021-04-22 00:09:37 +00:00
2021-10-05 02:13:54 +00:00
rendezvous "github.com/status-im/go-waku-rendezvous"
"github.com/status-im/go-waku/waku/try"
2021-11-01 14:42:55 +00:00
v2 "github.com/status-im/go-waku/waku/v2"
2021-11-17 16:19:42 +00:00
"github.com/status-im/go-waku/waku/v2/discv5"
"github.com/status-im/go-waku/waku/v2/metrics"
2021-06-10 12:59:51 +00:00
"github.com/status-im/go-waku/waku/v2/protocol/filter"
"github.com/status-im/go-waku/waku/v2/protocol/lightpush"
"github.com/status-im/go-waku/waku/v2/protocol/pb"
"github.com/status-im/go-waku/waku/v2/protocol/relay"
2021-04-22 00:09:37 +00:00
"github.com/status-im/go-waku/waku/v2/protocol/store"
"github.com/status-im/go-waku/waku/v2/protocol/swap"
"github.com/status-im/go-waku/waku/v2/utils"
2021-03-11 20:27:12 +00:00
)
2021-03-22 16:45:13 +00:00
var log = logging.Logger("wakunode")
2021-11-10 13:36:51 +00:00
type Peer struct {
ID peer.ID
Protocols []string
Addrs []ma.Multiaddr
Connected bool
}
2021-03-11 20:27:12 +00:00
type WakuNode struct {
host host.Host
opts *WakuNodeParameters
relay *relay.WakuRelay
filter *filter.WakuFilter
lightPush *lightpush.WakuLightPush
2021-10-01 17:49:50 +00:00
rendezvous *rendezvous.RendezvousService
store *store.WakuStore
swap *swap.WakuSwap
wakuFlag utils.WakuEnrBitfield
2021-11-17 16:19:42 +00:00
addrChan chan ma.Multiaddr
discoveryV5 *discv5.DiscoveryV5
2021-11-01 14:42:55 +00:00
bcaster v2.Broadcaster
connectionNotif ConnectionNotifier
2021-06-16 10:14:22 +00:00
protocolEventSub event.Subscription
identificationEventSub event.Subscription
2021-11-17 16:19:42 +00:00
addressChangesSub event.Subscription
2021-06-16 10:14:22 +00:00
keepAliveMutex sync.Mutex
keepAliveFails map[peer.ID]int
ctx context.Context
cancel context.CancelFunc
quit chan struct{}
wg *sync.WaitGroup
2021-06-16 10:14:22 +00:00
// Channel passed to WakuNode constructor
// receiving connection status notifications
connStatusChan chan ConnStatus
2021-03-11 20:27:12 +00:00
}
func New(ctx context.Context, opts ...WakuNodeOption) (*WakuNode, error) {
params := new(WakuNodeParameters)
2021-03-11 20:27:12 +00:00
ctx, cancel := context.WithCancel(ctx)
params.libP2POpts = DefaultLibP2POptions
2021-11-17 16:19:42 +00:00
opts = append(DefaultWakuNodeOptions, opts...)
for _, opt := range opts {
err := opt(params)
2021-03-11 20:27:12 +00:00
if err != nil {
2021-10-01 17:49:50 +00:00
cancel()
2021-03-11 20:27:12 +00:00
return nil, err
}
}
2021-11-17 16:19:42 +00:00
// Setting default host address if none was provided
if params.hostAddr == nil {
err := WithHostAddress(&net.TCPAddr{IP: net.ParseIP("0.0.0.0"), Port: 0})(params)
if err != nil {
cancel()
return nil, err
}
}
if len(params.multiAddr) > 0 {
params.libP2POpts = append(params.libP2POpts, libp2p.ListenAddrs(params.multiAddr...))
}
2021-03-11 20:27:12 +00:00
if params.privKey != nil {
params.libP2POpts = append(params.libP2POpts, params.Identity())
}
2021-03-15 16:07:23 +00:00
2021-10-15 02:15:02 +00:00
if params.addressFactory != nil {
params.libP2POpts = append(params.libP2POpts, libp2p.AddrsFactory(params.addressFactory))
}
host, err := libp2p.New(ctx, params.libP2POpts...)
2021-03-11 20:27:12 +00:00
if err != nil {
2021-10-01 17:49:50 +00:00
cancel()
2021-03-11 20:27:12 +00:00
return nil, err
}
w := new(WakuNode)
2021-11-01 14:42:55 +00:00
w.bcaster = v2.NewBroadcaster(1024)
2021-03-15 16:07:23 +00:00
w.host = host
w.cancel = cancel
w.ctx = ctx
w.opts = params
w.quit = make(chan struct{})
w.wg = &sync.WaitGroup{}
2021-11-17 16:19:42 +00:00
w.addrChan = make(chan ma.Multiaddr, 1024)
w.keepAliveFails = make(map[peer.ID]int)
w.wakuFlag = utils.NewWakuEnrBitfield(w.opts.enableLightPush, w.opts.enableFilter, w.opts.enableStore, w.opts.enableRelay)
2021-06-16 10:14:22 +00:00
if w.protocolEventSub, err = host.EventBus().Subscribe(new(event.EvtPeerProtocolsUpdated)); err != nil {
return nil, err
}
2021-06-16 10:14:22 +00:00
if w.identificationEventSub, err = host.EventBus().Subscribe(new(event.EvtPeerIdentificationCompleted)); err != nil {
return nil, err
}
2021-06-16 10:14:22 +00:00
2021-11-17 16:19:42 +00:00
if w.addressChangesSub, err = host.EventBus().Subscribe(new(event.EvtLocalAddressesUpdated)); err != nil {
return nil, err
}
if params.connStatusC != nil {
w.connStatusChan = params.connStatusC
2021-06-28 14:14:28 +00:00
}
2021-10-16 21:50:49 +00:00
w.connectionNotif = NewConnectionNotifier(ctx, host)
w.host.Network().Notify(w.connectionNotif)
w.wg.Add(2)
2021-06-16 10:14:22 +00:00
go w.connectednessListener()
go w.checkForAddressChanges()
go w.onAddrChange()
2021-06-28 14:14:28 +00:00
2021-10-05 02:13:54 +00:00
if w.opts.keepAliveInterval > time.Duration(0) {
w.wg.Add(1)
2021-10-05 02:13:54 +00:00
w.startKeepAlive(w.opts.keepAliveInterval)
}
return w, nil
}
2021-11-17 16:19:42 +00:00
func (w *WakuNode) onAddrChange() {
for m := range w.addrChan {
ipStr, err := m.ValueForProtocol(ma.P_IP4)
if err != nil {
log.Error(fmt.Sprintf("could not extract ip from ma %s: %s", m, err.Error()))
continue
}
ip := net.ParseIP(ipStr)
if !ip.IsLoopback() && !ip.IsUnspecified() {
if w.opts.enableDiscV5 {
err := w.discoveryV5.UpdateAddr(ip)
if err != nil {
log.Error(fmt.Sprintf("could not update DiscV5 address with IP %s: %s", ip, err.Error()))
continue
}
}
}
}
}
func (w *WakuNode) logAddress(addr ma.Multiaddr) {
log.Info("Listening on ", addr)
// TODO: make this optional depending on DNS Disc being enabled
if w.opts.privKey != nil {
enr, ip, err := utils.GetENRandIP(addr, w.wakuFlag, w.opts.privKey)
if err != nil {
log.Error("could not obtain ENR record from multiaddress", err)
} else {
log.Info(fmt.Sprintf("ENR for IP %s: %s", ip, enr))
}
}
}
2021-11-17 16:19:42 +00:00
func (w *WakuNode) checkForAddressChanges() {
defer w.wg.Done()
2021-11-17 16:19:42 +00:00
addrs := w.ListenAddresses()
first := make(chan struct{}, 1)
first <- struct{}{}
for {
select {
case <-w.quit:
return
case <-first:
for _, addr := range addrs {
w.logAddress(addr)
2021-11-17 16:19:42 +00:00
}
case <-w.addressChangesSub.Out():
newAddrs := w.ListenAddresses()
print := false
if len(addrs) != len(newAddrs) {
print = true
} else {
for i := range newAddrs {
if addrs[i].String() != newAddrs[i].String() {
print = true
break
}
}
}
if print {
addrs = newAddrs
log.Warn("Change in host multiaddresses")
for _, addr := range newAddrs {
w.addrChan <- addr
w.logAddress(addr)
2021-11-17 16:19:42 +00:00
}
}
}
}
}
2021-10-05 02:13:54 +00:00
func (w *WakuNode) Start() error {
w.swap = swap.NewWakuSwap([]swap.SwapOption{
swap.WithMode(w.opts.swapMode),
swap.WithThreshold(w.opts.swapPaymentThreshold, w.opts.swapDisconnectThreshold),
}...)
w.store = store.NewWakuStore(w.host, w.swap, w.opts.messageProvider, w.opts.maxMessages, w.opts.maxDuration)
2021-10-05 02:13:54 +00:00
if w.opts.enableStore {
2021-06-16 10:14:22 +00:00
w.startStore()
}
2021-10-05 02:13:54 +00:00
if w.opts.enableFilter {
filter, err := filter.NewWakuFilter(w.ctx, w.host, w.opts.isFilterFullNode, w.opts.filterOpts...)
if err != nil {
return err
}
w.filter = filter
2021-06-10 12:59:51 +00:00
}
2021-10-05 02:13:54 +00:00
if w.opts.enableRendezvous {
rendezvous := rendezvous.NewRendezvousDiscovery(w.host)
w.opts.wOpts = append(w.opts.wOpts, pubsub.WithDiscovery(rendezvous, w.opts.rendezvousOpts...))
2021-10-01 17:49:50 +00:00
}
2021-11-17 16:19:42 +00:00
if w.opts.enableDiscV5 {
err := w.mountDiscV5()
if err != nil {
return err
}
}
if w.opts.enableDiscV5 {
w.opts.wOpts = append(w.opts.wOpts, pubsub.WithDiscovery(w.discoveryV5, w.opts.discV5Opts...))
}
err := w.mountRelay(w.opts.minRelayPeersToPublish, w.opts.wOpts...)
2021-11-01 14:42:55 +00:00
if err != nil {
return err
2021-06-16 10:14:22 +00:00
}
2021-11-01 12:38:03 +00:00
w.lightPush = lightpush.NewWakuLightPush(w.ctx, w.host, w.relay)
2021-10-05 02:13:54 +00:00
if w.opts.enableLightPush {
2021-11-01 12:38:03 +00:00
if err := w.lightPush.Start(); err != nil {
return err
}
}
2021-10-05 02:13:54 +00:00
if w.opts.enableRendezvousServer {
2021-10-01 17:49:50 +00:00
err := w.mountRendezvous()
if err != nil {
2021-10-05 02:13:54 +00:00
return err
2021-10-01 17:49:50 +00:00
}
}
2021-11-01 14:42:55 +00:00
// Subscribe store to topic
if w.opts.storeMsgs {
log.Info("Subscribing store to broadcaster")
w.bcaster.Register(w.store.MsgC)
}
if w.filter != nil {
log.Info("Subscribing filter to broadcaster")
w.bcaster.Register(w.filter.MsgC)
}
2021-10-05 02:13:54 +00:00
return nil
2021-03-11 20:27:12 +00:00
}
2021-03-22 16:45:13 +00:00
func (w *WakuNode) Stop() {
2021-03-15 16:07:23 +00:00
defer w.cancel()
2021-03-22 16:45:13 +00:00
close(w.quit)
2021-11-17 16:19:42 +00:00
close(w.addrChan)
2021-11-01 14:42:55 +00:00
w.bcaster.Close()
defer w.connectionNotif.Close()
2021-06-16 10:14:22 +00:00
defer w.protocolEventSub.Close()
defer w.identificationEventSub.Close()
2021-11-17 16:19:42 +00:00
defer w.addressChangesSub.Close()
if w.rendezvous != nil {
w.rendezvous.Stop()
}
if w.filter != nil {
w.filter.Stop()
2021-03-22 16:45:13 +00:00
}
2021-11-01 14:42:55 +00:00
w.relay.Stop()
2021-11-01 12:38:03 +00:00
w.lightPush.Stop()
w.store.Stop()
w.host.Close()
w.wg.Wait()
2021-03-15 16:07:23 +00:00
}
func (w *WakuNode) Host() host.Host {
return w.host
}
func (w *WakuNode) ID() string {
return w.host.ID().Pretty()
}
func (w *WakuNode) ListenAddresses() []ma.Multiaddr {
2021-04-04 17:05:33 +00:00
hostInfo, _ := ma.NewMultiaddr(fmt.Sprintf("/p2p/%s", w.host.ID().Pretty()))
var result []ma.Multiaddr
2021-04-04 17:05:33 +00:00
for _, addr := range w.host.Addrs() {
result = append(result, addr.Encapsulate(hostInfo))
2021-04-04 17:05:33 +00:00
}
return result
}
func (w *WakuNode) Relay() *relay.WakuRelay {
return w.relay
2021-03-15 16:07:23 +00:00
}
2021-11-01 12:38:03 +00:00
func (w *WakuNode) Store() *store.WakuStore {
return w.store
}
2021-06-10 12:59:51 +00:00
func (w *WakuNode) Filter() *filter.WakuFilter {
return w.filter
}
2021-11-01 12:38:03 +00:00
func (w *WakuNode) Lightpush() *lightpush.WakuLightPush {
return w.lightPush
}
2021-11-17 16:19:42 +00:00
func (w *WakuNode) DiscV5() *discv5.DiscoveryV5 {
return w.discoveryV5
}
2021-11-18 14:20:58 +00:00
func (w *WakuNode) Broadcaster() v2.Broadcaster {
return w.bcaster
}
func (w *WakuNode) Publish(ctx context.Context, msg *pb.WakuMessage) error {
if !w.opts.enableLightPush && !w.opts.enableRelay {
return errors.New("cannot publish message, relay and lightpush are disabled")
}
hash, _ := msg.Hash()
err := try.Do(func(attempt int) (bool, error) {
var err error
if !w.relay.EnoughPeersToPublish() {
if !w.lightPush.IsStarted() {
err = errors.New("not enought peers for relay and lightpush is not yet started")
} else {
log.Debug("publishing message via lightpush", hexutil.Encode(hash))
_, err = w.Lightpush().Publish(ctx, msg)
}
} else {
log.Debug("publishing message via relay", hexutil.Encode(hash))
_, err = w.Relay().Publish(ctx, msg)
}
return attempt < maxPublishAttempt, err
})
return err
}
func (w *WakuNode) mountRelay(minRelayPeersToPublish int, opts ...pubsub.Option) error {
var err error
w.relay, err = relay.NewWakuRelay(w.ctx, w.host, w.bcaster, minRelayPeersToPublish, opts...)
if err != nil {
return err
}
2021-03-15 16:07:23 +00:00
2021-11-01 14:42:55 +00:00
if w.opts.enableRelay {
_, err = w.relay.Subscribe(w.ctx)
2021-11-01 14:42:55 +00:00
if err != nil {
return err
}
2021-06-28 14:14:28 +00:00
}
2021-03-15 16:07:23 +00:00
// TODO: rlnRelay
return err
2021-03-18 16:40:47 +00:00
}
2021-11-17 16:19:42 +00:00
func (w *WakuNode) mountDiscV5() error {
discV5Options := []discv5.DiscoveryV5Option{
discv5.WithBootnodes(w.opts.discV5bootnodes),
discv5.WithUDPPort(w.opts.udpPort),
discv5.WithAutoUpdate(w.opts.discV5autoUpdate),
}
addr := w.ListenAddresses()[0]
ipStr, err := addr.ValueForProtocol(ma.P_IP4)
if err != nil {
return err
}
portStr, err := addr.ValueForProtocol(ma.P_TCP)
if err != nil {
return err
}
port, err := strconv.Atoi(portStr)
if err != nil {
return err
}
2021-12-08 14:21:30 +00:00
w.discoveryV5, err = discv5.NewDiscoveryV5(w.Host(), net.ParseIP(ipStr), port, w.opts.privKey, w.wakuFlag, discV5Options...)
2021-11-17 16:19:42 +00:00
2021-12-08 14:21:30 +00:00
return err
2021-11-17 16:19:42 +00:00
}
2021-10-01 17:49:50 +00:00
func (w *WakuNode) mountRendezvous() error {
w.rendezvous = rendezvous.NewRendezvousService(w.host, w.opts.rendevousStorage)
if err := w.rendezvous.Start(); err != nil {
2021-10-01 17:49:50 +00:00
return err
}
2021-10-01 17:49:50 +00:00
log.Info("Rendezvous service started")
return nil
}
2021-06-28 14:14:28 +00:00
func (w *WakuNode) startStore() {
w.store.Start(w.ctx)
if w.opts.shouldResume {
// TODO: extract this to a function and run it when you go offline
// TODO: determine if a store is listening to a topic
w.wg.Add(1)
go func() {
defer w.wg.Done()
2021-11-19 23:51:18 +00:00
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
peerVerif:
for {
select {
case <-w.quit:
return
2021-11-19 23:51:18 +00:00
case <-ticker.C:
_, err := utils.SelectPeer(w.host, string(store.StoreID_v20beta3))
if err == nil {
break peerVerif
}
}
}
ctxWithTimeout, ctxCancel := context.WithTimeout(w.ctx, 20*time.Second)
defer ctxCancel()
2021-11-01 12:38:03 +00:00
if _, err := w.store.Resume(ctxWithTimeout, string(relay.DefaultWakuTopic), nil); err != nil {
log.Info("Retrying in 10s...")
time.Sleep(10 * time.Second)
} else {
break
}
}
}()
2021-08-13 11:56:09 +00:00
}
}
func (w *WakuNode) addPeer(info *peer.AddrInfo, protocolID p2pproto.ID) error {
log.Info(fmt.Sprintf("Adding peer %s to peerstore", info.ID.Pretty()))
w.host.Peerstore().AddAddrs(info.ID, info.Addrs, peerstore.PermanentAddrTTL)
2021-10-16 21:50:49 +00:00
err := w.host.Peerstore().AddProtocols(info.ID, string(protocolID))
if err != nil {
return err
}
2021-06-10 12:59:51 +00:00
2021-10-16 21:50:49 +00:00
return nil
2021-08-31 18:19:49 +00:00
}
2021-06-10 12:59:51 +00:00
func (w *WakuNode) AddPeer(address ma.Multiaddr, protocolID p2pproto.ID) (*peer.ID, error) {
info, err := peer.AddrInfoFromP2pAddr(address)
if err != nil {
return nil, err
}
2021-06-10 12:59:51 +00:00
return &info.ID, w.addPeer(info, protocolID)
2021-06-28 14:14:28 +00:00
}
func (w *WakuNode) DialPeerWithMultiAddress(ctx context.Context, address ma.Multiaddr) error {
info, err := peer.AddrInfoFromP2pAddr(address)
if err != nil {
return err
}
return w.connect(ctx, *info)
}
func (w *WakuNode) DialPeer(ctx context.Context, address string) error {
p, err := ma.NewMultiaddr(address)
if err != nil {
return err
}
info, err := peer.AddrInfoFromP2pAddr(p)
if err != nil {
return err
}
return w.connect(ctx, *info)
}
func (w *WakuNode) connect(ctx context.Context, info peer.AddrInfo) error {
err := w.host.Connect(ctx, info)
if err != nil {
return err
}
2021-10-16 21:50:49 +00:00
stats.Record(ctx, metrics.Dials.M(1))
return nil
}
func (w *WakuNode) DialPeerByID(ctx context.Context, peerID peer.ID) error {
2021-08-31 19:17:56 +00:00
info := w.host.Peerstore().PeerInfo(peerID)
return w.connect(ctx, info)
2021-08-31 19:17:56 +00:00
}
func (w *WakuNode) ClosePeerByAddress(address string) error {
p, err := ma.NewMultiaddr(address)
if err != nil {
return err
}
// Extract the peer ID from the multiaddr.
info, err := peer.AddrInfoFromP2pAddr(p)
if err != nil {
return err
}
return w.ClosePeerById(info.ID)
}
func (w *WakuNode) ClosePeerById(id peer.ID) error {
err := w.host.Network().ClosePeer(id)
if err != nil {
return err
}
2021-09-06 13:34:58 +00:00
return nil
}
func (w *WakuNode) PeerCount() int {
return len(w.host.Network().Peers())
}
2021-11-10 13:36:51 +00:00
func (w *WakuNode) PeerStats() PeerStats {
p := make(PeerStats)
for _, peerID := range w.host.Network().Peers() {
protocols, err := w.host.Peerstore().GetProtocols(peerID)
if err != nil {
continue
}
p[peerID] = protocols
}
return p
}
2021-11-10 13:36:51 +00:00
func (w *WakuNode) Peers() ([]*Peer, error) {
var peers []*Peer
for _, peerId := range w.host.Peerstore().Peers() {
connected := w.host.Network().Connectedness(peerId) == network.Connected
protocols, err := w.host.Peerstore().GetProtocols(peerId)
if err != nil {
return nil, err
}
addrs := w.host.Peerstore().Addrs(peerId)
peers = append(peers, &Peer{
ID: peerId,
Protocols: protocols,
Connected: connected,
Addrs: addrs,
})
}
return peers, nil
}