1
0

bitcoin.py: SCRIPT-related clean-up. transaction.py: construct_witness

This commit is contained in:
SomberNight
2018-04-27 15:38:44 +02:00
parent 97296432a2
commit e13183ea7a
3 changed files with 47 additions and 38 deletions

View File

@@ -152,7 +152,7 @@ def int_to_hex(i, length=1):
s = "0"*(2*length - len(s)) + s
return rev_hex(s)
def script_num_to_hex(i):
def script_num_to_hex(i: int) -> str:
"""See CScriptNum in Bitcoin Core.
Encodes an integer as hex, to be used in script.
@@ -176,7 +176,7 @@ def script_num_to_hex(i):
return bh2u(result)
def var_int(i):
def var_int(i: int) -> str:
# https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer
if i<0xfd:
return int_to_hex(i)
@@ -188,14 +188,14 @@ def var_int(i):
return "ff"+int_to_hex(i,8)
def witness_push(item):
""" Returns data in the form it should be present in the witness.
def witness_push(item: str) -> str:
"""Returns data in the form it should be present in the witness.
hex -> hex
"""
return var_int(len(item) // 2) + item
def op_push(i):
def op_push(i: int) -> str:
if i<0x4c: # OP_PUSHDATA1
return int_to_hex(i)
elif i<=0xff:
@@ -206,37 +206,33 @@ def op_push(i):
return '4e' + int_to_hex(i,4)
def add_data_to_script(data):
def push_script(data: str) -> str:
"""Returns pushed data to the script, automatically
choosing canonical opcodes depending on the length of the data.
bytes -> bytes
hex -> hex
ported from https://github.com/btcsuite/btcd/blob/fdc2bc867bda6b351191b5872d2da8270df00d13/txscript/scriptbuilder.go#L128
"""
assert_bytes(data)
data = bfh(data)
from .transaction import opcodes
data_len = len(data)
# "small integer" opcodes
if data_len == 0 or data_len == 1 and data[0] == 0:
return bytes([opcodes.OP_0])
return bh2u(bytes([opcodes.OP_0]))
elif data_len == 1 and data[0] <= 16:
return bytes([opcodes.OP_1 - 1 + data[0]])
return bh2u(bytes([opcodes.OP_1 - 1 + data[0]]))
elif data_len == 1 and data[0] == 0x81:
return bytes([opcodes.OP_1NEGATE])
return bh2u(bytes([opcodes.OP_1NEGATE]))
return bfh(push_script(bh2u(data)))
return op_push(data_len) + bh2u(data)
def add_number_to_script(i):
"""int -> bytes"""
return add_data_to_script(bfh(script_num_to_hex(i)))
def add_number_to_script(i: int) -> bytes:
return bfh(push_script(script_num_to_hex(i)))
def push_script(x):
return op_push(len(x)//2) + x
def sha256(x):
x = to_bytes(x, 'utf8')
return bytes(hashlib.sha256(x).digest())