-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtest_nodes.go
More file actions
309 lines (250 loc) · 7.26 KB
/
test_nodes.go
File metadata and controls
309 lines (250 loc) · 7.26 KB
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package bitcoin_reader
import (
"context"
"fmt"
"net"
"sync"
"sync/atomic"
"time"
"github.com/tokenized/bitcoin_reader/headers"
"github.com/tokenized/logger"
"github.com/tokenized/pkg/bitcoin"
"github.com/tokenized/pkg/wire"
"github.com/tokenized/threads"
"github.com/pkg/errors"
)
const (
TestUserAgent = "TestAgent/1"
TestNet = bitcoin.MainNet
)
type MockNode struct {
Name string
InternalNode *BitcoinNode
ExternalNode *MockExternalNode
}
func NewMockNode(name string, config *Config, headers *headers.Repository,
peers PeerRepository, txManager *TxManager) *MockNode {
result := &MockNode{
Name: name,
InternalNode: NewBitcoinNode(name, TestUserAgent, config, headers, peers),
ExternalNode: NewMockExternalNode(name, headers, 500),
}
result.InternalNode.SetTxManager(txManager)
return result
}
func (n *MockNode) Run(ctx context.Context, interrupt <-chan interface{}) error {
// Create mock connection
incomingConn, externalConn := net.Pipe()
n.InternalNode.mockConnect(ctx, incomingConn)
n.ExternalNode.SetConnection(externalConn)
var wait sync.WaitGroup
internalThread, internalComplete := threads.NewInterruptableThreadComplete(fmt.Sprintf("%s: Internal", n.Name),
n.InternalNode.run, &wait)
externalThread, externalComplete := threads.NewInterruptableThreadComplete(fmt.Sprintf("%s: External", n.Name),
n.ExternalNode.Run, &wait)
internalThread.Start(ctx)
externalThread.Start(ctx)
select {
case internalErr := <-internalComplete:
logger.Fatal(ctx, "[%s] Internal node failed : %s", n.Name, internalErr)
case externalErr := <-externalComplete:
logger.Fatal(ctx, "[%s] External node failed : %s", n.Name, externalErr)
case <-interrupt:
}
internalThread.Stop(ctx)
externalThread.Stop(ctx)
wait.Wait()
return nil
}
type MockExternalNode struct {
connection net.Conn
isClosed atomic.Value
Name string
Txs []*wire.MsgTx
TxRetentionCount int
TxLock sync.Mutex
headers *headers.Repository
outgoingMsgChannel chan wire.Message
}
func NewMockExternalNode(name string, headers *headers.Repository,
txRetentionCount int) *MockExternalNode {
return &MockExternalNode{
Name: name,
TxRetentionCount: txRetentionCount,
headers: headers,
outgoingMsgChannel: make(chan wire.Message, 100),
}
}
func (n *MockExternalNode) ProvideTx(tx *wire.MsgTx) error {
n.TxLock.Lock()
n.Txs = append(n.Txs, tx)
if len(n.Txs) > n.TxRetentionCount {
overage := len(n.Txs) - n.TxRetentionCount
n.Txs = n.Txs[overage:]
}
n.TxLock.Unlock()
// TODO Remove transactions if they aren't immediately requested with a get data message. --ce
// Send tx inventory.
msg := &wire.MsgInv{
InvList: []*wire.InvVect{
{
Type: wire.InvTypeTx,
Hash: *tx.TxHash(),
},
},
}
if err := n.sendMessage(msg); err != nil {
return errors.Wrap(err, "send message")
}
return nil
}
func (n *MockExternalNode) SetConnection(connection net.Conn) {
n.connection = connection
n.isClosed.Store(false)
}
func (n *MockExternalNode) Run(ctx context.Context, interrupt <-chan interface{}) error {
var wait sync.WaitGroup
// Listen for requests from connection and respond.
handleThread, handleComplete := threads.NewUninterruptableThreadComplete(fmt.Sprintf("%s: External: handle", n.Name),
n.handleMessages, &wait)
sendThread, sendComplete := threads.NewUninterruptableThreadComplete(fmt.Sprintf("%s: External: send", n.Name),
func(ctx context.Context) error {
return n.sendMessages(ctx)
}, &wait)
handleThread.Start(ctx)
sendThread.Start(ctx)
var resultErr error
select {
case err := <-sendComplete:
resultErr = errors.Wrap(err, "send")
case err := <-handleComplete:
resultErr = errors.Wrap(err, "handle")
}
logger.Info(ctx, "Stopping External: %s", n.Name)
n.isClosed.Store(true)
n.connection.Close()
close(n.outgoingMsgChannel)
wait.Wait()
return resultErr
}
func (n *MockExternalNode) handleMessages(ctx context.Context) error {
version := buildVersionMsg("", TestUserAgent, n.headers.Height(), true)
if err := n.sendMessage(version); err != nil {
return errors.Wrap(err, "send version")
}
for {
if n.isClosed.Load().(bool) {
return nil
}
if msg, _, err := wire.ReadMessage(n.connection, wire.ProtocolVersion,
wire.BitcoinNet(TestNet)); err != nil {
if typeError, ok := errors.Cause(err).(*wire.MessageError); ok {
if typeError.Type == wire.MessageErrorUnknownCommand {
continue
}
if typeError.Type == wire.MessageErrorConnectionClosed {
return nil
}
}
return errors.Wrap(err, "read")
} else {
if err := n.handleMessage(ctx, msg); err != nil {
return errors.Wrap(err, "handle")
}
}
}
}
func (n *MockExternalNode) handleMessage(ctx context.Context, msg wire.Message) error {
switch message := msg.(type) {
case *wire.MsgVersion:
if err := n.sendMessage(&wire.MsgVerAck{}); err != nil {
return errors.Wrap(err, "send ver ack")
}
case *wire.MsgVerAck:
case *wire.MsgGetHeaders:
msgHeaders := &wire.MsgHeaders{}
foundSplit := false
for _, hash := range message.BlockLocatorHashes {
if hash.Equal(&headers.MainNetRequiredHeader.PrevBlock) {
foundSplit = true
msgHeaders.AddBlockHeader(headers.MainNetRequiredHeader)
}
}
if !foundSplit {
// Find block height and send headers.
l := len(message.BlockLocatorHashes)
if l == 0 {
return errors.New("Empty block request")
}
lastHash := *message.BlockLocatorHashes[l-1]
height := n.headers.HashHeight(lastHash)
if height == -1 {
return fmt.Errorf("Header not found: %s", lastHash)
}
headers, err := n.headers.GetHeaders(ctx, height, 500)
if err != nil {
return errors.Wrap(err, "get headers")
}
if len(headers) == 0 {
return fmt.Errorf("No headers found: height %d", height)
}
for _, header := range headers {
msgHeaders.AddBlockHeader(header)
}
}
if err := n.sendMessage(msgHeaders); err != nil {
return errors.Wrap(err, "send headers")
}
case *wire.MsgGetData:
for _, inv := range message.InvList {
if inv.Type != wire.InvTypeTx {
continue
}
var tx *wire.MsgTx
n.TxLock.Lock()
for i, ltx := range n.Txs {
if ltx.TxHash().Equal(&inv.Hash) {
tx = ltx
n.Txs = append(n.Txs[:i], n.Txs[i+1:]...)
break
}
}
n.TxLock.Unlock()
if tx != nil {
if err := n.sendMessage(tx); err != nil {
return errors.Wrap(err, "send tx")
}
} else {
logger.ErrorWithFields(ctx, []logger.Field{
logger.Stringer("txid", inv.Hash),
}, "Tx not found for get data request")
}
}
}
return nil
}
func (n *MockExternalNode) sendMessage(msg wire.Message) error {
select {
case n.outgoingMsgChannel <- msg:
return nil
case <-time.After(time.Second * 10):
return errors.New("Could not add message to channel")
}
}
func (n *MockExternalNode) sendMessages(ctx context.Context) error {
for msg := range n.outgoingMsgChannel {
if n.isClosed.Load().(bool) {
return nil
}
if _, err := wire.WriteMessageN(n.connection, msg, wire.ProtocolVersion,
wire.BitcoinNet(TestNet)); err != nil {
logger.VerboseWithFields(ctx, []logger.Field{
logger.String("command", msg.Command()),
}, "Failed to send message : %s", err)
for range n.outgoingMsgChannel { // flush channel
}
return errors.Wrap(err, "write message")
}
}
return nil
}