|
| 1 | +/** |
| 2 | +* Copyright 2025 Shift Crypto AG |
| 3 | +* |
| 4 | +* Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +* you may not use this file except in compliance with the License. |
| 6 | +* You may obtain a copy of the License at |
| 7 | +* |
| 8 | +* http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +* |
| 10 | +* Unless required by applicable law or agreed to in writing, software |
| 11 | +* distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +* See the License for the specific language governing permissions and |
| 14 | +* limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +import { exec, spawn, ChildProcess } from 'child_process'; |
| 18 | +import path from 'path'; |
| 19 | +import util from 'util'; |
| 20 | +import fs from 'fs'; |
| 21 | + |
| 22 | + |
| 23 | +const execAsync = util.promisify(exec); |
| 24 | + |
| 25 | +const RPC_USER = 'dbb'; |
| 26 | +const RPC_PASSWORD = 'dbb'; |
| 27 | +const RPC_PORT = 10332; |
| 28 | +const DATADIR = '/bitcoin'; |
| 29 | + |
| 30 | +let addr: string; |
| 31 | + |
| 32 | +// run bitcoin-cli command inside the bitcoind-regtest docker container. |
| 33 | +async function runBitcoinCli(args: string[]): Promise<string> { |
| 34 | + const cmd = [ |
| 35 | + 'docker exec', |
| 36 | + '--user=$(id -u)', |
| 37 | + 'bitcoind-regtest', |
| 38 | + 'bitcoin-cli', |
| 39 | + '-regtest', |
| 40 | + `-datadir=${DATADIR}`, |
| 41 | + `-rpcuser=${RPC_USER}`, |
| 42 | + `-rpcpassword=${RPC_PASSWORD}`, |
| 43 | + `-rpcport=${RPC_PORT}`, |
| 44 | + ...args |
| 45 | + ].join(' '); |
| 46 | + |
| 47 | + const { stdout } = await execAsync(cmd); |
| 48 | + return stdout.trim(); |
| 49 | +} |
| 50 | + |
| 51 | +// Setup regtest by |
| 52 | +// - Creating a wallet |
| 53 | +// - Getting a new address |
| 54 | +// - Generating 101 blocks to that address |
| 55 | +export async function setupRegtestWallet(): Promise<void> { |
| 56 | + await runBitcoinCli(['createwallet', 'testwallet']); |
| 57 | + addr = await runBitcoinCli(['getnewaddress']); |
| 58 | + await runBitcoinCli(['generatetoaddress', '101', addr]); |
| 59 | +} |
| 60 | + |
| 61 | +// mineBlocks mines the given number of blocks to the regtest wallet address. |
| 62 | +// This is useful to confirm transactions in tests. |
| 63 | +export async function mineBlocks(numBlocks: number): Promise<void> { |
| 64 | + await runBitcoinCli(['generatetoaddress', numBlocks.toString(), addr]); |
| 65 | +} |
| 66 | + |
| 67 | +/** |
| 68 | + * Send coins to a given address in the regtest wallet. |
| 69 | + * @param address The address to send to |
| 70 | + * @param amount The amount in BTC |
| 71 | + */ |
| 72 | +export async function sendCoins(address: string, amount: number | string): Promise<string> { |
| 73 | + // bitcoin-cli expects amount as a string with decimal point |
| 74 | + const amt = typeof amount === 'number' ? amount.toFixed(8) : amount; |
| 75 | + const txid = await runBitcoinCli(['sendtoaddress', address, amt]); |
| 76 | + return txid; // returns the transaction ID |
| 77 | +} |
| 78 | + |
| 79 | + |
| 80 | +export function launchRegtest(): Promise<ChildProcess> { |
| 81 | + |
| 82 | + // First, clean up cache and headers. |
| 83 | + try { |
| 84 | + const basePath = path.resolve(__dirname, '../../../../appfolder.dev/cache'); |
| 85 | + |
| 86 | + // Remove headers-rbtc.bin if it exists |
| 87 | + const headersPath = path.join(basePath, 'headers-rbtc.bin'); |
| 88 | + if (fs.existsSync(headersPath)) { |
| 89 | + fs.rmSync(headersPath, { force: true }); |
| 90 | + console.log(`Removed: ${headersPath}`); |
| 91 | + } |
| 92 | + // Remove all account-*rbtc* directories |
| 93 | + const entries = fs.readdirSync(basePath); |
| 94 | + for (const entry of entries) { |
| 95 | + if (/^account-.*rbtc/i.test(entry)) { |
| 96 | + const dirPath = path.join(basePath, entry); |
| 97 | + fs.rmSync(dirPath, { recursive: true, force: true }); |
| 98 | + console.log(`Removed directory: ${dirPath}`); |
| 99 | + } |
| 100 | + } |
| 101 | + } catch (err) { |
| 102 | + console.warn('Warning: Failed to clean up cache or headers before regtest launch:', err); |
| 103 | + } |
| 104 | + |
| 105 | + const scriptPath = path.resolve(__dirname, '../../../../scripts/run_regtest.sh'); |
| 106 | + |
| 107 | + return new Promise((resolve, reject) => { |
| 108 | + const proc = spawn('bash', [scriptPath], { |
| 109 | + detached: true, |
| 110 | + stdio: ['ignore', 'pipe', 'pipe'], // capture stdout/stderr |
| 111 | + }); |
| 112 | + |
| 113 | + // Listen for the line we want |
| 114 | + const onData = (data: Buffer) => { |
| 115 | + const text = data.toString(); |
| 116 | + process.stdout.write(text); // still print it to console |
| 117 | + if (text.includes('waiting for 0 blocks to download (IBD)')) { |
| 118 | + proc.stdout.off('data', onData); |
| 119 | + proc.stderr.off('data', onData); |
| 120 | + resolve(proc); // resolve when we see the line |
| 121 | + } |
| 122 | + }; |
| 123 | + |
| 124 | + proc.stdout.on('data', onData); |
| 125 | + proc.stderr.on('data', onData); |
| 126 | + |
| 127 | + proc.on('error', reject); |
| 128 | + }); |
| 129 | +} |
| 130 | + |
| 131 | + |
| 132 | +/** |
| 133 | + * Cleans up all regtest-related processes and Docker containers. |
| 134 | + * |
| 135 | + * @param regtest The ChildProcess returned by launchRegtest() |
| 136 | + */ |
| 137 | +export async function cleanupRegtest( |
| 138 | + regtest?: ChildProcess, |
| 139 | +): Promise<void> { |
| 140 | + console.log('Cleaning up regtest environment'); |
| 141 | + |
| 142 | + |
| 143 | + // Kill the regtest process group (spawned as detached) |
| 144 | + if (regtest?.pid) { |
| 145 | + try { |
| 146 | + process.kill(-regtest.pid, 'SIGTERM'); |
| 147 | + } catch (err) { |
| 148 | + console.warn('Failed to kill regtest process:', err); |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + |
| 153 | + // Remove Docker containers |
| 154 | + try { |
| 155 | + await execAsync(` |
| 156 | +docker container rm -f bitcoind-regtest electrs-regtest1 electrs-regtest2 >/dev/null 2>&1 || true |
| 157 | +`); |
| 158 | + console.log('Docker containers cleaned up.'); |
| 159 | + } catch (err) { |
| 160 | + console.warn('Docker cleanup failed:', err); |
| 161 | + } |
| 162 | + |
| 163 | + |
| 164 | + // Remove regtest data directories |
| 165 | + const dirs = [ |
| 166 | + '/tmp/regtest/btcdata', |
| 167 | + '/tmp/regtest/electrsdata1', |
| 168 | + '/tmp/regtest/electrsdata2', |
| 169 | + ]; |
| 170 | + |
| 171 | + for (const dir of dirs) { |
| 172 | + try { |
| 173 | + await execAsync(`rm -rf ${dir}`); |
| 174 | + console.log(`Deleted directory: ${dir}`); |
| 175 | + } catch (err) { |
| 176 | + console.warn(`Failed to delete directory ${dir}:`, err); |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | +} |
0 commit comments