node.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. // Copyright © 2021 Ettore Di Giacinto <[email protected]>
  2. //
  3. // This program is free software; you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation; either version 2 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program; if not, see <http://www.gnu.org/licenses/>.
  15. package node
  16. import (
  17. "context"
  18. "time"
  19. "github.com/ipfs/go-log"
  20. "github.com/libp2p/go-libp2p"
  21. "github.com/libp2p/go-libp2p-core/host"
  22. "github.com/libp2p/go-libp2p-core/network"
  23. "github.com/libp2p/go-libp2p/p2p/net/conngater"
  24. protocol "github.com/mudler/edgevpn/pkg/protocol"
  25. pubsub "github.com/libp2p/go-libp2p-pubsub"
  26. "github.com/mudler/edgevpn/pkg/blockchain"
  27. hub "github.com/mudler/edgevpn/pkg/hub"
  28. "github.com/mudler/edgevpn/pkg/logger"
  29. )
  30. type Node struct {
  31. config Config
  32. HubRoom *hub.Room
  33. inputCh chan *hub.Message
  34. seed int64
  35. host host.Host
  36. cg *conngater.BasicConnectionGater
  37. ledger *blockchain.Ledger
  38. }
  39. var defaultLibp2pOptions = []libp2p.Option{
  40. libp2p.EnableNATService(),
  41. libp2p.NATPortMap(),
  42. libp2p.EnableAutoRelay(),
  43. }
  44. func New(p ...Option) *Node {
  45. c := Config{
  46. DiscoveryInterval: 120 * time.Second,
  47. StreamHandlers: make(map[protocol.Protocol]StreamHandler),
  48. LedgerAnnounceTime: 5 * time.Second,
  49. LedgerSyncronizationTime: 5 * time.Second,
  50. SealKeyLength: 12,
  51. Options: defaultLibp2pOptions,
  52. Logger: logger.New(log.LevelDebug),
  53. }
  54. c.Apply(p...)
  55. return &Node{
  56. config: c,
  57. inputCh: make(chan *hub.Message, 3000),
  58. seed: 0,
  59. }
  60. }
  61. // Ledger return the ledger which uses the node
  62. // connection to broadcast messages
  63. func (e *Node) Ledger() (*blockchain.Ledger, error) {
  64. if e.ledger != nil {
  65. return e.ledger, nil
  66. }
  67. mw, err := e.messageWriter()
  68. if err != nil {
  69. return nil, err
  70. }
  71. e.ledger = blockchain.New(mw, e.config.Store)
  72. return e.ledger, nil
  73. }
  74. // Start joins the node over the p2p network
  75. func (e *Node) Start(ctx context.Context) error {
  76. ledger, err := e.Ledger()
  77. if err != nil {
  78. return err
  79. }
  80. // Set the handler when we receive messages
  81. // The ledger needs to read them and update the internal blockchain
  82. e.config.Handlers = append(e.config.Handlers, ledger.Update)
  83. e.config.Logger.Info("Starting EdgeVPN network")
  84. // Startup libp2p network
  85. err = e.startNetwork(ctx)
  86. if err != nil {
  87. return err
  88. }
  89. // Send periodically messages to the channel with our blockchain content
  90. ledger.Syncronizer(ctx, e.config.LedgerSyncronizationTime)
  91. // Start eventual declared NetworkServices
  92. for _, s := range e.config.NetworkServices {
  93. err := s(ctx, e.config, e, ledger)
  94. if err != nil {
  95. return err
  96. }
  97. }
  98. return nil
  99. }
  100. // messageWriter returns a new MessageWriter bound to the edgevpn instance
  101. // with the given options
  102. func (e *Node) messageWriter(opts ...hub.MessageOption) (*messageWriter, error) {
  103. mess := &hub.Message{}
  104. mess.Apply(opts...)
  105. return &messageWriter{
  106. c: e.config,
  107. input: e.inputCh,
  108. mess: mess,
  109. }, nil
  110. }
  111. func (e *Node) startNetwork(ctx context.Context) error {
  112. e.config.Logger.Debug("Generating host data")
  113. host, err := e.genHost(ctx)
  114. if err != nil {
  115. e.config.Logger.Error(err.Error())
  116. return err
  117. }
  118. e.host = host
  119. ledger, err := e.Ledger()
  120. if err != nil {
  121. return err
  122. }
  123. for pid, strh := range e.config.StreamHandlers {
  124. host.SetStreamHandler(pid.ID(), network.StreamHandler(strh(e, ledger)))
  125. }
  126. e.config.Logger.Info("Node ID:", host.ID())
  127. e.config.Logger.Info("Node Addresses:", host.Addrs())
  128. // create a new PubSub service using the GossipSub router
  129. ps, err := pubsub.NewGossipSub(ctx, host, pubsub.WithMaxMessageSize(e.config.MaxMessageSize))
  130. if err != nil {
  131. return err
  132. }
  133. // join the "chat" room
  134. cr, err := hub.JoinRoom(ctx, ps, host.ID(), e.config.RoomName)
  135. if err != nil {
  136. return err
  137. }
  138. e.HubRoom = cr
  139. for _, sd := range e.config.ServiceDiscovery {
  140. if err := sd.Run(e.config.Logger, ctx, host); err != nil {
  141. e.config.Logger.Fatal(err)
  142. }
  143. }
  144. go e.handleEvents(ctx)
  145. e.config.Logger.Debug("Network started")
  146. return nil
  147. }