Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1#!/usr/bin/env python32# Copyright (c) 2020-present The Bitcoin Core developers3# Distributed under the MIT software license, see the accompanying4# file COPYING or http://www.opensource.org/licenses/mit-license.php.6import argparse7import io8import requests9import subprocess10import sys11import xml.etree.ElementTree13DEFAULT_GLOBAL_FAUCET = 'https://signetfaucet.com/claim'14DEFAULT_GLOBAL_CAPTCHA = 'https://signetfaucet.com/captcha'15GLOBAL_FIRST_BLOCK_HASH = '00000086d6b2636cb2a392d45edc4ec544a10024d30141c9adf4bfd9de533b53'17# braille unicode block18BASE = 0x280019BIT_PER_PIXEL = [20[0x01, 0x08],21[0x02, 0x10],22[0x04, 0x20],23[0x40, 0x80],24]25BW = 226BH = 428# imagemagick or compatible fork (used for converting SVG)29CONVERT = 'convert'31class PPMImage:32'''33Load a PPM image (Pillow-ish API).34'''35def __init__(self, f):36if f.readline() != b'P6\n':37raise ValueError('Invalid ppm format: header')38line = f.readline()39(width, height) = (int(x) for x in line.rstrip().split(b' '))40if f.readline() != b'255\n':41raise ValueError('Invalid ppm format: color depth')42data = f.read(width * height * 3)43stride = width * 344self.size = (width, height)45self._grid = [[tuple(data[stride * y + 3 * x:stride * y + 3 * (x + 1)]) for x in range(width)] for y in range(height)]47def getpixel(self, pos):48return self._grid[pos[1]][pos[0]]50def print_image(img, threshold=128):51'''Print black-and-white image to terminal in braille unicode characters.'''52x_blocks = (img.size[0] + BW - 1) // BW53y_blocks = (img.size[1] + BH - 1) // BH55for yb in range(y_blocks):56line = []57for xb in range(x_blocks):58ch = BASE59for y in range(BH):60for x in range(BW):61try:62val = img.getpixel((xb * BW + x, yb * BH + y))63except IndexError:64pass65else:66if val[0] < threshold:67ch |= BIT_PER_PIXEL[y][x]68line.append(chr(ch))69print(''.join(line))71parser = argparse.ArgumentParser(description='Script to get coins from a faucet.', epilog='You may need to start with double-dash (--) when providing bitcoin-cli arguments.')72parser.add_argument('-c', '--cmd', dest='cmd', default='bitcoin-cli', help='bitcoin-cli command to use')73parser.add_argument('-f', '--faucet', dest='faucet', default=DEFAULT_GLOBAL_FAUCET, help='URL of the faucet')74parser.add_argument('-g', '--captcha', dest='captcha', default=DEFAULT_GLOBAL_CAPTCHA, help='URL of the faucet captcha, or empty if no captcha is needed')75parser.add_argument('-a', '--addr', dest='addr', default='', help='Bitcoin address to which the faucet should send')76parser.add_argument('-p', '--password', dest='password', default='', help='Faucet password, if any')77parser.add_argument('-n', '--amount', dest='amount', default='0.001', help='Amount to request (0.001-0.1, default is 0.001)')78parser.add_argument('-i', '--imagemagick', dest='imagemagick', default=CONVERT, help='Path to imagemagick convert utility')79parser.add_argument('bitcoin_cli_args', nargs='*', help='Arguments to pass on to bitcoin-cli (default: -signet)')81args = parser.parse_args()83if args.bitcoin_cli_args == []:84args.bitcoin_cli_args = ['-signet']87def bitcoin_cli(rpc_command_and_params):88argv = [args.cmd] + args.bitcoin_cli_args + rpc_command_and_params89try:90return subprocess.check_output(argv).strip().decode()91except FileNotFoundError:92raise SystemExit(f"The binary {args.cmd} could not be found")93except subprocess.CalledProcessError:94cmdline = ' '.join(argv)95raise SystemExit(f"-----\nError while calling {cmdline} (see output above).")98if args.faucet.lower() == DEFAULT_GLOBAL_FAUCET:99# Get the hash of the block at height 1 of the currently active signet chain100curr_signet_hash = bitcoin_cli(['getblockhash', '1'])101if curr_signet_hash != GLOBAL_FIRST_BLOCK_HASH:102raise SystemExit('The global faucet cannot be used with a custom Signet network. Please use the global signet or setup your custom faucet to use this functionality.\n')103else:104# For custom faucets, don't request captcha by default.105if args.captcha == DEFAULT_GLOBAL_CAPTCHA:106args.captcha = ''108if args.addr == '':109# get address for receiving coins110args.addr = bitcoin_cli(['getnewaddress', 'faucet', 'bech32'])112data = {'address': args.addr, 'password': args.password, 'amount': args.amount}114# Store cookies115# for debugging: print(session.cookies.get_dict())116session = requests.Session()118if args.captcha != '': # Retrieve a captcha119try:120res = session.get(args.captcha)121res.raise_for_status()122except requests.exceptions.RequestException as e:123raise SystemExit(f"Unexpected error when contacting faucet: {e}")125# Size limitation126svg = xml.etree.ElementTree.fromstring(res.content)127if svg.attrib.get('width') != '150' or svg.attrib.get('height') != '50':128raise SystemExit("Captcha size doesn't match expected dimensions 150x50")130# Convert SVG image to PPM, and load it131try:132rv = subprocess.run([args.imagemagick, 'svg:-', '-depth', '8', 'ppm:-'], input=res.content, check=True, capture_output=True)133except FileNotFoundError:134raise SystemExit(f"The binary {args.imagemagick} could not be found. Please make sure ImageMagick (or a compatible fork) is installed and that the correct path is specified.")136img = PPMImage(io.BytesIO(rv.stdout))138# Terminal interaction139print_image(img)140print(f"Captcha from URL {args.captcha}")141data['captcha'] = input('Enter captcha: ')143try:144res = session.post(args.faucet, data=data)145except Exception:146raise SystemExit(f"Unexpected error when contacting faucet: {sys.exc_info()[0]}")148# Display the output as per the returned status code149if res:150# When the return code is in between 200 and 400 i.e. successful151print(res.text)152elif res.status_code == 404:153print('The specified faucet URL does not exist. Please check for any server issues/typo.')154elif res.status_code == 429:155print('The script does not allow for repeated transactions as the global faucet is rate-limited to 1 request/IP/day. You can access the faucet website to get more coins manually')156else:157print(f'Returned Error Code {res.status_code}\n{res.text}\n')158print('Please check the provided arguments for their validity and/or any possible typo.')
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.