node.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. "fmt"
  19. "sync"
  20. "time"
  21. "github.com/ipfs/go-log"
  22. "github.com/libp2p/go-libp2p"
  23. "github.com/libp2p/go-libp2p-core/host"
  24. "github.com/libp2p/go-libp2p-core/network"
  25. "github.com/libp2p/go-libp2p/p2p/net/conngater"
  26. "github.com/mudler/edgevpn/pkg/crypto"
  27. protocol "github.com/mudler/edgevpn/pkg/protocol"
  28. "github.com/mudler/edgevpn/pkg/blockchain"
  29. hub "github.com/mudler/edgevpn/pkg/hub"
  30. "github.com/mudler/edgevpn/pkg/logger"
  31. )
  32. type Node struct {
  33. config Config
  34. MessageHub *hub.MessageHub
  35. GenericHub *hub.MessageHub
  36. //HubRoom *hub.Room
  37. inputCh chan *hub.Message
  38. genericHubCh chan *hub.Message
  39. seed int64
  40. host host.Host
  41. cg *conngater.BasicConnectionGater
  42. ledger *blockchain.Ledger
  43. sync.Mutex
  44. }
  45. const defaultChanSize = 3000
  46. var defaultLibp2pOptions = []libp2p.Option{
  47. libp2p.EnableNATService(),
  48. libp2p.NATPortMap(),
  49. libp2p.EnableAutoRelay(),
  50. }
  51. func New(p ...Option) (*Node, error) {
  52. c := &Config{
  53. DiscoveryInterval: 120 * time.Second,
  54. StreamHandlers: make(map[protocol.Protocol]StreamHandler),
  55. LedgerAnnounceTime: 5 * time.Second,
  56. LedgerSyncronizationTime: 5 * time.Second,
  57. SealKeyLength: 12,
  58. Options: defaultLibp2pOptions,
  59. Logger: logger.New(log.LevelDebug),
  60. Sealer: &crypto.AESSealer{},
  61. Store: &blockchain.MemoryStore{},
  62. }
  63. if err := c.Apply(p...); err != nil {
  64. return nil, err
  65. }
  66. return &Node{
  67. config: *c,
  68. inputCh: make(chan *hub.Message, defaultChanSize),
  69. genericHubCh: make(chan *hub.Message, defaultChanSize),
  70. seed: 0,
  71. }, nil
  72. }
  73. // Ledger return the ledger which uses the node
  74. // connection to broadcast messages
  75. func (e *Node) Ledger() (*blockchain.Ledger, error) {
  76. e.Lock()
  77. defer e.Unlock()
  78. if e.ledger != nil {
  79. return e.ledger, nil
  80. }
  81. mw, err := e.messageWriter()
  82. if err != nil {
  83. return nil, err
  84. }
  85. e.ledger = blockchain.New(mw, e.config.Store)
  86. return e.ledger, nil
  87. }
  88. // Start joins the node over the p2p network
  89. func (e *Node) Start(ctx context.Context) error {
  90. ledger, err := e.Ledger()
  91. if err != nil {
  92. return err
  93. }
  94. // Set the handler when we receive messages
  95. // The ledger needs to read them and update the internal blockchain
  96. e.config.Handlers = append(e.config.Handlers, ledger.Update)
  97. e.config.Logger.Info("Starting EdgeVPN network")
  98. // Startup libp2p network
  99. err = e.startNetwork(ctx)
  100. if err != nil {
  101. return err
  102. }
  103. // Send periodically messages to the channel with our blockchain content
  104. ledger.Syncronizer(ctx, e.config.LedgerSyncronizationTime)
  105. // Start eventual declared NetworkServices
  106. for _, s := range e.config.NetworkServices {
  107. err := s(ctx, e.config, e, ledger)
  108. if err != nil {
  109. return err
  110. }
  111. }
  112. return nil
  113. }
  114. // messageWriter returns a new MessageWriter bound to the edgevpn instance
  115. // with the given options
  116. func (e *Node) messageWriter(opts ...hub.MessageOption) (*messageWriter, error) {
  117. mess := &hub.Message{}
  118. mess.Apply(opts...)
  119. return &messageWriter{
  120. c: e.config,
  121. input: e.inputCh,
  122. mess: mess,
  123. }, nil
  124. }
  125. func (e *Node) startNetwork(ctx context.Context) error {
  126. e.config.Logger.Debug("Generating host data")
  127. host, err := e.genHost(ctx)
  128. if err != nil {
  129. e.config.Logger.Error(err.Error())
  130. return err
  131. }
  132. e.host = host
  133. ledger, err := e.Ledger()
  134. if err != nil {
  135. return err
  136. }
  137. for pid, strh := range e.config.StreamHandlers {
  138. host.SetStreamHandler(pid.ID(), network.StreamHandler(strh(e, ledger)))
  139. }
  140. e.config.Logger.Info("Node ID:", host.ID())
  141. e.config.Logger.Info("Node Addresses:", host.Addrs())
  142. // Hub rotates within sealkey interval.
  143. // this time length should be enough to make room for few block exchanges. This is ideally on minutes (10, 20, etc. )
  144. // it makes sure that if a bruteforce is attempted over the encrypted messages, the real key is not exposed.
  145. e.MessageHub = hub.NewHub(e.config.RoomName, e.config.MaxMessageSize, e.config.SealKeyLength, e.config.SealKeyInterval)
  146. for _, sd := range e.config.ServiceDiscovery {
  147. if err := sd.Run(e.config.Logger, ctx, host); err != nil {
  148. e.config.Logger.Fatal(err)
  149. }
  150. }
  151. go e.handleEvents(ctx, e.inputCh, e.MessageHub, e.config.Handlers, true)
  152. go e.MessageHub.Start(ctx, host)
  153. // If generic hub is enabled one is created separately with a set of generic channel handlers associated with.
  154. // note peergating is disabled in order to freely exchange messages that can be used for authentication or for other public means.
  155. if e.config.GenericHub {
  156. e.GenericHub = hub.NewHub(fmt.Sprintf("%s-generic", e.config.RoomName), e.config.MaxMessageSize, e.config.SealKeyLength, e.config.SealKeyInterval)
  157. go e.handleEvents(ctx, e.genericHubCh, e.GenericHub, e.config.GenericChannelHandler, false)
  158. go e.GenericHub.Start(ctx, host)
  159. }
  160. e.config.Logger.Debug("Network started")
  161. return nil
  162. }
  163. // PublishMessage publishes a message to the generic channel (if enabled)
  164. // See GenericChannelHandlers(..) to attach handlers to receive messages from this channel.
  165. func (e *Node) PublishMessage(m *hub.Message) error {
  166. if !e.config.GenericHub {
  167. return fmt.Errorf("generic hub disabled")
  168. }
  169. e.genericHubCh <- m
  170. return nil
  171. }