-
Notifications
You must be signed in to change notification settings - Fork 0
/
mix.go
215 lines (175 loc) · 4.97 KB
/
mix.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package main
import (
"context"
"fmt"
"math"
"math/rand/v2"
"strings"
"sync"
"time"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/core/peerstore"
"github.com/libp2p/go-msgio/pbio"
"github.com/multiformats/go-multiaddr"
)
const customProtocolID = "/custom/1.0.0"
type CustomProtocol struct {
host host.Host
mutex sync.Mutex
hasConn bool
origin multiaddr.Multiaddr
parentID peer.ID
C chan *Payload
listOfCustomNodes []multiaddr.Multiaddr
}
func NewCustomProtocol(host host.Host, listOfCustomNodes []multiaddr.Multiaddr) (*CustomProtocol, error) {
for _, x := range listOfCustomNodes {
peerID, err := GetPeerID(x)
if err != nil {
return nil, err
}
host.Peerstore().AddAddrs(peerID, []multiaddr.Multiaddr{x}, peerstore.PermanentAddrTTL)
}
return &CustomProtocol{
host: host,
C: make(chan *Payload),
listOfCustomNodes: listOfCustomNodes,
}, nil
}
func (m *CustomProtocol) Conn() *CustomConn {
for {
if m.hasConn {
ctx, cancel := context.WithCancel(context.Background())
return &CustomConn{
ctx: ctx,
cancel: cancel,
myCustomNode: m,
remotePeer: m.origin,
}
}
time.Sleep(100 * time.Millisecond)
}
}
func (m *CustomProtocol) setParentID(p peer.ID) {
m.parentID = p
}
func (m *CustomProtocol) GetRandomPath(destination multiaddr.Multiaddr) []string {
if m.parentID == "" {
panic("parentID not set")
}
rand.Shuffle(len(m.listOfCustomNodes), func(i, j int) {
m.listOfCustomNodes[i], m.listOfCustomNodes[j] = m.listOfCustomNodes[j], m.listOfCustomNodes[i]
})
fmt.Println("DESTINATION", destination)
// Remove both the origin and destination
var filteredSlice []multiaddr.Multiaddr
destinationPeerIdStr, _ := destination.ValueForProtocol(P_CUSTOM)
destinationPeerId, _ := peer.Decode(destinationPeerIdStr)
for _, v := range m.listOfCustomNodes {
vpeerID, _ := GetPeerID(v)
if vpeerID == m.host.ID() || vpeerID == destinationPeerId {
continue
}
filteredSlice = append(filteredSlice, v)
}
// Return random 3 nodes
n := 1
if len(filteredSlice) < n {
panic("More nodes required!!!")
}
destinationStrParts := strings.Split(destination.String(), "/p2p")
destinationStr := strings.Replace(destinationStrParts[0], "/custom", "/p2p", -1)
destinationMa, _ := multiaddr.NewMultiaddr(destinationStr)
resultMa := append(filteredSlice[:n], destinationMa)
result := make([]string, len(resultMa))
for i, addr := range resultMa {
result[i] = addr.String()
}
fmt.Println("THE RANDOM PATH: ", result)
return result
}
func (m *CustomProtocol) Start(ctx context.Context) {
m.host.SetStreamHandler(customProtocolID, func(s network.Stream) {
fmt.Println("I am ", m.host.ID(), "and received request from ", s.Conn().RemotePeer())
reader := pbio.NewDelimitedReader(s, math.MaxInt32)
message := &Message{}
reader.ReadMsg(message)
if len(message.Path) > 0 {
nextNode := message.Path[0]
nextNodeMA, err := multiaddr.NewMultiaddr(nextNode)
if err != nil {
fmt.Println("ERROR building peerID!!!", err)
s.Reset()
return
}
peerID, err := GetPeerID(nextNodeMA)
if err != nil {
fmt.Println("ERROR obtaining peerID!!!", err)
s.Reset()
return
}
m.host.Peerstore().AddAddr(peerID, nextNodeMA, peerstore.PermanentAddrTTL)
message := &Message{
Path: message.Path[1:], // Remove current node from the path
Payload: message.Payload,
}
err = m.Send(ctx, nextNodeMA.String(), message)
if err != nil {
fmt.Println("ERROR sending message", err)
s.Reset()
return
}
} else {
fmt.Println("PUSHING TO CHANNEL IN", m.host.ID(), string(message.Payload.Payload))
m.mutex.Lock()
if !m.hasConn {
m.origin, _ = multiaddr.NewMultiaddr(message.Payload.Origin)
m.hasConn = true
}
m.mutex.Unlock()
m.C <- message.Payload
fmt.Println("PUSHED TO CHANNEL IN", m.host.ID())
}
s.Close()
})
}
func (m *CustomProtocol) Write(stream network.Stream, message *Message) error {
writer := pbio.NewDelimitedWriter(stream)
err := writer.WriteMsg(message)
if err != nil {
stream.Reset()
return err
}
return nil
}
func (m *CustomProtocol) Send(ctx context.Context, nextHopStr string, message *Message) error {
nextHop, err := multiaddr.NewMultiaddr(nextHopStr)
if err != nil {
return err
}
peerID, err := GetPeerID(nextHop)
if err != nil {
return err
}
fmt.Println("Send: I am", m.host.ID())
fmt.Println("Send: the next hop:", nextHop)
stream, err := m.host.NewStream(ctx, peerID, customProtocolID)
if err != nil {
return nil
}
writer := pbio.NewDelimitedWriter(stream)
message = &Message{
Path: message.Path, // Remove current node from the path
Payload: message.Payload,
}
fmt.Println("Send: Now writing msg to", peerID)
err = writer.WriteMsg(message)
if err != nil {
stream.Reset()
return err
}
fmt.Println("Closing in ", m.host.ID())
return stream.Close()
}