-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
96 lines (79 loc) · 2.32 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package ngp2p
import (
"context"
"fmt"
logging "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p-core/host"
multiplex "github.com/libp2p/go-libp2p-mplex"
yamux "github.com/libp2p/go-libp2p-yamux"
rhost "github.com/libp2p/go-libp2p/p2p/host/routed"
"github.com/libp2p/go-tcp-transport"
"github.com/ngchain/ngbiz/blockchain"
"github.com/ngchain/ngbiz/keytools"
"github.com/ngchain/ngbiz/ngp2p/broadcast"
"github.com/ngchain/ngbiz/ngp2p/wired"
"github.com/ngchain/ngbiz/ngtypes"
)
var log = logging.Logger("ngp2p")
// LocalNode is the local host on p2p network
type LocalNode struct {
host.Host // lib-p2p host
network ngtypes.Network
P2PConfig P2PConfig
*wired.Wired
*broadcast.Broadcast
}
type P2PConfig struct {
P2PKeyFile string
Network ngtypes.Network
Port int
DisableDiscovery bool
}
// InitLocalNode creates a new node with its implemented protocols.
func InitLocalNode(chain *blockchain.Chain, config P2PConfig) *LocalNode {
ctx := context.Background()
priv := keytools.GetP2PKey(config.P2PKeyFile)
transports := libp2p.ChainOptions(
libp2p.Transport(tcp.NewTCPTransport),
// libp2p.Transport(ws.New),
)
listenAddrs := libp2p.ListenAddrStrings(
fmt.Sprintf("/ip4/0.0.0.0/tcp/%d", config.Port),
fmt.Sprintf("/ip6/::/tcp/%d", config.Port),
)
muxers := libp2p.ChainOptions(
libp2p.Muxer("/yamux/1.0.0", yamux.DefaultTransport),
libp2p.Muxer("/mplex/6.7.0", multiplex.DefaultTransport),
)
localHost, err := libp2p.New(
transports,
listenAddrs,
muxers,
libp2p.Identity(priv),
getPublicRouter(config.Network),
libp2p.NATPortMap(),
libp2p.EnableAutoRelay(),
)
if err != nil {
panic(err)
}
// init
log.Warnf("P2P Listening on: /ip4/<External IP>/tcp/%d/p2p/%s \n", config.Port, localHost.ID().String())
localNode := &LocalNode{
// sub modules
Host: rhost.Wrap(localHost, p2pDHT),
network: config.Network,
Wired: wired.NewWiredProtocol(localHost, config.Network, chain),
Broadcast: broadcast.NewBroadcastProtocol(localHost, config.Network, make(chan *ngtypes.Block), make(chan *ngtypes.Tx)),
}
if !config.DisableDiscovery {
initMDNS(ctx, localHost)
activeDHT(ctx, p2pDHT, localNode)
}
return localNode
}
func (localNode *LocalNode) GoServe() {
localNode.Wired.GoServe()
localNode.Broadcast.GoServe()
}