node.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. protocol "github.com/mudler/edgevpn/pkg/protocol"
  24. pubsub "github.com/libp2p/go-libp2p-pubsub"
  25. "github.com/mudler/edgevpn/pkg/blockchain"
  26. hub "github.com/mudler/edgevpn/pkg/hub"
  27. "github.com/mudler/edgevpn/pkg/logger"
  28. )
  29. type Node struct {
  30. config Config
  31. HubRoom *hub.Room
  32. inputCh chan *hub.Message
  33. seed int64
  34. host host.Host
  35. ledger *blockchain.Ledger
  36. }
  37. var defaultLibp2pOptions = []libp2p.Option{
  38. libp2p.EnableNATService(),
  39. libp2p.NATPortMap(),
  40. libp2p.EnableAutoRelay(),
  41. }
  42. func New(p ...Option) *Node {
  43. c := Config{
  44. DiscoveryInterval: 120 * time.Second,
  45. StreamHandlers: make(map[protocol.Protocol]StreamHandler),
  46. LedgerAnnounceTime: 5 * time.Second,
  47. LedgerSyncronizationTime: 5 * time.Second,
  48. SealKeyLength: 12,
  49. Options: defaultLibp2pOptions,
  50. Logger: logger.New(log.LevelDebug),
  51. }
  52. c.Apply(p...)
  53. return &Node{
  54. config: c,
  55. inputCh: make(chan *hub.Message, 3000),
  56. seed: 0,
  57. }
  58. }
  59. // Ledger return the ledger which uses the node
  60. // connection to broadcast messages
  61. func (e *Node) Ledger() (*blockchain.Ledger, error) {
  62. if e.ledger != nil {
  63. return e.ledger, nil
  64. }
  65. mw, err := e.messageWriter()
  66. if err != nil {
  67. return nil, err
  68. }
  69. e.ledger = blockchain.New(mw, e.config.Store)
  70. return e.ledger, nil
  71. }
  72. // Start joins the node over the p2p network
  73. func (e *Node) Start(ctx context.Context) error {
  74. ledger, err := e.Ledger()
  75. if err != nil {
  76. return err
  77. }
  78. // Set the handler when we receive messages
  79. // The ledger needs to read them and update the internal blockchain
  80. e.config.Handlers = append(e.config.Handlers, ledger.Update)
  81. e.config.Logger.Info("Starting EdgeVPN network")
  82. // Startup libp2p network
  83. err = e.startNetwork(ctx)
  84. if err != nil {
  85. return err
  86. }
  87. // Send periodically messages to the channel with our blockchain content
  88. ledger.Syncronizer(ctx, e.config.LedgerSyncronizationTime)
  89. // Start eventual declared NetworkServices
  90. for _, s := range e.config.NetworkServices {
  91. s(ctx, e.config, e, ledger)
  92. }
  93. return nil
  94. }
  95. // messageWriter returns a new MessageWriter bound to the edgevpn instance
  96. // with the given options
  97. func (e *Node) messageWriter(opts ...hub.MessageOption) (*messageWriter, error) {
  98. mess := &hub.Message{}
  99. mess.Apply(opts...)
  100. return &messageWriter{
  101. c: e.config,
  102. input: e.inputCh,
  103. mess: mess,
  104. }, nil
  105. }
  106. func (e *Node) startNetwork(ctx context.Context) error {
  107. e.config.Logger.Debug("Generating host data")
  108. host, err := e.genHost(ctx)
  109. if err != nil {
  110. e.config.Logger.Error(err.Error())
  111. return err
  112. }
  113. e.host = host
  114. ledger, err := e.Ledger()
  115. if err != nil {
  116. return err
  117. }
  118. for pid, strh := range e.config.StreamHandlers {
  119. host.SetStreamHandler(pid.ID(), network.StreamHandler(strh(e, ledger)))
  120. }
  121. e.config.Logger.Info("Node ID:", host.ID())
  122. e.config.Logger.Info("Node Addresses:", host.Addrs())
  123. // create a new PubSub service using the GossipSub router
  124. ps, err := pubsub.NewGossipSub(ctx, host, pubsub.WithMaxMessageSize(e.config.MaxMessageSize))
  125. if err != nil {
  126. return err
  127. }
  128. // join the "chat" room
  129. cr, err := hub.JoinRoom(ctx, ps, host.ID(), e.config.RoomName)
  130. if err != nil {
  131. return err
  132. }
  133. e.HubRoom = cr
  134. for _, sd := range e.config.ServiceDiscovery {
  135. if err := sd.Run(e.config.Logger, ctx, host); err != nil {
  136. e.config.Logger.Fatal(err)
  137. }
  138. }
  139. go e.handleEvents(ctx)
  140. e.config.Logger.Debug("Network started")
  141. return nil
  142. }