def compile(filename): """ Compile a .bt file into a script. """ f = open(filename,'r') raw_string = f.read().replace('\n',' ') raw_list = [x for x in raw_string.split(' ') if x != ''] parsed_list = [] for item in raw_list: if len(item) > 1 and item[:2] == 'OP': try: parsed_list.append(ops.word[item]) except KeyError: print "Unrecognized op %s" % (item,) return else: parsed_list.append(bytestream.bytestream(item)) stream = bytestream.bytestream('') for parsed_item in parsed_list: if(isinstance(parsed_item, ops.op)): stream += parsed_item.stream() else: stream += parsed_item return script.script(stream)
def encode(self): stream = bytestream.bytestream("") stream += bytestream.bytestream(self.prev_hash).reverse() stream += bytestream.fromunsigned(self.index, 4) stream += bytestream.fromvarlen(self.script_length) stream += self.script.stream() stream += bytestream.fromunsigned(self.sequence, 4) return stream
def encode(self): stream = bytestream.bytestream("") stream += bytestream.bytestream(self.prev_hash).reverse() stream += bytestream.fromunsigned(self.index, 4) stream += bytestream.fromvarlen(self.script_length) stream += self.script.stream() stream += bytestream.fromunsigned(self.sequence, 4) return stream
def hash160(stream, machine): data = machine.pop() sha256 = hashlib.new('sha256') ripemd160 = hashlib.new('ripemd160') sha256.update(data.stream.decode('hex')) ripemd160.update(sha256.digest()) hashed = bytestream.bytestream(ripemd160.hexdigest()) machine.push(hashed) return bytestream.bytestream(ripemd160.hexdigest())
def op_add1(stream, machine): top_element = machine.pop() if top_element[2:] == '\\x': hex_value = top_element[2:] # get ride of \x else: hex_value = top_element top_stream = bytestream.bytestream(hex_value) if len(top_stream) > 4: # input is longer than 4 bytes raise InvalidTransactionException('Integer longer than 4 bytes') machine.push(bytestream.bytestream(hex(top_stream.unsigned()+1))) #TODO verify little or big
def __init__(self, payload): self.magic = bytestream.bytestream("F9BEB4D9") #self.command = bytestream.bytestream("000000000000000000000000") self.command = bytestream.bytestream("747800000000000000000000") #self.command = bytestream.bytestream("000000000000000000000000") self.length = bytestream.fromunsigned(len(payload)) first_hasher = hashlib.new('sha256') first_hasher.update(payload.decode()) second_hasher = hashlib.new('sha256') second_hasher.update(first_hasher.digest()) hashed = bytestream.bytestream(second_hasher.hexdigest()) self.checksum = hashed.peek(4) self.payload = payload
def __init__(self, payload): self.magic = bytestream.bytestream("F9BEB4D9") #self.command = bytestream.bytestream("000000000000000000000000") self.command = bytestream.bytestream("747800000000000000000000") #self.command = bytestream.bytestream("000000000000000000000000") self.length = bytestream.fromunsigned(len(payload)) first_hasher = hashlib.new('sha256') first_hasher.update(payload.decode()) second_hasher = hashlib.new('sha256') second_hasher.update(first_hasher.digest()) hashed = bytestream.bytestream(second_hasher.hexdigest()) self.checksum = hashed.peek(4) self.payload = payload
def __init__(self, s): if isinstance(s, str): self.bstream = bytestream.bytestream(s) else: self.bstream = s self.iterator = copy.deepcopy(self.bstream) self.nops = None
def __init__(self, *args): if len(args) < 2: self.version = 1 self.tx_in_count = 0 self.tx_in = [] self.tx_out_count = 0 self.tx_out = [] self.lock_time = 0 if len(args) == 1: self.server = args[0] elif len(args) == 2: txid = args[0] server = args[1] self.server = server tx = server("getrawtransaction", txid, 1) self.txid = txid try: stream = bytestream.bytestream(tx['hex']) except TypeError as e: print "Server returned error. Probably can't find the transaction key." print "\tTypeError error: {0}:".format(e) sys.exit(1) except: print "Unexpected error:", sys.exc_info()[0] raise self.version = stream.read(4).unsigned() self.tx_in_count = stream.readvarlensize() self.tx_in = [txin(stream) for i in xrange(self.tx_in_count)] self.tx_out_count = stream.readvarlensize() self.tx_out = [txout(stream) for i in xrange(self.tx_out_count)] self.lock_time = stream.read(4).unsigned() else: raise ValueError("Zero or two args")
def __init__(self, s): if isinstance(s, str): self.bstream = bytestream.bytestream(s) else: self.bstream = s self.iterator = copy.deepcopy(self.bstream) self.nops = None
def __init__(self, *args): if len(args) < 2: self.version = 1 self.tx_in_count = 0 self.tx_in = [] self.tx_out_count = 0 self.tx_out = [] self.lock_time = 0 if len(args) == 1: self.server = args[0] elif len(args) == 2: txid = args[0] server = args[1] self.server = server tx = server("getrawtransaction", txid, 1) self.txid = txid try: stream = bytestream.bytestream(tx['hex']) except TypeError as e: print "Server returned error. Probably can't find the transaction key." print "\tTypeError error: {0}:".format(e) sys.exit(1) except: print "Unexpected error:", sys.exc_info()[0] raise self.version = stream.read(4).unsigned() self.tx_in_count = stream.readvarlensize() self.tx_in = [txin(stream) for i in xrange(self.tx_in_count)] self.tx_out_count = stream.readvarlensize() self.tx_out = [txout(stream) for i in xrange(self.tx_out_count)] self.lock_time = stream.read(4).unsigned() else: raise ValueError("Zero or two args")
def encode(self): encoded = bytestream.bytestream("") encoded += self.magic encoded += self.command encoded += self.length encoded += self.checksum encoded += self.payload return encoded
def twohasher(stream, machine): data = machine.pop() first_hasher = hashlib.new(hashtype_string_1) first_hasher.update(data.stream.decode('hex')) second_hasher = hashlib.new(hashtype_string_2) second_hasher.update(first_hasher.digest()) hashed = bytestream.bytestream(second_hasher.hexdigest()) machine.push(hashed)
def encode(self): encoded = bytestream.bytestream("") encoded += self.magic encoded += self.command encoded += self.length encoded += self.checksum encoded += self.payload return encoded
def checksig(stream, machine, transaction, index, subscript): """ For details, please see https://en.bitcoin.it/wiki/OP_CHECKSIG. """ # How it works # Firstly always this (the default) procedure is # applied: Signature verification process of the default procedure # the public key and the signature are popped from the stack, in # that order. If the hash-type value is 0, then it is replaced by # the last_byte of the signature. Then the last byte of the # signature is always deleted. pubkey = machine.pop() sig = machine.pop() #sig.stream = sig.stream[:-2] # this is actually done later # A new subscript is created from the instruction from the most # recently parsed OP_CODESEPARATOR (last one in script) to the end # of the script. If there is no OP_CODESEPARATOR the entire script # becomes the subscript (hereby referred to as subScript) # not implemented yet (james) # The sig is deleted from subScript. # note: this is nonstandard so I am ignoring it (james) # All OP_CODESEPARATORS are removed from subScript # not implemented yet (james) # The hashtype is removed from the last byte of the sig and stored (as 4 bytes) hashtype = bytestream.fromunsigned(bytestream.bytestream(sig.stream[-2:]).unsigned(),4) sig.stream = sig.string()[:-2] # A copy is made of the current transaction (hereby referred to txCopy) txCopy = copy.deepcopy(transaction) # The scripts for all transaction inputs in txCopy are set to empty scripts (exactly 1 byte 0x00) for i in xrange(txCopy.tx_in_count): txCopy.tx_in[i].script_length = 0 txCopy.tx_in[i].script = script.script(bytestream.fromunsigned(0,1)) # The script for the current transaction input in txCopy is set to subScript (lead in by its length as a var-integer encoded!) txCopy.tx_in[index-1].script_length = len(subscript) txCopy.tx_in[index-1].script = subscript # Serialize txCopy and append hashtype serial = txCopy.encode() + hashtype # hash twice with sha256 msg = ((hashlib.sha256(hashlib.sha256(serial.decode()).digest()).digest()))# [::-1]).encode('hex_codec') # verify via ecdsa key = btct.decompress(pubkey.stream) vk = ecdsa.VerifyingKey.from_string(key[2:].decode('hex'), curve=ecdsa.SECP256k1) try: vk.verify_digest(sig.decode(), msg, sigdecode=ecdsa.util.sigdecode_der) machine.push(bytestream.fromunsigned(1,1)) except ecdsa.BadSignatureError: machine.push(bytestream.fromunsigned(0,1))
def opt_size(stream, machine): top_element = machine.peek() # hex value if top_element[2:] == '\\x': hex_value = top_element[2:] # get ride of \x else: hex_value = top_element string_top_element = ''.join([chr(int(s, 16)) for s in [hex_value[i: i+2] for i in range(0, len(hex_value), 2)]]) size_top = len(string_top_element) machine.push(bytestream.bytestream(hex(size_top))) # push hex representation of size_top
def encode(self): stream = bytestream.bytestream('') stream += bytestream.fromunsigned(self.version, 4) stream += bytestream.fromvarlen(self.tx_in_count) for tx_in in self.tx_in: stream += tx_in.encode() stream += bytestream.fromvarlen(self.tx_out_count) for tx_out in self.tx_out: stream += tx_out.encode() stream += bytestream.fromunsigned(self.lock_time, 4) return stream
def encode(self): stream = bytestream.bytestream("") stream += bytestream.fromunsigned(self.version, 4) stream += bytestream.fromvarlen(self.tx_in_count) for tx_in in self.tx_in: stream += tx_in.encode() stream += bytestream.fromvarlen(self.tx_out_count) for tx_out in self.tx_out: stream += tx_out.encode() stream += bytestream.fromunsigned(self.lock_time, 4) return stream
def script(obj): """ Compile a .bs file into a script. """ if instanceof(obj, str): f = open(filename, 'r') raw_string = f.read().replace('\n', ' ') f.close() raw_list = [x for x in raw_string.split(' ') if x != ''] else: raw_list = obj parsed_list = [] #for i in xrange(1,len(raw_list)): for item in raw_list: #item = raw_list[i] if len(item) > 1 and item[:2] == 'OP': try: parsed_list.append(ops.word[item]) except KeyError: print "Unrecognized op %s" % (item, ) return else: bstream = bytestream.bytestream(item) # add a pushing op if needed if (len(parsed_list) == 0 or ((isinstance(parsed_list[-1], ops.op) and (parsed_list[-1].opcode < 1 or parsed_list[-1].opcode > 75)) or not isinstance(parsed_list[-1], ops.op))): parsed_list.append(ops.code[len(bstream)]) parsed_list.append(bstream) stream = bytestream.bytestream('') for parsed_item in parsed_list: if (isinstance(parsed_item, ops.op)): stream += parsed_item.stream() else: stream += parsed_item return scr.script(stream)
def script(obj): """ Compile a .bs file into a script. """ if instanceof(obj,str): f = open(filename,'r') raw_string = f.read().replace('\n',' ') f.close() raw_list = [x for x in raw_string.split(' ') if x != ''] else: raw_list = obj parsed_list = [] #for i in xrange(1,len(raw_list)): for item in raw_list: #item = raw_list[i] if len(item) > 1 and item[:2] == 'OP': try: parsed_list.append(ops.word[item]) except KeyError: print "Unrecognized op %s" % (item,) return else: bstream = bytestream.bytestream(item) # add a pushing op if needed if (len(parsed_list) == 0 or ((isinstance(parsed_list[-1], ops.op) and (parsed_list[-1].opcode < 1 or parsed_list[-1].opcode > 75)) or not isinstance(parsed_list[-1], ops.op))): parsed_list.append(ops.code[len(bstream)]) parsed_list.append(bstream) stream = bytestream.bytestream('') for parsed_item in parsed_list: if(isinstance(parsed_item, ops.op)): stream += parsed_item.stream() else: stream += parsed_item return scr.script(stream)
def __init__(self, txid, server): self.server = server tx = server("getrawtransaction", txid, 1) self.txid = txid try: stream = bytestream.bytestream(tx["hex"]) except TypeError as e: print "Server returned error. Probably can't find the transaction key." print "\tTypeError error: {0}:".format(e) sys.exit(1) except: print "Unexpected error:", sys.exc_info()[0] raise self.version = stream.read(4).unsigned() self.tx_in_count = stream.readvarlensize() self.tx_in = [txin(stream) for i in xrange(self.tx_in_count)] self.tx_out_count = stream.readvarlensize() self.tx_out = [txout(stream) for i in xrange(self.tx_out_count)] self.lock_time = stream.read(4).unsigned()
def stream(self): string = hex(self.opcode)[2:] if len(string) < 2: string = "0" + string return bytestream.bytestream(string)
def encode(self): stream = bytestream.bytestream("") stream += bytestream.fromunsigned(self.value, 8) stream += bytestream.fromvarlen(self.script_length) stream += self.script.stream() return stream
def onehasher(stream, machine): data = machine.pop() hasher = hashlib.new(hashtype_string) hasher.update(data.stream.decode('hex')) hashed = bytestream.bytestream(hasher.hexdigest()) machine.push(hashed)
def __init__(self, s): if isinstance(s, str): self.bstream = bytestream.bytestream(s) else: self.bstream = s self.original_bstream = copy.deepcopy(self.bstream)
def stream(self): string = hex(self.opcode)[2:] if len(string) < 2: string = '0' + string return bytestream.bytestream(string)
def encode(self): stream = bytestream.bytestream("") stream += bytestream.fromunsigned(self.value, 8) stream += bytestream.fromvarlen(self.script_length) stream += self.script.stream() return stream