def dump_signatures(tx, tx_in, tx_out, idx, netcode, address_prefix, traceback_f, disassembly_level): signatures = [] for opcode in opcode_list(tx_in.script): if not opcode.startswith("OP_"): try: signatures.append(parse_signature_blob(h2b(opcode[1:-1]))) except UnexpectedDER: pass if signatures: sig_types_identical = (tuple(zip(*signatures))[1].count( signatures[0][1]) == len(signatures)) i = 1 if len(signatures) > 1 else '' for sig_pair, sig_type in signatures: print(" r{0}: {1:#x}\n s{0}: {2:#x}".format( i, *sig_pair)) if not sig_types_identical and tx_out: print(" z{}: {:#x} {}".format( i, tx.signature_hash(tx_out.script, idx, sig_type), sighash_type_to_string(sig_type))) if i: i += 1 if sig_types_identical and tx_out: print(" z:{} {:#x} {}".format( ' ' if i else '', tx.signature_hash(tx_out.script, idx, sig_type), sighash_type_to_string(sig_type)))
def fromTransaction(blockn, txhex): tx = Tx.from_hex(txhex) #print (binascii.hexlify (tx.blanked_hash ())) # Get the opreturn oprets = [] for txout in tx.txs_out: ops = tools.opcode_list(txout.script) if len(ops) > 0 and ops[0] == 'OP_RETURN': oprets.append(ops[1]) # If there's no opreturn, return empty if len(oprets) == 0: return None # Check opret datas for opret in oprets: # Get the opreturn data try: data = (''.join( chr(int(opret[i:i + 2], 16)) for i in range(0, len(opret), 2))) except: # Other oprets with invalid data continue # Check if data is a contractchain message if data[0:len(Protocol.MAGIC_FLAG)] != Protocol.MAGIC_FLAG: continue m = Message() # Grab metadata from transaction m.Protocol = ord( data[len(Protocol.MAGIC_FLAG):len(Protocol.MAGIC_FLAG) + 1]) m.DappCode = [ ord(data[len(Protocol.MAGIC_FLAG) + 1:len(Protocol.MAGIC_FLAG) + 2]), ord(data[len(Protocol.MAGIC_FLAG) + 2:len(Protocol.MAGIC_FLAG) + 3]) ] m.Method = ord(data[len(Protocol.MAGIC_FLAG) + 3:len(Protocol.MAGIC_FLAG) + 4]) m.Hash = tx.id() m.Block = blockn m.DataHash = data[len(Protocol.MAGIC_FLAG) + 4:len(Protocol.MAGIC_FLAG) + 4 + Protocol.DATA_HASH_SIZE].encode('ascii') m.Player = tx.txs_in[0].bitcoin_address( address_prefix_for_netcode(config.CONF['chain'])) return m return None
def public_key_sec(self): """Return the public key as sec, or None in case of failure.""" if self.is_coinbase(): return None opcodes = opcode_list(self.script) if len(opcodes) == 2 and opcodes[0].startswith("[30"): # the second opcode is probably the public key as sec sec = h2b(opcodes[1][1:-1]) return sec return None
def cosign(tx, keys, redeem_scripts=None): """ Utility for locally signing a multisig transaction. :param tx: Transaction to sign. :param redeem_scripts: Required when adding first signature only. :param keys: one key per transaction input :return: """ if not keys: # Nothing to do return if redeem_scripts: # scripts supplied as a param raw_scripts = [script.script() for script in redeem_scripts] else: # parsing scripts from tx raw_scripts = [h2b(opcode_list(script)[-1]) for script in [tx_in.script for tx_in in tx.txs_in] if script] lookup = build_p2sh_lookup(raw_scripts) if raw_scripts else None db = LazySecretExponentDBWithNetwork(keys[0]._netcode, [key.wif() for key in keys], {}) tx.sign(db, p2sh_lookup=lookup)
def fromTransaction (blockn, txhex): tx = Tx.from_hex(txhex) #print (binascii.hexlify (tx.blanked_hash ())) # Get the opreturn oprets = [] for txout in tx.txs_out: ops = tools.opcode_list (txout.script) if len (ops) > 0 and ops[0] == 'OP_RETURN': oprets.append (ops[1]) # If there's no opreturn, return empty if len (oprets) == 0: return None # Check opret datas for opret in oprets: # Get the opreturn data try: data = (''.join(chr(int(opret[i:i+2], 16)) for i in range(0, len(opret), 2))) except: # Other oprets with invalid data continue # Check if data is a contractchain message if data[0:len (Protocol.MAGIC_FLAG)] != Protocol.MAGIC_FLAG: continue m = Message () # Grab metadata from transaction m.Protocol = ord (data[len(Protocol.MAGIC_FLAG):len(Protocol.MAGIC_FLAG)+1]) m.DappCode = [ ord (data[len(Protocol.MAGIC_FLAG)+1:len(Protocol.MAGIC_FLAG)+2]), ord (data[len(Protocol.MAGIC_FLAG)+2:len(Protocol.MAGIC_FLAG)+3]) ] m.Method = ord (data[len(Protocol.MAGIC_FLAG)+3:len(Protocol.MAGIC_FLAG)+4]) m.Hash = tx.id () m.Block = blockn m.DataHash = data[len(Protocol.MAGIC_FLAG)+4:len(Protocol.MAGIC_FLAG)+4+Protocol.DATA_HASH_SIZE].encode ('ascii') m.Player = tx.txs_in[0].bitcoin_address (address_prefix_for_netcode(config.CONF['chain'])) return m return None
def isMessage (txhex): tx = Tx.from_hex (txhex) oprets = [] for txout in tx.txs_out: ops = tools.opcode_list (txout.script) #print ('OPS:',ops) if len (ops) > 0 and ops[0] == 'OP_RETURN': oprets.append (ops[1]) if len (oprets) == 0: return False for opret in oprets: data = (''.join(chr(int(opret[i:i+2], 16)) for i in range(0, len(opret), 2))) if data[0:len (Protocol.MAGIC_FLAG)] != Protocol.MAGIC_FLAG: continue else: return True return False
def isMessage(txhex): tx = Tx.from_hex(txhex) oprets = [] for txout in tx.txs_out: ops = tools.opcode_list(txout.script) #print ('OPS:',ops) if len(ops) > 0 and ops[0] == 'OP_RETURN': oprets.append(ops[1]) if len(oprets) == 0: return False for opret in oprets: data = (''.join( chr(int(opret[i:i + 2], 16)) for i in range(0, len(opret), 2))) if data[0:len(Protocol.MAGIC_FLAG)] != Protocol.MAGIC_FLAG: continue else: return True return False
def dump_signatures(tx, tx_in, tx_out, idx, netcode, address_prefix, traceback_f, disassembly_level): signatures = [] for opcode in opcode_list(tx_in.script): if not opcode.startswith("OP_"): try: signatures.append(parse_signature_blob(h2b(opcode[1:-1]))) except UnexpectedDER: pass if signatures: sig_types_identical = ( tuple(zip(*signatures))[1].count(signatures[0][1]) == len(signatures)) i = 1 if len(signatures) > 1 else '' for sig_pair, sig_type in signatures: print(" r{0}: {1:#x}\n s{0}: {2:#x}".format(i, *sig_pair)) if not sig_types_identical and tx_out: print(" z{}: {:#x} {}".format(i, tx.signature_hash(tx_out.script, idx, sig_type), sighash_type_to_string(sig_type))) if i: i += 1 if sig_types_identical and tx_out: print(" z:{} {:#x} {}".format(' ' if i else '', tx.signature_hash( tx_out.script, idx, sig_type), sighash_type_to_string(sig_type)))
def dump_tx(tx, netcode, verbose_signature, disassembly_level, do_trace): address_prefix = address_prefix_for_netcode(netcode) tx_bin = stream_to_bytes(tx.stream) print("Version: %2d tx hash %s %d bytes " % (tx.version, tx.id(), len(tx_bin))) print("TxIn count: %d; TxOut count: %d" % (len(tx.txs_in), len(tx.txs_out))) if tx.lock_time == 0: meaning = "valid anytime" elif tx.lock_time < LOCKTIME_THRESHOLD: meaning = "valid after block index %d" % tx.lock_time else: when = datetime.datetime.utcfromtimestamp(tx.lock_time) meaning = "valid on or after %s utc" % when.isoformat() print("Lock time: %d (%s)" % (tx.lock_time, meaning)) print("Input%s:" % ('s' if len(tx.txs_in) != 1 else '')) missing_unspents = tx.missing_unspents() traceback_f = trace_script if do_trace else None for idx, tx_in in enumerate(tx.txs_in): if disassembly_level > 0: signature_for_hash_type_f = lambda hash_type, script: tx.signature_hash( script, idx, hash_type) if tx.is_coinbase(): print("%4d: COINBASE %12.5f mBTC" % (idx, satoshi_to_mbtc(tx.total_in()))) else: suffix = "" if tx.missing_unspent(idx): tx_out = None address = tx_in.bitcoin_address(address_prefix=address_prefix) else: tx_out = tx.unspents[idx] sig_result = " sig ok" if tx.is_signature_ok(idx, traceback_f=traceback_f) else " BAD SIG" suffix = " %12.5f mBTC %s" % (satoshi_to_mbtc(tx_out.coin_value), sig_result) address = tx_out.bitcoin_address(netcode=netcode) t = "%4d: %34s from %s:%-4d%s" % (idx, address, b2h_rev(tx_in.previous_hash), tx_in.previous_index, suffix) print(t.rstrip()) if disassembly_level > 0: out_script = b'' if tx_out: out_script = tx_out.script for (pre_annotations, pc, opcode, instruction, post_annotations) in \ disassemble_scripts(tx_in.script, out_script, signature_for_hash_type_f): for l in pre_annotations: print(" %s" % l) print( " %4x: %02x %s" % (pc, opcode, instruction)) for l in post_annotations: print(" %s" % l) if verbose_signature: signatures = [] for opcode in opcode_list(tx_in.script): if not opcode.startswith("OP_"): try: signatures.append(parse_signature_blob(h2b(opcode))) except UnexpectedDER: pass if signatures: sig_types_identical = (zip(*signatures)[1]).count(signatures[0][1]) == len(signatures) i = 1 if len(signatures) > 1 else '' for sig_pair, sig_type in signatures: print(" r{0}: {1:#x}\n s{0}: {2:#x}".format(i, *sig_pair)) if not sig_types_identical and tx_out: print(" z{}: {:#x} {}".format(i, tx.signature_hash(tx_out.script, idx, sig_type), sighash_type_to_string(sig_type))) if i: i += 1 if sig_types_identical and tx_out: print(" z:{} {:#x} {}".format(' ' if i else '', tx.signature_hash(tx_out.script, idx, sig_type), sighash_type_to_string(sig_type))) print("Output%s:" % ('s' if len(tx.txs_out) != 1 else '')) for idx, tx_out in enumerate(tx.txs_out): amount_mbtc = satoshi_to_mbtc(tx_out.coin_value) address = tx_out.bitcoin_address(netcode=netcode) or "(unknown)" print("%4d: %34s receives %12.5f mBTC" % (idx, address, amount_mbtc)) if disassembly_level > 0: for (pre_annotations, pc, opcode, instruction, post_annotations) in \ disassemble_scripts(b'', tx_out.script, signature_for_hash_type_f): for l in pre_annotations: print(" %s" % l) print( " %4x: %02x %s" % (pc, opcode, instruction)) for l in post_annotations: print(" %s" % l) if not missing_unspents: print("Total input %12.5f mBTC" % satoshi_to_mbtc(tx.total_in())) print( "Total output %12.5f mBTC" % satoshi_to_mbtc(tx.total_out())) if not missing_unspents: print("Total fees %12.5f mBTC" % satoshi_to_mbtc(tx.fee()))
def dump_tx(tx, netcode, verbose_signature, disassembly_level, do_trace, use_pdb): address_prefix = address_prefix_for_netcode(netcode) tx_bin = stream_to_bytes(tx.stream) # print("Tx_type:%2d" % tx.tx_type) if TransactionUtils.isCFTransation(tx): print("original_hash : %s" % tx.cf_header.original_hash) print("target_amount : %s" % tx.cf_header.target_amount) print("pubkey : %s" % tx.cf_header.pubkey) print("end_time : %s" % tx.cf_header.end_time) print("pre_hash : %s" % tx.cf_header.pre_hash) print("lack_amount : %s" % tx.cf_header.lack_amount) print("Version: %2d tx hash %s %d bytes " % (tx.version, tx.id(), len(tx_bin))) print("TransactionIn count: %d; TransactionOut count: %d" % (len(tx.txs_in), len(tx.txs_out))) if tx.lock_time == 0: meaning = "valid anytime" elif tx.lock_time < LOCKTIME_THRESHOLD: meaning = "valid after block index %d" % tx.lock_time else: when = datetime.datetime.utcfromtimestamp(tx.lock_time) meaning = "valid on or after %s utc" % when.isoformat() print("Lock time: %d (%s)" % (tx.lock_time, meaning)) print("Input%s:" % ('s' if len(tx.txs_in) != 1 else '')) missing_unspents = tx.missing_unspents() def trace_script(old_pc, opcode, data, stack, altstack, if_condition_stack, is_signature): from pycoin.tx.script.tools import disassemble_for_opcode_data print("%3d : %02x %s" % (old_pc, opcode, disassemble_for_opcode_data(opcode, data))) if use_pdb: import pdb from pycoin.serialize import b2h print("stack: [%s]" % ', '.join(b2h(s) for s in stack)) if len(altstack) > 0: print("altstack: %s" % altstack) if len(if_condition_stack) > 0: print("condition stack: %s" % ', '.join(int(s) for s in if_condition_stack)) pdb.set_trace() traceback_f = trace_script if do_trace or use_pdb else None for idx, tx_in in enumerate(tx.txs_in): if disassembly_level > 0: def signature_for_hash_type_f(hash_type, script): return tx.signature_hash(script, idx, hash_type) if tx.is_coinbase(): print("%4d: COINBASE %12.5f mBTC" % (idx, satoshi_to_mbtc(tx.total_in()))) else: suffix = "" if tx.missing_unspent(idx): tx_out = None address = tx_in.bitcoin_address(address_prefix=address_prefix) else: tx_out = tx.unspents[idx] sig_result = " sig ok" if tx.is_signature_ok( idx, traceback_f=traceback_f) else " BAD SIG" suffix = " %12.5f mBTC %s" % (satoshi_to_mbtc( tx_out.coin_value), sig_result) address = tx_out.bitcoin_address(netcode=netcode) t = "%4d: %34s from %s:%-4d%s" % (idx, address, b2h_rev(tx_in.previous_hash), tx_in.previous_index, suffix) print(t.rstrip()) if disassembly_level > 0: out_script = b'' if tx_out: out_script = tx_out.script for (pre_annotations, pc, opcode, instruction, post_annotations) in \ disassemble_scripts( tx_in.script, out_script, tx.lock_time, signature_for_hash_type_f): for l in pre_annotations: print(" %s" % l) print(" %4x: %02x %s" % (pc, opcode, instruction)) for l in post_annotations: print(" %s" % l) if verbose_signature: signatures = [] for opcode in opcode_list(tx_in.script): if not opcode.startswith("OP_"): try: signatures.append(parse_signature_blob( h2b(opcode))) except UnexpectedDER: pass if signatures: sig_types_identical = (zip(*signatures)[1]).count( signatures[0][1]) == len(signatures) i = 1 if len(signatures) > 1 else '' for sig_pair, sig_type in signatures: print(" r{0}: {1:#x}\n s{0}: {2:#x}".format( i, *sig_pair)) if not sig_types_identical and tx_out: print(" z{}: {:#x} {}".format( i, tx.signature_hash(tx_out.script, idx, sig_type), sighash_type_to_string(sig_type))) if i: i += 1 if sig_types_identical and tx_out: print(" z:{} {:#x} {}".format( ' ' if i else '', tx.signature_hash(tx_out.script, idx, sig_type), sighash_type_to_string(sig_type))) print("Output%s:" % ('s' if len(tx.txs_out) != 1 else '')) for idx, tx_out in enumerate(tx.txs_out): amount_mbtc = satoshi_to_mbtc(tx_out.coin_value) address = tx_out.bitcoin_address(netcode=netcode) or "(unknown)" print("%4d: %34s receives %12.5f mBTC" % (idx, address, amount_mbtc)) if disassembly_level > 0: for (pre_annotations, pc, opcode, instruction, post_annotations) in \ disassemble_scripts(b'', tx_out.script, tx.lock_time, signature_for_hash_type_f): for l in pre_annotations: print(" %s" % l) print(" %4x: %02x %s" % (pc, opcode, instruction)) for l in post_annotations: print(" %s" % l) if not missing_unspents: print("Total input %12.5f mBTC" % satoshi_to_mbtc(tx.total_in())) print("Total output %12.5f mBTC" % satoshi_to_mbtc(tx.total_out())) if not missing_unspents: print("Total fees %12.5f mBTC" % satoshi_to_mbtc(tx.fee()))
def to_codes(script): return tools.opcode_list(script)