-
Notifications
You must be signed in to change notification settings - Fork 11
/
ouroboros.go
252 lines (245 loc) · 7.55 KB
/
ouroboros.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package ouroboros
import (
"errors"
"fmt"
"github.com/cloudstruct/go-ouroboros-network/muxer"
"github.com/cloudstruct/go-ouroboros-network/protocol"
"github.com/cloudstruct/go-ouroboros-network/protocol/blockfetch"
"github.com/cloudstruct/go-ouroboros-network/protocol/chainsync"
"github.com/cloudstruct/go-ouroboros-network/protocol/handshake"
"github.com/cloudstruct/go-ouroboros-network/protocol/keepalive"
"github.com/cloudstruct/go-ouroboros-network/protocol/localstatequery"
"github.com/cloudstruct/go-ouroboros-network/protocol/localtxsubmission"
"github.com/cloudstruct/go-ouroboros-network/protocol/txsubmission"
"io"
"net"
"sync"
)
type Ouroboros struct {
conn net.Conn
networkMagic uint32
server bool
useNodeToNodeProto bool
muxer *muxer.Muxer
ErrorChan chan error
protoErrorChan chan error
handshakeFinishedChan chan interface{}
doneChan chan interface{}
closeMutex sync.Mutex
sendKeepAlives bool
delayMuxerStart bool
fullDuplex bool
// Mini-protocols
Handshake *handshake.Handshake
ChainSync *chainsync.ChainSync
chainSyncConfig *chainsync.Config
BlockFetch *blockfetch.BlockFetch
blockFetchConfig *blockfetch.Config
KeepAlive *keepalive.KeepAlive
keepAliveConfig *keepalive.Config
LocalTxSubmission *localtxsubmission.LocalTxSubmission
localTxSubmissionConfig *localtxsubmission.Config
LocalStateQuery *localstatequery.LocalStateQuery
localStateQueryConfig *localstatequery.Config
TxSubmission *txsubmission.TxSubmission
txSubmissionConfig *txsubmission.Config
}
func New(options ...OuroborosOptionFunc) (*Ouroboros, error) {
o := &Ouroboros{
protoErrorChan: make(chan error, 10),
handshakeFinishedChan: make(chan interface{}),
doneChan: make(chan interface{}),
}
// Apply provided options functions
for _, option := range options {
option(o)
}
if o.ErrorChan == nil {
o.ErrorChan = make(chan error, 10)
}
if o.conn != nil {
if err := o.setupConnection(); err != nil {
return nil, err
}
}
return o, nil
}
func (o *Ouroboros) Muxer() *muxer.Muxer {
return o.muxer
}
// Convenience function for creating a connection if you didn't provide one when
// calling New()
func (o *Ouroboros) Dial(proto string, address string) error {
conn, err := net.Dial(proto, address)
if err != nil {
return err
}
o.conn = conn
if err := o.setupConnection(); err != nil {
return err
}
return nil
}
func (o *Ouroboros) Close() error {
// We use a mutex to prevent this function from being called multiple times
// concurrently, which would cause a race condition
o.closeMutex.Lock()
defer o.closeMutex.Unlock()
// Immediately return if we're already shutting down
select {
case <-o.doneChan:
return nil
default:
}
// Close doneChan to signify that we're shutting down
close(o.doneChan)
// Gracefully stop the muxer
if o.muxer != nil {
o.muxer.Stop()
}
// Close the underlying connection
if o.conn != nil {
if err := o.conn.Close(); err != nil {
return err
}
}
// Close channels
close(o.ErrorChan)
close(o.protoErrorChan)
// We can only close a channel once, so we have to jump through a few hoops
select {
// The channel is either closed or has an item pending
case _, ok := <-o.handshakeFinishedChan:
// We successfully retrieved an item
// This will probably never happen, but it doesn't hurt to cover this case
if ok {
close(o.handshakeFinishedChan)
}
// The channel is open and has no pending items
default:
close(o.handshakeFinishedChan)
}
return nil
}
func (o *Ouroboros) setupConnection() error {
o.muxer = muxer.New(o.conn)
// Start Goroutine to pass along errors from the muxer
go func() {
select {
case <-o.doneChan:
return
case err, ok := <-o.muxer.ErrorChan:
// Break out of goroutine if muxer's error channel is closed
if !ok {
return
}
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
// Return a bare io.EOF error if error is EOF/ErrUnexpectedEOF
o.ErrorChan <- io.EOF
} else {
// Wrap error message to denote it comes from the muxer
o.ErrorChan <- fmt.Errorf("muxer error: %s", err)
}
// Close connection on muxer errors
o.Close()
}
}()
protoOptions := protocol.ProtocolOptions{
Muxer: o.muxer,
ErrorChan: o.protoErrorChan,
}
var protoVersions []uint16
if o.useNodeToNodeProto {
protoVersions = GetProtocolVersionsNtN()
protoOptions.Mode = protocol.ProtocolModeNodeToNode
} else {
protoVersions = GetProtocolVersionsNtC()
protoOptions.Mode = protocol.ProtocolModeNodeToClient
}
if o.server {
protoOptions.Role = protocol.ProtocolRoleServer
} else {
protoOptions.Role = protocol.ProtocolRoleClient
}
// Perform handshake
var handshakeVersion uint16
var handshakeFullDuplex bool
handshakeConfig := handshake.NewConfig(
handshake.WithProtocolVersions(protoVersions),
handshake.WithNetworkMagic(o.networkMagic),
handshake.WithClientFullDuplex(o.fullDuplex),
handshake.WithFinishedFunc(func(version uint16, fullDuplex bool) error {
handshakeVersion = version
handshakeFullDuplex = fullDuplex
close(o.handshakeFinishedChan)
return nil
}),
)
o.Handshake = handshake.New(protoOptions, &handshakeConfig)
if o.server {
o.Handshake.Server.Start()
} else {
o.Handshake.Client.Start()
}
// Wait for handshake completion or error
select {
case <-o.doneChan:
// Return an error if we're shutting down
return io.EOF
case err := <-o.protoErrorChan:
return err
case <-o.handshakeFinishedChan:
// This is purposely empty, but we need this case to break out when this channel is closed
}
// Provide the negotiated protocol version to the various mini-protocols
protoOptions.Version = handshakeVersion
// Drop bit used to signify NtC protocol versions
if protoOptions.Version > PROTOCOL_VERSION_NTC_FLAG {
protoOptions.Version = protoOptions.Version - PROTOCOL_VERSION_NTC_FLAG
}
// Start Goroutine to pass along errors from the mini-protocols
go func() {
err, ok := <-o.protoErrorChan
// The channel is closed, which means we're already shutting down
if !ok {
return
}
o.ErrorChan <- fmt.Errorf("protocol error: %s", err)
// Close connection on mini-protocol errors
o.Close()
}()
// Configure the relevant mini-protocols
if o.useNodeToNodeProto {
versionNtN := GetProtocolVersionNtN(handshakeVersion)
protoOptions.Mode = protocol.ProtocolModeNodeToNode
o.ChainSync = chainsync.New(protoOptions, o.chainSyncConfig)
o.BlockFetch = blockfetch.New(protoOptions, o.blockFetchConfig)
o.TxSubmission = txsubmission.New(protoOptions, o.txSubmissionConfig)
if versionNtN.EnableKeepAliveProtocol {
o.KeepAlive = keepalive.New(protoOptions, o.keepAliveConfig)
if !o.server && o.sendKeepAlives {
o.KeepAlive.Client.Start()
}
}
} else {
versionNtC := GetProtocolVersionNtC(handshakeVersion)
protoOptions.Mode = protocol.ProtocolModeNodeToClient
o.ChainSync = chainsync.New(protoOptions, o.chainSyncConfig)
o.LocalTxSubmission = localtxsubmission.New(protoOptions, o.localTxSubmissionConfig)
if versionNtC.EnableLocalQueryProtocol {
o.LocalStateQuery = localstatequery.New(protoOptions, o.localStateQueryConfig)
}
}
// Start muxer
diffusionMode := muxer.DiffusionModeInitiator
if handshakeFullDuplex {
diffusionMode = muxer.DiffusionModeInitiatorAndResponder
} else if o.server {
diffusionMode = muxer.DiffusionModeResponder
}
o.muxer.SetDiffusionMode(diffusionMode)
if !o.delayMuxerStart {
o.muxer.Start()
}
return nil
}