node.go 4.7 KB

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