timplement script_num_to_hex - electrum - Electrum Bitcoin wallet HTML git clone https://git.parazyd.org/electrum DIR Log DIR Files DIR Refs DIR Submodules --- DIR commit 4b89b1e270e0730d3b7a811f950663439d3864ac DIR parent 376a815458d7765c3e3b4c22b74552bd4702b163 HTML Author: SomberNight <somber.night@protonmail.com> Date: Fri, 13 Apr 2018 20:14:54 +0200 implement script_num_to_hex Diffstat: M lib/bitcoin.py | 23 +++++++++++++++++++++++ M lib/tests/test_bitcoin.py | 18 +++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) --- DIR diff --git a/lib/bitcoin.py b/lib/bitcoin.py t@@ -152,6 +152,29 @@ def int_to_hex(i, length=1): s = "0"*(2*length - len(s)) + s return rev_hex(s) +def script_num_to_hex(i): + """See CScriptNum in Bitcoin Core. + Encodes an integer as hex, to be used in script. + + ported from https://github.com/bitcoin/bitcoin/blob/8cbc5c4be4be22aca228074f087a374a7ec38be8/src/script/script.h#L326 + """ + if i == 0: + return '' + + result = bytearray() + neg = i < 0 + absvalue = abs(i) + while absvalue > 0: + result.append(absvalue & 0xff) + absvalue >>= 8 + + if result[-1] & 0x80: + result.append(0x80 if neg else 0x00) + elif neg: + result[-1] |= 0x80 + + return bh2u(result) + def var_int(i): # https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer DIR diff --git a/lib/tests/test_bitcoin.py b/lib/tests/test_bitcoin.py t@@ -11,7 +11,8 @@ from lib.bitcoin import ( var_int, op_push, address_to_script, regenerate_key, verify_message, deserialize_privkey, serialize_privkey, is_segwit_address, is_b58_address, address_to_scripthash, is_minikey, is_compressed, is_xpub, - xpub_type, is_xprv, is_bip32_derivation, seed_type, EncodeBase58Check) + xpub_type, is_xprv, is_bip32_derivation, seed_type, EncodeBase58Check, + script_num_to_hex) from lib.util import bfh from lib import constants t@@ -150,6 +151,21 @@ class Test_bitcoin(unittest.TestCase): self.assertEqual(op_push(0x10000), '4e00000100') self.assertEqual(op_push(0x12345678), '4e78563412') + def test_script_num_to_hex(self): + # test vectors from https://github.com/btcsuite/btcd/blob/fdc2bc867bda6b351191b5872d2da8270df00d13/txscript/scriptnum.go#L77 + self.assertEqual(script_num_to_hex(127), '7f') + self.assertEqual(script_num_to_hex(-127), 'ff') + self.assertEqual(script_num_to_hex(128), '8000') + self.assertEqual(script_num_to_hex(-128), '8080') + self.assertEqual(script_num_to_hex(129), '8100') + self.assertEqual(script_num_to_hex(-129), '8180') + self.assertEqual(script_num_to_hex(256), '0001') + self.assertEqual(script_num_to_hex(-256), '0081') + self.assertEqual(script_num_to_hex(32767), 'ff7f') + self.assertEqual(script_num_to_hex(-32767), 'ffff') + self.assertEqual(script_num_to_hex(32768), '008000') + self.assertEqual(script_num_to_hex(-32768), '008080') + def test_address_to_script(self): # bech32 native segwit # test vectors from BIP-0173