-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
288 lines (264 loc) · 7.58 KB
/
connection.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// Copyright 2024 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ouroboros_mock
import (
"bytes"
"fmt"
"net"
"reflect"
"sync"
"time"
"github.com/blinklabs-io/gouroboros/cbor"
"github.com/blinklabs-io/gouroboros/muxer"
)
// ProtocolRole is an enum of the protocol roles
type ProtocolRole uint
// Protocol roles
const (
ProtocolRoleNone ProtocolRole = 0 // Default (invalid) protocol role
ProtocolRoleClient ProtocolRole = 1 // Client protocol role
ProtocolRoleServer ProtocolRole = 2 // Server protocol role
)
// Connection mocks an Ouroboros connection
type Connection struct {
mockConn net.Conn
conn net.Conn
conversation []ConversationEntry
muxer *muxer.Muxer
muxerRecvChan chan *muxer.Segment
doneChan chan any
onceClose sync.Once
errorChan chan error
}
// NewConnection returns a new Connection with the provided conversation entries
func NewConnection(
protocolRole ProtocolRole,
conversation []ConversationEntry,
) net.Conn {
c := &Connection{
conversation: conversation,
doneChan: make(chan any),
errorChan: make(chan error, 1),
}
c.conn, c.mockConn = net.Pipe()
// Start a muxer on the mocked side of the connection
c.muxer = muxer.New(c.mockConn)
// The muxer is for the opposite end of the connection, so we flip the protocol role
muxerProtocolRole := muxer.ProtocolRoleResponder
if protocolRole == ProtocolRoleServer {
muxerProtocolRole = muxer.ProtocolRoleInitiator
}
// We use ProtocolUnknown to catch all inbound messages when no other protocols are registered
_, c.muxerRecvChan, _ = c.muxer.RegisterProtocol(
muxer.ProtocolUnknown,
muxerProtocolRole,
)
c.muxer.Start()
// Start async muxer error handler
go func() {
err, ok := <-c.muxer.ErrorChan()
if !ok {
return
}
c.errorChan <- fmt.Errorf("muxer error: %w", err)
c.Close()
}()
// Start async conversation handler
go c.asyncLoop()
return c
}
func (c *Connection) ErrorChan() <-chan error {
return c.errorChan
}
// Read provides a proxy to the client-side connection's Read function. This is needed to satisfy the net.Conn interface
func (c *Connection) Read(b []byte) (n int, err error) {
return c.conn.Read(b)
}
// Write provides a proxy to the client-side connection's Write function. This is needed to satisfy the net.Conn interface
func (c *Connection) Write(b []byte) (n int, err error) {
return c.conn.Write(b)
}
// Close closes both sides of the connection. This is needed to satisfy the net.Conn interface
func (c *Connection) Close() error {
var retErr error
c.onceClose.Do(func() {
close(c.doneChan)
c.muxer.Stop()
if err := c.conn.Close(); err != nil {
retErr = err
return
}
if err := c.mockConn.Close(); err != nil {
retErr = err
return
}
})
return retErr
}
// LocalAddr provides a proxy to the client-side connection's LocalAddr function. This is needed to satisfy the net.Conn interface
func (c *Connection) LocalAddr() net.Addr {
return MockAddr{
addr: fmt.Sprintf("mock-local:%p", c),
}
}
// RemoteAddr provides a proxy to the client-side connection's RemoteAddr function. This is needed to satisfy the net.Conn interface
func (c *Connection) RemoteAddr() net.Addr {
return MockAddr{
addr: fmt.Sprintf("mock-remote:%p", c),
}
}
// SetDeadline provides a proxy to the client-side connection's SetDeadline function. This is needed to satisfy the net.Conn interface
func (c *Connection) SetDeadline(t time.Time) error {
return c.conn.SetDeadline(t)
}
// SetReadDeadline provides a proxy to the client-side connection's SetReadDeadline function. This is needed to satisfy the net.Conn interface
func (c *Connection) SetReadDeadline(t time.Time) error {
return c.conn.SetReadDeadline(t)
}
// SetWriteDeadline provides a proxy to the client-side connection's SetWriteDeadline function. This is needed to satisfy the net.Conn interface
func (c *Connection) SetWriteDeadline(t time.Time) error {
return c.conn.SetWriteDeadline(t)
}
func (c *Connection) sendError(err error) {
select {
case c.errorChan <- err:
_ = c.Close()
default:
}
}
func (c *Connection) asyncLoop() {
defer func() {
close(c.errorChan)
}()
for _, entry := range c.conversation {
select {
case <-c.doneChan:
return
default:
}
switch entry := entry.(type) {
case ConversationEntryInput:
if err := c.processInputEntry(entry); err != nil {
c.sendError(fmt.Errorf("input error: %w", err))
return
}
case ConversationEntryOutput:
if err := c.processOutputEntry(entry); err != nil {
c.sendError(fmt.Errorf("output error: %w", err))
return
}
case ConversationEntryClose:
c.Close()
case ConversationEntrySleep:
time.Sleep(entry.Duration)
default:
c.sendError(
fmt.Errorf(
"unknown conversation entry type: %T: %#v",
entry,
entry,
),
)
return
}
}
}
func (c *Connection) processInputEntry(entry ConversationEntryInput) error {
// Wait for segment to be received from muxer
segment, ok := <-c.muxerRecvChan
if !ok {
return nil
}
if segment.GetProtocolId() != entry.ProtocolId {
return fmt.Errorf(
"input message protocol ID did not match expected value: expected %d, got %d",
entry.ProtocolId,
segment.GetProtocolId(),
)
}
if segment.IsResponse() != entry.IsResponse {
return fmt.Errorf(
"input message response flag did not match expected value: expected %v, got %v",
entry.IsResponse,
segment.IsResponse(),
)
}
// Determine message type
msgType, err := cbor.DecodeIdFromList(segment.Payload)
if err != nil {
return fmt.Errorf("decode error: %s", err)
}
if entry.Message != nil {
// Create Message object from CBOR
msg, err := entry.MsgFromCborFunc(uint(msgType), segment.Payload)
if err != nil {
return fmt.Errorf("message from CBOR error: %s", err)
}
if msg == nil {
return fmt.Errorf("received unknown message type: %d", msgType)
}
// Compare received message to expected message, excluding the cbor content
//
// As changing the CBOR of the expected message is not thread-safe, we instead clear the
// CBOR of the received message
msg.SetCbor(nil)
if !reflect.DeepEqual(msg, entry.Message) {
return fmt.Errorf(
"parsed message does not match expected value: got %#v, expected %#v",
msg,
entry.Message,
)
}
} else {
if entry.MessageType == uint(msgType) {
return nil
}
return fmt.Errorf("input message is not of expected type: expected %d, got %d", entry.MessageType, msgType)
}
return nil
}
func (c *Connection) processOutputEntry(entry ConversationEntryOutput) error {
payloadBuf := bytes.NewBuffer(nil)
for _, msg := range entry.Messages {
// Get raw CBOR from message
data := msg.Cbor()
// If message has no raw CBOR, encode the message
if data == nil {
var err error
data, err = cbor.Encode(msg)
if err != nil {
return err
}
}
payloadBuf.Write(data)
}
segment := muxer.NewSegment(
entry.ProtocolId,
payloadBuf.Bytes(),
entry.IsResponse,
)
if err := c.muxer.Send(segment); err != nil {
return err
}
return nil
}
type MockAddr struct {
addr string
}
func (m MockAddr) Network() string {
return "mock"
}
func (m MockAddr) String() string {
return m.addr
}