-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathbitcoind_common.go
More file actions
265 lines (230 loc) · 7.21 KB
/
bitcoind_common.go
File metadata and controls
265 lines (230 loc) · 7.21 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
//go:build bitcoind
// +build bitcoind
package lntest
import (
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/rpcclient"
"github.com/lightningnetwork/lnd/lntest/node"
"github.com/lightningnetwork/lnd/lntest/port"
"github.com/lightningnetwork/lnd/lntest/wait"
)
// logDirPattern is the pattern of the name of the temporary log directory.
const logDirPattern = "%s/.backendlogs"
// BitcoindBackendConfig is an implementation of the BackendConfig interface
// backed by a Bitcoind node.
type BitcoindBackendConfig struct {
rpcHost string
rpcUser string
rpcPass string
zmqBlockPath string
zmqTxPath string
p2pPort int
rpcClient *rpcclient.Client
rpcPolling bool
// minerAddr is the p2p address of the miner to connect to.
minerAddr string
}
// A compile time assertion to ensure BitcoindBackendConfig meets the
// BackendConfig interface.
var _ node.BackendConfig = (*BitcoindBackendConfig)(nil)
// GenArgs returns the arguments needed to be passed to LND at startup for
// using this node as a chain backend.
func (b BitcoindBackendConfig) GenArgs() []string {
var args []string
args = append(args, "--bitcoin.node=bitcoind")
args = append(args, fmt.Sprintf("--bitcoind.rpchost=%v", b.rpcHost))
args = append(args, fmt.Sprintf("--bitcoind.rpcuser=%v", b.rpcUser))
args = append(args, fmt.Sprintf("--bitcoind.rpcpass=%v", b.rpcPass))
if b.rpcPolling {
args = append(args, fmt.Sprintf("--bitcoind.rpcpolling"))
args = append(args,
fmt.Sprintf("--bitcoind.blockpollinginterval=10ms"))
args = append(args,
fmt.Sprintf("--bitcoind.txpollinginterval=10ms"))
} else {
args = append(args, fmt.Sprintf("--bitcoind.zmqpubrawblock=%v",
b.zmqBlockPath))
args = append(args, fmt.Sprintf("--bitcoind.zmqpubrawtx=%v",
b.zmqTxPath))
}
return args
}
// ConnectMiner is called to establish a connection to the test miner.
func (b BitcoindBackendConfig) ConnectMiner() error {
err := b.rpcClient.AddNode(b.minerAddr, rpcclient.ANOneTry)
if err != nil {
return err
}
return wait.NoError(func() error {
peerInfo, err := b.rpcClient.GetPeerInfo()
if err != nil {
return err
}
for _, peer := range peerInfo {
if strings.HasPrefix(peer.Addr, b.minerAddr) {
return nil
}
}
return fmt.Errorf("peer %s not connected", b.minerAddr)
}, wait.DefaultTimeout)
}
// DisconnectMiner is called to disconnect the miner.
func (b BitcoindBackendConfig) DisconnectMiner() error {
// `addnode remove` removes from the addnode list, but doesn't reliably
// disconnect an existing connection. Use `disconnectnode` first.
_, err := b.rpcClient.RawRequest(
"disconnectnode",
[]json.RawMessage{
[]byte(fmt.Sprintf("%q", b.minerAddr)),
},
)
if err != nil {
return err
}
_ = b.rpcClient.AddNode(b.minerAddr, rpcclient.ANRemove)
return nil
}
// Credentials returns the rpc username, password and host for the backend.
func (b BitcoindBackendConfig) Credentials() (string, string, string, error) {
return b.rpcUser, b.rpcPass, b.rpcHost, nil
}
// Name returns the name of the backend type.
func (b BitcoindBackendConfig) Name() string {
return "bitcoind"
}
// P2PAddr return bitcoin p2p ip:port.
func (b BitcoindBackendConfig) P2PAddr() (string, error) {
return fmt.Sprintf("127.0.0.1:%d", b.p2pPort), nil
}
// newBackend starts a bitcoind node with the given extra parameters and returns
// a BitcoindBackendConfig for that node.
func newBackend(miner string, netParams *chaincfg.Params, extraArgs []string,
rpcPolling bool) (*BitcoindBackendConfig, func() error, error) {
baseLogDir := fmt.Sprintf(logDirPattern, node.GetLogDir())
if netParams != &chaincfg.RegressionNetParams {
return nil, nil, fmt.Errorf("only regtest supported")
}
if err := os.MkdirAll(baseLogDir, 0700); err != nil {
return nil, nil, err
}
logFile, err := filepath.Abs(baseLogDir + "/bitcoind.log")
if err != nil {
return nil, nil, err
}
tempBitcoindDir, err := os.MkdirTemp("", "bitcoind")
if err != nil {
return nil, nil,
fmt.Errorf("unable to create temp directory: %w", err)
}
zmqBlockAddr := fmt.Sprintf("tcp://127.0.0.1:%d",
port.NextAvailablePort())
zmqTxAddr := fmt.Sprintf("tcp://127.0.0.1:%d", port.NextAvailablePort())
rpcPort := port.NextAvailablePort()
p2pPort := port.NextAvailablePort()
torBindPort := port.NextAvailablePort()
cmdArgs := []string{
"-datadir=" + tempBitcoindDir,
// Whitelist localhost to speed up relay.
"-whitelist=127.0.0.1",
"-rpcauth=weks:469e9bb14ab2360f8e226efed5ca6f" +
"d$507c670e800a95284294edb5773b05544b" +
"220110063096c221be9933c82d38e1",
fmt.Sprintf("-rpcport=%d", rpcPort),
fmt.Sprintf("-bind=127.0.0.1:%d", p2pPort),
fmt.Sprintf("-bind=127.0.0.1:%d=onion", torBindPort),
"-zmqpubrawblock=" + zmqBlockAddr,
"-zmqpubrawtx=" + zmqTxAddr,
"-debug",
"-debugexclude=libevent",
"-debuglogfile=" + logFile,
"-blockfilterindex",
"-peerblockfilters",
// Disable v2 transport since the miner is btcd, which
// doesn't support v2 yet. Without this, bitcoind
// attempts a v2 handshake that hangs for 30s before
// falling back to v1, causing test flakes whenever a
// test reconnects to the miner under a timeout.
//
// TODO: Remove once btcd supports v2 P2P transport.
"-v2transport=0",
}
cmdArgs = append(cmdArgs, extraArgs...)
bitcoind := exec.Command("bitcoind", cmdArgs...)
err = bitcoind.Start()
if err != nil {
if err := os.RemoveAll(tempBitcoindDir); err != nil {
fmt.Printf("unable to remote temp dir %v: %v",
tempBitcoindDir, err)
}
return nil, nil, fmt.Errorf("couldn't start bitcoind: %w", err)
}
cleanUp := func() error {
_ = bitcoind.Process.Kill()
_ = bitcoind.Wait()
var errStr string
// After shutting down the chain backend, we'll make a copy of
// the log file before deleting the temporary log dir.
logDestination := fmt.Sprintf(
"%s/output_bitcoind_chainbackend.log", node.GetLogDir(),
)
err := node.CopyFile(logDestination, logFile)
if err != nil {
errStr += fmt.Sprintf("unable to copy file: %v\n", err)
}
if err = os.RemoveAll(baseLogDir); err != nil {
errStr += fmt.Sprintf(
"cannot remove dir %s: %v\n", baseLogDir, err,
)
}
if err := os.RemoveAll(tempBitcoindDir); err != nil {
errStr += fmt.Sprintf(
"cannot remove dir %s: %v\n",
tempBitcoindDir, err,
)
}
if errStr != "" {
return errors.New(errStr)
}
return nil
}
// Allow process to start.
time.Sleep(1 * time.Second)
rpcHost := fmt.Sprintf("127.0.0.1:%d", rpcPort)
rpcUser := "weks"
rpcPass := "weks"
rpcCfg := rpcclient.ConnConfig{
Host: rpcHost,
User: rpcUser,
Pass: rpcPass,
DisableConnectOnNew: true,
DisableAutoReconnect: false,
DisableTLS: true,
HTTPPostMode: true,
}
client, err := rpcclient.New(&rpcCfg, nil)
if err != nil {
_ = cleanUp()
return nil, nil, fmt.Errorf("unable to create rpc client: %w",
err)
}
bd := BitcoindBackendConfig{
rpcHost: rpcHost,
rpcUser: rpcUser,
rpcPass: rpcPass,
zmqBlockPath: zmqBlockAddr,
zmqTxPath: zmqTxAddr,
p2pPort: p2pPort,
rpcClient: client,
minerAddr: miner,
rpcPolling: rpcPolling,
}
return &bd, cleanUp, nil
}