1+ const fs = require ( 'fs' )
2+ , urlp = require ( 'url' )
3+ , assert = require ( 'assert' )
4+ , BitcoinClient = require ( 'bitcoin-core' )
5+
6+ module . exports = ( on , config ) => {
7+ config . baseUrl = config . baseUrl || process . env . BASE_URL
8+ config . bitcoindUrl = config . bitcoindUrl || process . env . BITCOIND_URL
9+
10+ // TODO: auto spawn dev-server for testing
11+
12+ assert ( config . baseUrl && config . bitcoindUrl , 'BASE_URL and BITCOIND_URL are required' )
13+
14+ const bitcoind = new BitcoinClient ( bitcoind_opt ( config . bitcoindUrl ) )
15+
16+ on ( 'task' , {
17+ bitcoind : async ( [ method , ...params ] ) =>
18+ bitcoind . command ( method , ...params )
19+
20+ , "bitcoind:mine" : async ( ) => {
21+ const addr = await bitcoind . getNewAddress ( )
22+ return ( await bitcoind . generateToAddress ( 1 , addr ) ) [ 0 ]
23+ }
24+
25+ , "bitcoind:make_tx" : async ( { confirmed } ) => {
26+ const addr = await bitcoind . getNewAddress ( )
27+ , amount = randAmount ( )
28+ , txid = await bitcoind . sendToAddress ( addr , amount )
29+ , block_hash = confirmed ? await bitcoind . generateToAddress ( 1 , await bitcoind . getNewAddress ( ) ) : null
30+ return { txid, addr, amount, block_hash }
31+ }
32+
33+ , "bitcoind:make_tx_bulk" : async ( { num_txs } ) => {
34+ const addr = await bitcoind . getNewAddress ( )
35+ , txids = [ ]
36+ for ( let i = 0 ; i < num_txs ; i ++ ) {
37+ txids . push ( await bitcoind . sendToAddress ( addr , randAmount ( ) ) )
38+ }
39+ return { txids, addr }
40+ }
41+ } )
42+
43+ return config
44+ }
45+
46+ function bitcoind_opt ( url ) {
47+ const parsed = urlp . parse ( url , true )
48+ , auth_str = parsed . auth || ( parsed . query . cookie && fs . readFileSync ( parsed . query . cookie ) . toString ( ) )
49+ , auth = auth_str && auth_str . split ( ':' , 2 ) . map ( decodeURIComponent )
50+
51+ return {
52+ host : parsed . hostname || 'localhost'
53+ , port : parsed . port
54+ , ssl : ( parsed . protocol == 'https:' )
55+ , username : auth ? auth [ 0 ] : null
56+ , password : auth ? auth [ 1 ] : null
57+ , network :'regtest'
58+ , wallet : parsed . query . wallet
59+ }
60+ }
61+
62+ const randAmount = ( ) =>
63+ `0.01${ Math . random ( ) * 10000 | 0 } ` . replace ( / 0 + $ / , '' )
0 commit comments