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) 2025-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.5"""Routines for compressing transaction output amounts and scripts."""6import unittest8from .messages import COIN11def compress_amount(n):12if n == 0:13return 014e = 015while ((n % 10) == 0) and (e < 9):16n //= 1017e += 118if e < 9:19d = n % 1020assert (d >= 1 and d <= 9)21n //= 1022return 1 + (n*9 + d - 1)*10 + e23else:24return 1 + (n - 1)*10 + 927def decompress_amount(x):28if x == 0:29return 030x -= 131e = x % 1032x //= 1033n = 034if e < 9:35d = (x % 9) + 136x //= 937n = x * 10 + d38else:39n = x + 140while e > 0:41n *= 1042e -= 143return n46class TestFrameworkCompressor(unittest.TestCase):47def test_amount_compress_decompress(self):48def check_amount(amount, expected_compressed):49self.assertEqual(compress_amount(amount), expected_compressed)50self.assertEqual(decompress_amount(expected_compressed), amount)52# test cases from compress_tests.cpp:compress_amounts53check_amount(0, 0x0)54check_amount(1, 0x1)55check_amount(1000000, 0x7)56check_amount(COIN, 0x9)57check_amount(50*COIN, 0x32)58check_amount(21000000*COIN, 0x1406f40)
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.