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) 2022-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"""Test-only Elligator Swift implementation7WARNING: This code is slow and uses bad randomness.8Do not use for anything but tests."""10import csv11import os12import random13import unittest15from test_framework.crypto.secp256k1 import FE, G, GE16from test_framework.util import assert_equal18# Precomputed constant square root of -3 (mod p).19MINUS_3_SQRT = FE(-3).sqrt()21def xswiftec(u, t):22"""Decode field elements (u, t) to an X coordinate on the curve."""23if u == 0:24u = FE(1)25if t == 0:26t = FE(1)27if u**3 + t**2 + 7 == 0:28t = 2 * t29X = (u**3 + 7 - t**2) / (2 * t)30Y = (X + t) / (MINUS_3_SQRT * u)31for x in (u + 4 * Y**2, (-X / Y - u) / 2, (X / Y - u) / 2):32if GE.is_valid_x(x):33return x34assert False36def xswiftec_inv(x, u, case):37"""Given x and u, find t such that xswiftec(u, t) = x, or return None.39Case selects which of the up to 8 results to return."""41if case & 2 == 0:42if GE.is_valid_x(-x - u):43return None44v = x45s = -(u**3 + 7) / (u**2 + u*v + v**2)46else:47s = x - u48if s == 0:49return None50r = (-s * (4 * (u**3 + 7) + 3 * s * u**2)).sqrt()51if r is None:52return None53if case & 1 and r == 0:54return None55v = (-u + r / s) / 256w = s.sqrt()57if w is None:58return None59if case & 5 == 0:60return -w * (u * (1 - MINUS_3_SQRT) / 2 + v)61if case & 5 == 1:62return w * (u * (1 + MINUS_3_SQRT) / 2 + v)63if case & 5 == 4:64return w * (u * (1 - MINUS_3_SQRT) / 2 + v)65if case & 5 == 5:66return -w * (u * (1 + MINUS_3_SQRT) / 2 + v)68def xelligatorswift(x):69"""Given a field element X on the curve, find (u, t) that encode them."""70assert GE.is_valid_x(x)71while True:72u = FE(random.randrange(1, FE.SIZE))73case = random.randrange(0, 8)74t = xswiftec_inv(x, u, case)75if t is not None:76return u, t78def ellswift_create():79"""Generate a (privkey, ellswift_pubkey) pair."""80priv = random.randrange(1, GE.ORDER)81u, t = xelligatorswift((priv * G).x)82return priv.to_bytes(32, 'big'), u.to_bytes() + t.to_bytes()84def ellswift_ecdh_xonly(pubkey_theirs, privkey):85"""Compute X coordinate of shared ECDH point between ellswift pubkey and privkey."""86u = FE(int.from_bytes(pubkey_theirs[:32], 'big'))87t = FE(int.from_bytes(pubkey_theirs[32:], 'big'))88d = int.from_bytes(privkey, 'big')89return (d * GE.lift_x(xswiftec(u, t))).x.to_bytes()92class TestFrameworkEllSwift(unittest.TestCase):93def test_xswiftec(self):94"""Verify that xswiftec maps all inputs to the curve."""95for _ in range(32):96u = FE(random.randrange(0, FE.SIZE))97t = FE(random.randrange(0, FE.SIZE))98x = xswiftec(u, t)99self.assertTrue(GE.is_valid_x(x))101# Check that inputs which are considered undefined in the original102# SwiftEC paper can also be decoded successfully (by remapping)103undefined_inputs = [104(FE(0), FE(23)), # u = 0105(FE(42), FE(0)), # t = 0106(FE(5), FE(-132).sqrt()), # u^3 + t^2 + 7 = 0107]108assert_equal(undefined_inputs[-1][0]**3 + undefined_inputs[-1][1]**2 + 7, 0)109for u, t in undefined_inputs:110x = xswiftec(u, t)111self.assertTrue(GE.is_valid_x(x))113def test_elligator_roundtrip(self):114"""Verify that encoding using xelligatorswift decodes back using xswiftec."""115for _ in range(32):116while True:117# Loop until we find a valid X coordinate on the curve.118x = FE(random.randrange(1, FE.SIZE))119if GE.is_valid_x(x):120break121# Encoding it to (u, t), decode it back, and compare.122u, t = xelligatorswift(x)123x2 = xswiftec(u, t)124self.assertEqual(x2, x)126def test_ellswift_ecdh_xonly(self):127"""Verify that shared secret computed by ellswift_ecdh_xonly match."""128for _ in range(32):129privkey1, encoding1 = ellswift_create()130privkey2, encoding2 = ellswift_create()131shared_secret1 = ellswift_ecdh_xonly(encoding1, privkey2)132shared_secret2 = ellswift_ecdh_xonly(encoding2, privkey1)133self.assertEqual(shared_secret1, shared_secret2)135def test_elligator_encode_testvectors(self):136"""Implement the BIP324 test vectors for ellswift encoding (read from xswiftec_inv_test_vectors.csv)."""137vectors_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'xswiftec_inv_test_vectors.csv')138with open(vectors_file, newline='') as csvfile:139reader = csv.DictReader(csvfile)140for row in reader:141u = FE.from_bytes(bytes.fromhex(row['u']))142x = FE.from_bytes(bytes.fromhex(row['x']))143for case in range(8):144ret = xswiftec_inv(x, u, case)145if ret is None:146self.assertEqual(row[f"case{case}_t"], "")147else:148self.assertEqual(row[f"case{case}_t"], ret.to_bytes().hex())149self.assertEqual(xswiftec(u, ret), x)151def test_elligator_decode_testvectors(self):152"""Implement the BIP324 test vectors for ellswift decoding (read from ellswift_decode_test_vectors.csv)."""153vectors_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ellswift_decode_test_vectors.csv')154with open(vectors_file, newline='') as csvfile:155reader = csv.DictReader(csvfile)156for row in reader:157encoding = bytes.fromhex(row['ellswift'])158assert_equal(len(encoding), 64)159expected_x = FE(int(row['x'], 16))160u = FE(int.from_bytes(encoding[:32], 'big'))161t = FE(int.from_bytes(encoding[32:], 'big'))162x = xswiftec(u, t)163self.assertEqual(x, expected_x)164self.assertTrue(GE.is_valid_x(x))
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.