-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode_test.go
401 lines (351 loc) · 12.8 KB
/
node_test.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package btcregtest
import (
"bytes"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/rpcclient"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/jfixby/btcharness"
"github.com/jfixby/coinharness"
"testing"
"time"
)
func TestGetBestBlock(t *testing.T) {
// Skip tests when running with -short
//if testing.Short() {
// t.Skip("Skipping RPC harness tests in short mode")
//}
r := ObtainHarness(mainHarnessName)
_, prevbestHeight, err := r.NodeRPCClient().GetBestBlock()
if err != nil {
t.Fatalf("Call to `getbestblock` failed: %v", err)
}
// Create a new block connecting to the current tip.
generatedBlockHashes, err := r.NodeRPCClient().Generate(1)
if err != nil {
t.Fatalf("Unable to generate block: %v", err)
}
bestHash, bestHeight, err := r.NodeRPCClient().GetBestBlock()
if err != nil {
t.Fatalf("Call to `getbestblock` failed: %v", err)
}
// Hash should be the same as the newly submitted block.
if !bytes.Equal(bestHash.(*chainhash.Hash)[:], generatedBlockHashes[0].(*chainhash.Hash)[:]) {
t.Fatalf("Block hashes do not match. Returned hash %v, wanted "+
"hash %v", bestHash, generatedBlockHashes[0].(*chainhash.Hash)[:])
}
// Block height should now reflect newest height.
if bestHeight != prevbestHeight+1 {
t.Fatalf("Block heights do not match. Got %v, wanted %v",
bestHeight, prevbestHeight+1)
}
}
func TestGetBlockCount(t *testing.T) {
// Skip tests when running with -short
//if testing.Short() {
// t.Skip("Skipping RPC harness tests in short mode")
//}
r := ObtainHarness(mainHarnessName)
// Save the current count.
currentCount, err := r.NodeRPCClient().GetBlockCount()
if err != nil {
t.Fatalf("Unable to get block count: %v", err)
}
if _, err := r.NodeRPCClient().Generate(1); err != nil {
t.Fatalf("Unable to generate block: %v", err)
}
// Count should have increased by one.
newCount, err := r.NodeRPCClient().GetBlockCount()
if err != nil {
t.Fatalf("Unable to get block count: %v", err)
}
if newCount != currentCount+1 {
t.Fatalf("Block count incorrect. Got %v should be %v",
newCount, currentCount+1)
}
}
func TestGetBlockHash(t *testing.T) {
r := ObtainHarness(mainHarnessName)
// Create a new block connecting to the current tip.
generatedBlockHashes, err := r.NodeRPCClient().Generate(1)
if err != nil {
t.Fatalf("Unable to generate block: %v", err)
}
info, err := r.NodeRPCClient().Internal().(*rpcclient.Client).GetInfo()
if err != nil {
t.Fatalf("call to getinfo cailed: %v", err)
}
blockHash, err := r.NodeRPCClient().Internal().(*rpcclient.Client).GetBlockHash(int64(info.Blocks))
if err != nil {
t.Fatalf("Call to `getblockhash` failed: %v", err)
}
// Block hashes should match newly created block.
if !bytes.Equal(generatedBlockHashes[0].(*chainhash.Hash)[:], blockHash[:]) {
t.Fatalf("Block hashes do not match. Returned hash %v, wanted "+
"hash %v", blockHash, generatedBlockHashes[0].(*chainhash.Hash)[:])
}
}
func TestConnectNode(t *testing.T) {
r := ObtainHarness(mainHarnessName)
// Create a fresh test harness.
harness := testSetup.Regnet0.NewInstance(t.Name()).(*coinharness.Harness)
defer testSetup.Regnet0.Dispose(harness)
// Establish a p2p connection from our new local harness to the main
// harness.
if err := coinharness.ConnectNode(harness, r, rpcclient.ANAdd); err != nil {
t.Fatalf("unable to connect local to main harness: %v", err)
}
// The main harness should show up in our local harness' peer's list,
// and vice verse.
coinharness.AssertConnectedTo(t, harness, r)
}
func TestJoin(t *testing.T) {
checkJoinBlocks(t)
checkJoinMempools(t)
}
func checkJoinBlocks(t *testing.T) {
r := ObtainHarness(mainHarnessName)
// Create a second harness with only the genesis block so it is behind
// the main harness.
h := testSetup.Regnet0.NewInstance("checkJoinBlocks").(*coinharness.Harness)
defer testSetup.Regnet0.Dispose(h)
nodeSlice := []*coinharness.Harness{r, h}
blocksSynced := make(chan struct{})
go func() {
if err := coinharness.JoinNodes("", nodeSlice, coinharness.Blocks); err != nil {
t.Fatalf("unable to join node on blocks: %v", err)
}
blocksSynced <- struct{}{}
}()
// This select case should fall through to the default as the goroutine
// should be blocked on the JoinNodes calls.
select {
case <-blocksSynced:
t.Fatalf("blocks detected as synced yet local harness is behind")
default:
}
// Connect the local harness to the main harness which will sync the
// chains.
if err := coinharness.ConnectNode(h, r, rpcclient.ANAdd); err != nil {
t.Fatalf("unable to connect harnesses: %v", err)
}
// Select once again with a special timeout case after 1 minute. The
// goroutine above should now be blocked on sending into the unbuffered
// channel. The send should immediately succeed. In order to avoid the
// test hanging indefinitely, a 1 minute timeout is in place.
select {
case <-blocksSynced:
// fall through
case <-time.After(time.Minute):
t.Fatalf("blocks never detected as synced")
}
}
// TestJoinMempools must be executed after the TestJoinBlocks
func checkJoinMempools(t *testing.T) {
r := ObtainHarness(mainHarnessName)
// Assert main test harness has no transactions in its mempool.
pooledHashes, err := r.NodeRPCClient().GetRawMempool("")
if err != nil {
t.Fatalf("unable to get mempool for main test harness: %v", err)
}
if len(pooledHashes) != 0 {
t.Fatal("main test harness mempool not empty")
}
// Create a local test harness with only the genesis block. The nodes
// will be synced below so the same transaction can be sent to both
// nodes without it being an orphan.
// Create a fresh test harness.
h := testSetup.Regnet0.NewInstance("checkJoinMempools").(*coinharness.Harness)
defer testSetup.Regnet0.Dispose(h)
nodeSlice := []*coinharness.Harness{r, h}
// Both mempools should be considered synced as they are empty.
// Therefore, this should return instantly.
if err := coinharness.JoinNodes("", nodeSlice, coinharness.Mempools); err != nil {
t.Fatalf("unable to join node on mempools: %v", err)
}
// Generate a coinbase spend to a new address within the main harness'
// mempool.
addr, err := r.Wallet.NewAddress(nil)
if err != nil {
t.Fatalf("unable to generate address: %v", err)
}
addrScript, err := txscript.PayToAddrScript(addr.Internal().(btcutil.Address))
if err != nil {
t.Fatalf("unable to generate pkscript to addr: %v", err)
}
output := wire.NewTxOut(5e8, addrScript)
ctargs := &coinharness.CreateTransactionArgs{
Outputs: []coinharness.OutputTx{&btcharness.OutputTx{output}},
FeeRate: 10,
}
testTx, err := r.Wallet.CreateTransaction(ctargs)
if err != nil {
t.Fatalf("coinbase spend failed: %v", err)
}
if _, err := r.NodeRPCClient().SendRawTransaction(testTx, true); err != nil {
t.Fatalf("send transaction failed: %v", err)
}
// Wait until the transaction shows up to ensure the two mempools are
// not the same.
harnessSynced := make(chan struct{})
go func() {
for {
poolHashes, err := r.NodeRPCClient().GetRawMempool("")
if err != nil {
t.Fatalf("failed to retrieve harness mempool: %v", err)
}
if len(poolHashes) > 0 {
break
}
time.Sleep(time.Millisecond * 100)
}
harnessSynced <- struct{}{}
}()
select {
case <-harnessSynced:
case <-time.After(time.Minute):
t.Fatalf("harness node never received transaction")
}
// This select case should fall through to the default as the goroutine
// should be blocked on the JoinNodes call.
poolsSynced := make(chan struct{})
go func() {
if err := coinharness.JoinNodes("", nodeSlice, coinharness.Mempools); err != nil {
t.Fatalf("unable to join node on mempools: %v", err)
}
poolsSynced <- struct{}{}
}()
select {
case <-poolsSynced:
t.Fatalf("mempools detected as synced yet harness has a new tx")
default:
}
// Establish an outbound connection from the local harness to the main
// harness and wait for the chains to be synced.
if err := coinharness.ConnectNode(h, r, rpcclient.ANAdd); err != nil {
t.Fatalf("unable to connect harnesses: %v", err)
}
if err := coinharness.JoinNodes("", nodeSlice, coinharness.Blocks); err != nil {
t.Fatalf("unable to join node on blocks: %v", err)
}
// Send the transaction to the local harness which will result in synced
// mempools.
if _, err := h.NodeRPCClient().SendRawTransaction(testTx, true); err != nil {
t.Fatalf("send transaction failed: %v", err)
}
// Select once again with a special timeout case after 1 minute. The
// goroutine above should now be blocked on sending into the unbuffered
// channel. The send should immediately succeed. In order to avoid the
// test hanging indefinitely, a 1 minute timeout is in place.
select {
case <-poolsSynced:
// fall through
case <-time.After(time.Minute):
t.Fatalf("mempools never detected as synced")
}
}
func TestMemWalletLockedOutputs(t *testing.T) {
r := ObtainHarness(mainHarnessName)
// Obtain the initial balance of the wallet at this point.
startingBalance := coinharness.GetBalance(t, r.Wallet)
// First, create a signed transaction spending some outputs.
addr, err := r.Wallet.NewAddress(nil)
if err != nil {
t.Fatalf("unable to generate new address: %v", err)
}
pkScript, err := txscript.PayToAddrScript(addr.Internal().(btcutil.Address))
if err != nil {
t.Fatalf("unable to create script: %v", err)
}
outputAmt := btcutil.Amount(50 * btcutil.SatoshiPerBitcoin)
output := wire.NewTxOut(int64(outputAmt), pkScript)
ctargs := &coinharness.CreateTransactionArgs{
Outputs: []coinharness.OutputTx{&btcharness.OutputTx{output}},
FeeRate: 10,
}
tx, err := r.Wallet.CreateTransaction(ctargs)
if err != nil {
t.Fatalf("unable to create transaction: %v", err)
}
// The current wallet balance should now be at least 50 BTC less
// (accounting for fees) than the period balance
currentBalance, err := r.Wallet.GetBalance("")
if err != nil {
t.Fatalf("unable to get balance: %v", err)
}
if !(currentBalance.TotalSpendable.(float64) <= startingBalance.TotalSpendable.(float64)-outputAmt.ToBTC()) {
t.Fatalf("spent outputs not locked: previous balance %v, "+
"current balance %v", startingBalance, currentBalance)
}
// Now unlocked all the spent inputs within the unbroadcast signed
// transaction. The current balance should now be exactly that of the
// starting balance.
txin := tx.TxIn()
inpts := make([]coinharness.InputTx, len(txin))
for i, j := range txin {
inpts[i] = j
}
r.Wallet.UnlockOutputs(inpts)
currentBalance, err = r.Wallet.GetBalance("")
if err != nil {
t.Fatalf("unable to get balance: %v", err)
}
if currentBalance.TotalSpendable != startingBalance.TotalSpendable {
t.Fatalf("current and starting balance should now match: "+
"expected %v, got %v", startingBalance, currentBalance)
}
}
func TestP2PConnect(t *testing.T) {
r := ObtainHarness(mainHarnessName)
// Create a fresh test harness.
harness := testSetup.Regnet25.NewInstance("TestP2PConnect").(*coinharness.Harness)
defer testSetup.Regnet25.Dispose(harness)
// Establish a p2p connection from our new local harness to the main
// harness.
if err := coinharness.ConnectNode(harness, r, rpcclient.ANAdd); err != nil {
t.Fatalf("unable to connect local to main harness: %v", err)
}
// The main harness should show up in our local harness' peer's list,
// and vice verse.
coinharness.AssertConnectedTo(t, harness, r)
}
func TestMemWalletReorg(t *testing.T) {
r := ObtainHarness(mainHarnessName)
// Create a fresh h, we'll be using the main h to force a
// re-org on this local h.
h := testSetup.Regnet5.NewInstance(t.Name() + ".4").(*coinharness.Harness)
defer testSetup.Regnet5.Dispose(h)
h.Wallet.Sync(testSetup.Regnet5.NumMatureOutputs)
// The internal wallet of this h should now have 250 BTC.
expectedBalance := btcutil.Amount(250 * btcutil.SatoshiPerBitcoin)
walletBalance, err := r.Wallet.GetBalance("")
if err != nil {
t.Fatalf("unable to get balance: %v", err)
}
if expectedBalance != walletBalance.TotalSpendable {
t.Fatalf("wallet balance incorrect: expected %v, got %v",
expectedBalance, walletBalance)
}
// Now connect this local h to the main h then wait for
// their chains to synchronize.
if err := coinharness.ConnectNode(h, r, rpcclient.ANAdd); err != nil {
t.Fatalf("unable to connect harnesses: %v", err)
}
nodeSlice := []*coinharness.Harness{r, h}
if err := coinharness.JoinNodes("", nodeSlice, coinharness.Blocks); err != nil {
t.Fatalf("unable to join node on blocks: %v", err)
}
// The original wallet should now have a balance of 0 BTC as its entire
// chain should have been decimated in favor of the main h'
// chain.
expectedBalance = btcutil.Amount(0)
walletBalance, err = r.Wallet.GetBalance("")
if err != nil {
t.Fatalf("unable to get balance: %v", err)
}
if expectedBalance != walletBalance.TotalSpendable {
t.Fatalf("wallet balance incorrect: expected %v, got %v",
expectedBalance, walletBalance)
}
}