Takes a signed transaction hex binary (and coin_symbol) and decodes it to JSON.

    Does NOT broadcast the transaction to the bitcoin network.
    Especially useful for testing/debugging and sanity checking
5793
def decodetx(tx_hex, coin_symbol='btc', api_key=None):
    '''
    
    '''

    assert is_valid_coin_symbol(coin_symbol)
    assert api_key, 'api_key required'

    url = make_url(coin_symbol, **dict(txs='decode'))

    params = {'token': api_key}
    data = {
        'tx': tx_hex,
        'token': api_key,
    }

    r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
    return get_valid_json(r)
185256
def sign_digest(hash_hex, privkey_hex, hashfunc=hashlib.sha256):
    
    if not isinstance(hash_hex, (str, unicode)):
        raise ValueError("hash hex is not a string")

    hash_hex = str(hash_hex)

    pk_i = decode_privkey_hex(privkey_hex)
    privk = ec.derive_private_key(pk_i, ec.SECP256K1(), default_backend())

    sig = privk.sign(hash_hex.decode('hex'), ec.ECDSA(utils.Prehashed(hashes.SHA256())))

    sig_r, sig_s = decode_dss_signature(sig)
    sigb64 = encode_signature(sig_r, sig_s)
    return sigb64
580789
def btc_script_deserialize(script):
    

    if isinstance(script, str) and re.match('^[0-9a-fA-F]*$', script):
       script = binascii.unhexlify(script)

    # output buffer
    out = []
    pos = 0

    while pos < len(script):
        # next script op...
        code = encoding.from_byte_to_int(script[pos])

        if code == 0:
            # empty (OP_0)
            out.append(None)
            pos += 1

        elif code <= 75:
            # literal numeric constant, followed by a slice of data.
            # push the slice of data.
            out.append(script[pos+1:pos+1+code])
            pos += 1 + code

        elif code <= 78:
            # OP_PUSHDATA1, OP_PUSHDATA2, OP_PUSHDATA4, followed by length and data
            # push the data itself
            szsz = pow(2, code - 76)
            sz = encoding.decode(script[pos+szsz: pos:-1], 256)
            out.append(script[pos + 1 + szsz : pos + 1 + szsz + sz])
            pos += 1 + szsz + sz

        elif code <= 96:
            # OP_1NEGATE, OP_RESERVED, OP_1 thru OP_16
            # pass -1 for OP_1NEGATE
            # pass 0 for OP_RESERVED (shouldn't be used anyway)
            # pass 1 thru 16 for OP_1 thru OP_16
            out.append(code - 80)
            pos += 1

        else:
            # raw opcode
            out.append(code)
            pos += 1

    # make sure each string is hex'ed
    out = encoding.json_changebase(out, lambda x: encoding.safe_hexlify(x))
    return out
399676
def btc_script_to_hex(script):
    

    hex_script = ''
    parts = script.split(' ')
    for part in parts:
        if part[0:3] == 'OP_':
            value = OPCODE_VALUES.get(part)
            if not value:
                raise ValueError("Unrecognized opcode {}".format(part))

            hex_script += "%0.2x" % value

        elif hashing.is_hex(part):
            hex_script += '%0.2x' % hashing.count_bytes(part) + part

        else:
            raise Exception('Invalid script - only opcodes and hex characters allowed.')

    return hex_script
776037
def broadcast_transaction(hex_tx, blockchain_client):
    
    if not isinstance(blockchain_client, BlockcypherClient):
        raise Exception('A BlockcypherClient object is required')

    url = '%s/txs/push' % (BLOCKCYPHER_BASE_URL)
    payload = json.dumps({'tx': hex_tx})
    r = requests.post(url, data=payload)

    try:
        data = r.json()
    except ValueError:
        raise Exception('Received non-JSON from blockcypher.com.')

    if 'tx' in data:
        reply = {}
        reply['tx_hash'] = data['tx']['hash']
        reply['success'] = True
        return reply
    else:
        err_str = 'Tx hash missing from blockcypher response: ' + str(data)
        raise Exception(err_str)
851933
def decrypt(self, token, signature=None):
        
        binary = rsa.decrypt(token, self.my_privkey)
        if signature:
            rsa.verify(binary, signature, self.his_pubkey)
        return binary
1270032
def sanitize_tx_data(unspents, outputs, fee, leftover, combine=True,
                     message=None, compressed=True, absolute_fee=False,
                     min_change=0, version='main'):
    

    outputs = outputs.copy()

    for i, output in enumerate(outputs):
        dest, amount, currency = output
        outputs[i] = (dest, currency_to_satoshi_cached(amount, currency))

    if not unspents:
        raise ValueError('Transactions must have at least one unspent.')

    # Temporary storage so all outputs precede messages.
    messages = []

    if message:
        message_chunks = chunk_data(message.encode('utf-8'), MESSAGE_LIMIT)

        for message in message_chunks:
            messages.append((message, 0))

    # Include return address in output count.
    # Calculate output size as a list (including return address).
    output_size = [len(address_to_scriptpubkey(o[0])) + 9 for o in outputs]
    output_size.append(len(messages) * (MESSAGE_LIMIT + 9))
    output_size.append(len(address_to_scriptpubkey(leftover)) + 9)
    sum_outputs = sum(out[1] for out in outputs)

    # Use Branch-and-Bound for coin selection:
    unspents[:], remaining = select_coins(
        sum_outputs, fee, output_size, min_change=min_change,
        absolute_fee=absolute_fee, consolidate=combine, unspents=unspents
    )

    if remaining > 0:
        outputs.append((leftover, remaining))

    # Sanity check: If spending from main-/testnet, then all output addresses must also be for main-/testnet.
    for output in outputs:
        dest, amount = output
        vs = get_version(dest)
        if vs and vs != version:
            raise ValueError('Cannot send to ' + vs + 'net address when '
                             'spending from a ' + version + 'net address.')

    outputs.extend(messages)

    return unspents, outputs
116794
def sign_singlesig(privkey_hex, plaintext):
    
    hash_hex = hashlib.sha256(plaintext).hexdigest()
    b64sig = virtualchain.ecdsalib.sign_digest(hash_hex, privkey_hex)
    sighex = binascii.hexlify(base64.b64decode(b64sig))
    pubkey_hex = virtualchain.ecdsalib.ecdsa_private_key(privkey_hex).public_key().to_hex()
    return base64.b64encode(virtualchain.btc_script_serialize([sighex, pubkey_hex]).decode('hex'))
1101661
def signingPayloadState(self, identifier=None):
        
        if self.operation.get(TXN_TYPE) == ATTRIB:
            d = deepcopy(super().signingPayloadState(identifier=identifier))
            op = d[OPERATION]
            keyName = {RAW, ENC, HASH}.intersection(set(op.keys())).pop()
            op[keyName] = sha256(op[keyName].encode()).hexdigest()
            return d
        return super().signingPayloadState(identifier=identifier)
902272
def serialize_input(input, signature_script_hex=''):
    
    if not (isinstance(input, dict) and 'transaction_hash' in input \
            and 'output_index' in input):
        raise Exception('Required parameters: transaction_hash, output_index')

    if is_hex(str(input['transaction_hash'])) and len(str(input['transaction_hash'])) != 64:
        raise Exception("Transaction hash '%s' must be 32 bytes" % input['transaction_hash'])

    elif not is_hex(str(input['transaction_hash'])) and len(str(input['transaction_hash'])) != 32:
        raise Exception("Transaction hash '%s' must be 32 bytes" % hexlify(input['transaction_hash']))

    if not 'sequence' in input:
        input['sequence'] = UINT_MAX

    return ''.join([
        flip_endian(input['transaction_hash']),
        hexlify(struct.pack('<I', input['output_index'])),
        hexlify(variable_length_int(len(signature_script_hex)/2)),
        signature_script_hex,
        hexlify(struct.pack('<I', input['sequence']))
    ])
455040
function verifySecondSignature (transaction, publicKey) {
	var bytes = getBytes(transaction);
	var data2 = Buffer.alloc(bytes.length - 64);

	for (var i = 0; i < data2.length; i++) {
		data2[i] = bytes[i];
	}

	var hash = crypto.createHash('sha256').update(data2.toString('hex'), 'hex').digest();

	var signSignatureBuffer = Buffer.from(transaction.signSignature, 'hex');
	var publicKeyBuffer = Buffer.from(publicKey, 'hex');
	var res = naclInstance.crypto_sign_verify_detached(signSignatureBuffer, hash, publicKeyBuffer);

	return res;
}
827901
def _decode_token_json(token):
    
    header, payload, raw_signatures, signing_inputs = _unpack_token_json(token)
    token = {
        'header': header,
        'payload': payload,
        'signature': [base64url_encode(rs) for rs in raw_signatures]
    }
    return token
747225
def decode(self, tx):
        
        if not isinstance(self._service, BitcoinBlockrService):
            raise NotImplementedError('Currently only supported for "blockr.io"')
        return self._service.decode(tx)
1256136
def _SignedBinaryURNFromID(binary_id
                          ):
  """"""
  binary_type = binary_id.binary_type
  if binary_type == rdf_objects.SignedBinaryID.BinaryType.PYTHON_HACK:
    return GetAFF4PythonHackRoot().Add(binary_id.path)
  elif binary_type == rdf_objects.SignedBinaryID.BinaryType.EXECUTABLE:
    return GetAFF4ExecutablesRoot().Add(binary_id.path)
  else:
    raise ValueError("Unknown binary type %s." % binary_type)
1005988
def btc_tx_make_input_signature_segwit(tx, idx, prevout_amount, prevout_script, privkey_str, hashcode):
    
    # always compressed
    if len(privkey_str) == 64:
        privkey_str += '01'

    pk = ecdsalib.ecdsa_private_key(str(privkey_str))
    pubk = pk.public_key()
    
    priv = pk.to_hex()

    # must always be compressed
    pub = keylib.key_formatting.compress(pubk.to_hex())
    sighash = btc_tx_sighash_segwit(tx, idx, prevout_amount, prevout_script, hashcode=hashcode)
    
    # sign using uncompressed private key
    # pk_uncompressed_hex, pubk_uncompressed_hex = ecdsalib.get_uncompressed_private_and_public_keys(priv)
    sigb64 = ecdsalib.sign_digest( sighash, priv )

    # sanity check 
    # assert ecdsalib.verify_digest( txhash, pubk_uncompressed_hex, sigb64 )

    sig_r, sig_s = ecdsalib.decode_signature(sigb64)
    sig_bin = btc_tx_der_encode_signature(sig_r, sig_s)
    sig = sig_bin.encode('hex') + encoding.encode(hashcode, 16, 2)

    # print 'segwit signature: {}'.format(sig)
    return sig
1026207
def from_hex_key(cls, key, network=BitcoinMainNet):
        
        if len(key) == 130 or len(key) == 66:
            # It might be a hexlified byte array
            try:
                key = unhexlify(key)
            except TypeError:
                pass
        key = ensure_bytes(key)

        compressed = False
        id_byte = key[0]
        if not isinstance(id_byte, six.integer_types):
            id_byte = ord(id_byte)
        if id_byte == 4:
            # Uncompressed public point
            # 1B ID + 32B x coord + 32B y coord = 65 B
            if len(key) != 65:
                raise KeyParseError("Invalid key length")
            public_pair = PublicPair(
                long_or_int(hexlify(key[1:33]), 16),
                long_or_int(hexlify(key[33:]), 16))
        elif id_byte in [2, 3]:
            # Compressed public point!
            compressed = True
            if len(key) != 33:
                raise KeyParseError("Invalid key length")
            y_odd = bool(id_byte & 0x01)  # 0 even, 1 odd
            x = long_or_int(hexlify(key[1:]), 16)
            # The following x-to-pair algorithm was lifted from pycoin
            # I still need to sit down an understand it. It is also described
            # in http://www.secg.org/collateral/sec1_final.pdf
            curve = SECP256k1.curve
            p = curve.p()
            # For SECP256k1, curve.a() is 0 and curve.b() is 7, so this is
            # effectively (x ** 3 + 7) % p, but the full equation is kept
            # for just-in-case-the-curve-is-broken future-proofing
            alpha = (pow(x, 3, p) + curve.a() * x + curve.b()) % p
            beta = square_root_mod_prime(alpha, p)
            y_even = not y_odd
            if y_even == bool(beta & 1):
                public_pair = PublicPair(x, p - beta)
            else:
                public_pair = PublicPair(x, beta)
        else:
            raise KeyParseError("The given key is not in a known format.")
        return cls.from_public_pair(public_pair, network=network,
                                    compressed=compressed)
831673
def tx_hash( cls, tx ):
        
        tx_hex = bits.btc_bitcoind_tx_serialize( tx )
        tx_hash = hashing.bin_double_sha256(tx_hex.decode('hex'))[::-1].encode('hex')
        return tx_hash