Ejemplo n.º 1
0
def construct_data_tx(data, _from):
    # inputs
    coins_from = blockchain_info.coin_sources_for_address(_from)
    if len(coins_from) < 1:
        return "No free outputs to spend"
    max_coin_value, _, max_idx, max_h, max_script = max(
        (tx_out.coin_value, random(), idx, h, tx_out.script)
        for h, idx, tx_out in coins_from)
    unsigned_txs_out = [
        UnsignedTxOut(max_h, max_idx, max_coin_value, max_script)
    ]

    # outputs
    if max_coin_value > TX_FEES * 2:
        return 'max output greater than twice the threshold, too big.'
    if max_coin_value < TX_FEES:
        return 'max output smaller than threshold, too small.'
    script_text = 'OP_RETURN %s' % data.encode('hex')
    script_bin = tools.compile(script_text)
    new_txs_out = [TxOut(0, script_bin)]
    version = 1
    lock_time = 0
    unsigned_tx = UnsignedTx(version, unsigned_txs_out, new_txs_out, lock_time)
    return unsigned_tx
Ejemplo n.º 2
0
    def sign_tx(self, hex_tx, tx_input, netcode):
        """
        Sign the transaction with private key
        :param hex_tx:
        :param tx_input:
        :param netcode:
        :return:
        """
        logging.info('Signing tx with private key')

        self.secret_manager.start()
        wif = self.secret_manager.get_wif()

        transaction = Tx.from_hex(hex_tx)
        allowable_wif_prefixes = wif_prefix_for_netcode(netcode)

        se = wif_to_secret_exponent(wif, allowable_wif_prefixes)
        lookup = build_hash160_lookup([se])
        transaction.set_unspents(
            [TxOut(coin_value=tx_input.coin_value, script=tx_input.script)])
        signed_tx = transaction.sign(lookup)
        self.secret_manager.stop()
        logging.info('Finished signing transaction')
        return signed_tx
Ejemplo n.º 3
0
Archivo: tx.py Proyecto: stafur/pycoin
def main():
    parser = argparse.ArgumentParser(
        description="Manipulate bitcoin (or alt coin) transactions.",
        epilog=EPILOG)

    parser.add_argument('-t', "--transaction-version", type=int,
                        help='Transaction version, either 1 (default) or 3 (not yet supported).')

    parser.add_argument('-l', "--lock-time", type=parse_locktime, help='Lock time; either a block'
                        'index, or a date/time (example: "2014-01-01T15:00:00"')

    parser.add_argument('-n', "--network", default="BTC",
                        help='Define network code (M=Bitcoin mainnet, T=Bitcoin testnet).')

    parser.add_argument('-a', "--augment", action='store_true',
                        help='augment tx by adding any missing spendable metadata by fetching'
                             ' inputs from cache and/or web services')

    parser.add_argument("-i", "--fetch-spendables", metavar="address", action="append",
                        help='Add all unspent spendables for the given bitcoin address. This information'
                        ' is fetched from web services.')

    parser.add_argument('-f', "--private-key-file", metavar="path-to-private-keys", action="append",
                        help='file containing WIF or BIP0032 private keys. If file name ends with .gpg, '
                        '"gpg -d" will be invoked automatically. File is read one line at a time, and if '
                        'the file contains only one WIF per line, it will also be scanned for a bitcoin '
                        'address, and any addresses found will be assumed to be public keys for the given'
                        ' private key.',
                        type=argparse.FileType('r'))

    parser.add_argument('-g', "--gpg-argument", help='argument to pass to gpg (besides -d).', default='')

    parser.add_argument("--remove-tx-in", metavar="tx_in_index_to_delete", action="append", type=int,
                        help='remove a tx_in')

    parser.add_argument("--remove-tx-out", metavar="tx_out_index_to_delete", action="append", type=int,
                        help='remove a tx_out')

    parser.add_argument('-F', "--fee", help='fee, in satoshis, to pay on transaction, or '
                        '"standard" to auto-calculate. This is only useful if the "split pool" '
                        'is used; otherwise, the fee is automatically set to the unclaimed funds.',
                        default="standard", metavar="transaction-fee", type=parse_fee)

    parser.add_argument('-C', "--cache", help='force the resultant transaction into the transaction cache.'
                        ' Mostly for testing.', action='store_true'),

    parser.add_argument('-u', "--show-unspents", action='store_true',
                        help='show TxOut items for this transaction in Spendable form.')

    parser.add_argument('-b', "--bitcoind-url",
                        help='URL to bitcoind instance to validate against (http://user:pass@host:port).')

    parser.add_argument('-o', "--output-file", metavar="path-to-output-file", type=argparse.FileType('wb'),
                        help='file to write transaction to. This supresses most other output.')

    parser.add_argument("argument", nargs="+", help='generic argument: can be a hex transaction id '
                        '(exactly 64 characters) to be fetched from cache or a web service;'
                        ' a transaction as a hex string; a path name to a transaction to be loaded;'
                        ' a spendable 4-tuple of the form tx_id/tx_out_idx/script_hex/satoshi_count '
                        'to be added to TxIn list; an address/satoshi_count to be added to the TxOut '
                        'list; an address to be added to the TxOut list and placed in the "split'
                        ' pool".')

    args = parser.parse_args()

    # defaults

    txs = []
    spendables = []
    payables = []

    key_iters = []

    TX_ID_RE = re.compile(r"^[0-9a-fA-F]{64}$")

    # there are a few warnings we might optionally print out, but only if
    # they are relevant. We don't want to print them out multiple times, so we
    # collect them here and print them at the end if they ever kick in.

    warning_tx_cache = None
    warning_get_tx = None
    warning_spendables = None

    if args.private_key_file:
        wif_re = re.compile(r"[1-9a-km-zA-LMNP-Z]{51,111}")
        # address_re = re.compile(r"[1-9a-kmnp-zA-KMNP-Z]{27-31}")
        for f in args.private_key_file:
            if f.name.endswith(".gpg"):
                gpg_args = ["gpg", "-d"]
                if args.gpg_argument:
                    gpg_args.extend(args.gpg_argument.split())
                gpg_args.append(f.name)
                popen = subprocess.Popen(gpg_args, stdout=subprocess.PIPE)
                f = popen.stdout
            for line in f.readlines():
                # decode
                if isinstance(line, bytes):
                    line = line.decode("utf8")
                # look for WIFs
                possible_keys = wif_re.findall(line)

                def make_key(x):
                    try:
                        return Key.from_text(x)
                    except Exception:
                        return None

                keys = [make_key(x) for x in possible_keys]
                for key in keys:
                    if key:
                        key_iters.append((k.wif() for k in key.subkeys("")))

                # if len(keys) == 1 and key.hierarchical_wallet() is None:
                #    # we have exactly 1 WIF. Let's look for an address
                #   potential_addresses = address_re.findall(line)

    # we create the tx_db lazily
    tx_db = None

    for arg in args.argument:

        # hex transaction id
        if TX_ID_RE.match(arg):
            if tx_db is None:
                warning_tx_cache = message_about_tx_cache_env()
                warning_get_tx = message_about_get_tx_env()
                tx_db = get_tx_db()
            tx = tx_db.get(h2b_rev(arg))
            if not tx:
                for m in [warning_tx_cache, warning_get_tx, warning_spendables]:
                    if m:
                        print("warning: %s" % m, file=sys.stderr)
                parser.error("can't find Tx with id %s" % arg)
            txs.append(tx)
            continue

        # hex transaction data
        try:
            tx = Tx.tx_from_hex(arg)
            txs.append(tx)
            continue
        except Exception:
            pass

        try:
            key = Key.from_text(arg)
            # TODO: check network
            if key.wif() is None:
                payables.append((key.address(), 0))
                continue
            # TODO: support paths to subkeys
            key_iters.append((k.wif() for k in key.subkeys("")))
            continue
        except Exception:
            pass

        if os.path.exists(arg):
            try:
                with open(arg, "rb") as f:
                    if f.name.endswith("hex"):
                        f = io.BytesIO(codecs.getreader("hex_codec")(f).read())
                    tx = Tx.parse(f)
                    txs.append(tx)
                    try:
                        tx.parse_unspents(f)
                    except Exception as ex:
                        pass
                    continue
            except Exception:
                pass

        parts = arg.split("/")
        if len(parts) == 4:
            # spendable
            try:
                spendables.append(Spendable.from_text(arg))
                continue
            except Exception:
                pass

        # TODO: fix allowable_prefixes
        allowable_prefixes = b'\0'
        if len(parts) == 2 and encoding.is_valid_bitcoin_address(
                parts[0], allowable_prefixes=allowable_prefixes):
            try:
                payables.append(parts)
                continue
            except ValueError:
                pass

        parser.error("can't parse %s" % arg)

    if args.fetch_spendables:
        warning_spendables = message_about_spendables_for_address_env()
        for address in args.fetch_spendables:
            spendables.extend(spendables_for_address(address))

    for tx in txs:
        if tx.missing_unspents() and args.augment:
            if tx_db is None:
                warning_tx_cache = message_about_tx_cache_env()
                warning_get_tx = message_about_get_tx_env()
                tx_db = get_tx_db()
            tx.unspents_from_db(tx_db, ignore_missing=True)

    txs_in = []
    txs_out = []
    unspents = []
    # we use a clever trick here to keep each tx_in corresponding with its tx_out
    for tx in txs:
        smaller = min(len(tx.txs_in), len(tx.txs_out))
        txs_in.extend(tx.txs_in[:smaller])
        txs_out.extend(tx.txs_out[:smaller])
        unspents.extend(tx.unspents[:smaller])
    for tx in txs:
        smaller = min(len(tx.txs_in), len(tx.txs_out))
        txs_in.extend(tx.txs_in[smaller:])
        txs_out.extend(tx.txs_out[smaller:])
        unspents.extend(tx.unspents[smaller:])
    for spendable in spendables:
        txs_in.append(spendable.tx_in())
        unspents.append(spendable)
    for address, coin_value in payables:
        script = standard_tx_out_script(address)
        txs_out.append(TxOut(coin_value, script))

    lock_time = args.lock_time
    version = args.transaction_version

    # if no lock_time is explicitly set, inherit from the first tx or use default
    if lock_time is None:
        if txs:
            lock_time = txs[0].lock_time
        else:
            lock_time = DEFAULT_LOCK_TIME

    # if no version is explicitly set, inherit from the first tx or use default
    if version is None:
        if txs:
            version = txs[0].version
        else:
            version = DEFAULT_VERSION

    if args.remove_tx_in:
        s = set(args.remove_tx_in)
        txs_in = [tx_in for idx, tx_in in enumerate(txs_in) if idx not in s]

    if args.remove_tx_out:
        s = set(args.remove_tx_out)
        txs_out = [tx_out for idx, tx_out in enumerate(txs_out) if idx not in s]

    tx = Tx(txs_in=txs_in, txs_out=txs_out, lock_time=lock_time, version=version, unspents=unspents)

    fee = args.fee
    try:
        distribute_from_split_pool(tx, fee)
    except ValueError as ex:
        print("warning: %s" % ex.args[0], file=sys.stderr)

    unsigned_before = tx.bad_signature_count()
    if unsigned_before > 0 and key_iters:
        def wif_iter(iters):
            while len(iters) > 0:
                for idx, iter in enumerate(iters):
                    try:
                        wif = next(iter)
                        yield wif
                    except StopIteration:
                        iters = iters[:idx] + iters[idx+1:]
                        break

        print("signing...", file=sys.stderr)
        sign_tx(tx, wif_iter(key_iters))

    unsigned_after = tx.bad_signature_count()
    if unsigned_after > 0 and key_iters:
        print("warning: %d TxIn items still unsigned" % unsigned_after, file=sys.stderr)

    if len(tx.txs_in) == 0:
        print("warning: transaction has no inputs", file=sys.stderr)

    if len(tx.txs_out) == 0:
        print("warning: transaction has no outputs", file=sys.stderr)

    include_unspents = (unsigned_after > 0)
    tx_as_hex = tx.as_hex(include_unspents=include_unspents)

    if args.output_file:
        f = args.output_file
        if f.name.endswith(".hex"):
            f.write(tx_as_hex.encode("utf8"))
        else:
            tx.stream(f)
            if include_unspents:
                tx.stream_unspents(f)
        f.close()
    elif args.show_unspents:
        for spendable in tx.tx_outs_as_spendable():
            print(spendable.as_text())
    else:
        if not tx.missing_unspents():
            check_fees(tx)
        dump_tx(tx, args.network)
        if include_unspents:
            print("including unspents in hex dump since transaction not fully signed")
        print(tx_as_hex)

    if args.cache:
        if tx_db is None:
            warning_tx_cache = message_about_tx_cache_env()
            warning_get_tx = message_about_get_tx_env()
            tx_db = get_tx_db()
        tx_db.put(tx)

    if args.bitcoind_url:
        if tx_db is None:
            warning_tx_cache = message_about_tx_cache_env()
            warning_get_tx = message_about_get_tx_env()
            tx_db = get_tx_db()
        validate_bitcoind(tx, tx_db, args.bitcoind_url)

    if tx.missing_unspents():
        print("\n** can't validate transaction as source transactions missing", file=sys.stderr)
    else:
        try:
            if tx_db is None:
                warning_tx_cache = message_about_tx_cache_env()
                warning_get_tx = message_about_get_tx_env()
                tx_db = get_tx_db()
            tx.validate_unspents(tx_db)
            print('all incoming transaction values validated')
        except BadSpendableError as ex:
            print("\n**** ERROR: FEES INCORRECTLY STATED: %s" % ex.args[0], file=sys.stderr)
        except Exception as ex:
            print("\n*** can't validate source transactions as untampered: %s" %
                  ex.args[0], file=sys.stderr)

    # print warnings
    for m in [warning_tx_cache, warning_get_tx, warning_spendables]:
        if m:
            print("warning: %s" % m, file=sys.stderr)
Ejemplo n.º 4
0
def build_credit_tx(script_out_bin, coin_value=0):
    txs_in = [TxIn(b'\0' * 32, 4294967295, b'\0\0', sequence=4294967295)]
    txs_out = [TxOut(coin_value, script_out_bin)]
    return Tx(1, txs_in, txs_out)
Ejemplo n.º 5
0
    def _test_sighash_single(self, netcode):
        k0 = Key(secret_exponent=PRIV_KEYS[0],
                 is_compressed=True,
                 netcode=netcode)
        k1 = Key(secret_exponent=PRIV_KEYS[1],
                 is_compressed=True,
                 netcode=netcode)
        k2 = Key(secret_exponent=PRIV_KEYS[2],
                 is_compressed=True,
                 netcode=netcode)
        k3 = Key(secret_exponent=PRIV_KEYS[3],
                 is_compressed=True,
                 netcode=netcode)
        k4 = Key(secret_exponent=PRIV_KEYS[4],
                 is_compressed=True,
                 netcode=netcode)
        k5 = Key(secret_exponent=PRIV_KEYS[5],
                 is_compressed=True,
                 netcode=netcode)

        # Fake a coinbase transaction
        coinbase_tx = Tx.coinbase_tx(k0.sec(), 500000000)
        coinbase_tx.txs_out.append(
            TxOut(1000000000,
                  pycoin_compile('%s OP_CHECKSIG' % b2h(k1.sec()))))
        coinbase_tx.txs_out.append(
            TxOut(1000000000,
                  pycoin_compile('%s OP_CHECKSIG' % b2h(k2.sec()))))

        self.assertEqual(
            '2acbe1006f7168bad538b477f7844e53de3a31ffddfcfc4c6625276dd714155a',
            b2h_rev(coinbase_tx.hash()))

        # Make the test transaction
        txs_in = [
            TxIn(coinbase_tx.hash(), 0),
            TxIn(coinbase_tx.hash(), 1),
            TxIn(coinbase_tx.hash(), 2),
        ]
        txs_out = [
            TxOut(900000000, standard_tx_out_script(k3.address())),
            TxOut(800000000, standard_tx_out_script(k4.address())),
            TxOut(800000000, standard_tx_out_script(k5.address())),
        ]
        tx = Tx(1, txs_in, txs_out)
        tx.set_unspents(coinbase_tx.txs_out)

        self.assertEqual(
            '791b98ef0a3ac87584fe273bc65abd89821569fd7c83538ac0625a8ca85ba587',
            b2h_rev(tx.hash()))

        sig_type = SIGHASH_SINGLE

        sig_hash = tx.signature_hash(coinbase_tx.txs_out[0].script, 0,
                                     sig_type)
        self.assertEqual(
            'cc52d785a3b4133504d1af9e60cd71ca422609cb41df3a08bbb466b2a98a885e',
            b2h(to_bytes_32(sig_hash)))

        sig = sigmake(k0, sig_hash, sig_type)
        self.assertTrue(sigcheck(k0, sig_hash, sig[:-1]))

        tx.txs_in[0].script = pycoin_compile(b2h(sig))
        self.assertTrue(tx.is_signature_ok(0))

        sig_hash = tx.signature_hash(coinbase_tx.txs_out[1].script, 1,
                                     sig_type)
        self.assertEqual(
            '93bb883d70fccfba9b8aa2028567aca8357937c65af7f6f5ccc6993fd7735fb7',
            b2h(to_bytes_32(sig_hash)))

        sig = sigmake(k1, sig_hash, sig_type)
        self.assertTrue(sigcheck(k1, sig_hash, sig[:-1]))

        tx.txs_in[1].script = pycoin_compile(b2h(sig))
        self.assertTrue(tx.is_signature_ok(1))

        sig_hash = tx.signature_hash(coinbase_tx.txs_out[2].script, 2,
                                     sig_type)
        self.assertEqual(
            '53ef7f67c3541bffcf4e0d06c003c6014e2aa1fb38ff33240b3e1c1f3f8e2a35',
            b2h(to_bytes_32(sig_hash)))

        sig = sigmake(k2, sig_hash, sig_type)
        self.assertTrue(sigcheck(k2, sig_hash, sig[:-1]))

        tx.txs_in[2].script = pycoin_compile(b2h(sig))
        self.assertTrue(tx.is_signature_ok(2))

        sig_type = SIGHASH_SINGLE | SIGHASH_ANYONECANPAY

        sig_hash = tx.signature_hash(coinbase_tx.txs_out[0].script, 0,
                                     sig_type)
        self.assertEqual(
            '2003393d246a7f136692ce7ab819c6eadc54ffea38eb4377ac75d7d461144e75',
            b2h(to_bytes_32(sig_hash)))

        sig = sigmake(k0, sig_hash, sig_type)
        self.assertTrue(sigcheck(k0, sig_hash, sig[:-1]))

        tx.txs_in[0].script = pycoin_compile(b2h(sig))
        self.assertTrue(tx.is_signature_ok(0))

        sig_hash = tx.signature_hash(coinbase_tx.txs_out[1].script, 1,
                                     sig_type)
        self.assertEqual(
            'e3f469ac88e9f35e8eff0bd8ad4ad3bf899c80eb7645947d60860de4a08a35df',
            b2h(to_bytes_32(sig_hash)))

        sig = sigmake(k1, sig_hash, sig_type)
        self.assertTrue(sigcheck(k1, sig_hash, sig[:-1]))

        tx.txs_in[1].script = pycoin_compile(b2h(sig))
        self.assertTrue(tx.is_signature_ok(1))

        sig_hash = tx.signature_hash(coinbase_tx.txs_out[2].script, 2,
                                     sig_type)
        self.assertEqual(
            'bacd7c3ab79cad71807312677c1788ad9565bf3c00ab9a153d206494fb8b7e6a',
            b2h(to_bytes_32(sig_hash)))

        sig = sigmake(k2, sig_hash, sig_type)
        self.assertTrue(sigcheck(k2, sig_hash, sig[:-1]))

        tx.txs_in[2].script = pycoin_compile(b2h(sig))
        self.assertTrue(tx.is_signature_ok(2))
Ejemplo n.º 6
0
def make_bare_tx(network, from_address, to_address, redeem_script, version=1):

    # <Tx> components
    spendables = []
    ins = []
    outs = []

    # estimate the final (signed) bytesize per input based on the redeemscript
    in_size = estimate_input_size(redeem_script)

    # initialize size and amount counters
    in_amount = Decimal(0)
    est_size = TX_COMPONENTS.version + TX_COMPONENTS.out_count + TX_COMPONENTS.in_count

    # add output size (we"ll only have 1)
    est_size += TX_COMPONENTS.out_scriptlen + TX_COMPONENTS.out_scriptsize + TX_COMPONENTS.out_scriptlen

    unspent_response = sochain_get_unspents(network, from_address)

    unspents = unspent_response.get("txs", [])

    # iterate over unspents
    for tx in unspents:

        value = Decimal(tx.get("value")) * Decimal(1e8)
        in_amount += value

        script = h2b(tx.get("script_hex"))
        # for now: test if the in_script we figured we would need, actually matches the in script :D

        # reverse that tx hash
        txhex = tx.get("txid")
        prevtx = h2b_rev(txhex)

        # output index
        outnum = tx.get("output_no")

        # create "spendable"
        spdbl = Spendable(value, script, prevtx, outnum)
        spendables.append(spdbl)

        # also create this as input
        as_input = spdbl.tx_in()
        as_input.sigs = []
        ins.append(as_input)

        # add the estimated size per input
        est_size += in_size

    # calc fee and out amount
    fee = Decimal(math.ceil(
        est_size / 1000.0)) * Decimal(1e8) * NETWORK_FEES.get(network)
    out_amount = in_amount - fee

    if (is_p2sh(to_address)):
        outscript = make_payto_script(to_address)
    else:
        outscript = make_payto_address(to_address)

    # create output
    outs.append(TxOut(out_amount, outscript))

    # create bare tx without sigs
    tx = Tx(version, ins, outs, 0, spendables)

    return tx
Ejemplo n.º 7
0
def main():
    parser = create_parser()
    args = parser.parse_args()

    (txs, spendables, payables, key_iters, p2sh_lookup, tx_db,
     warning_tx_cache, warning_tx_for_tx_hash,
     warning_spendables) = parse_context(args, parser)

    txs_in = []
    txs_out = []
    unspents = []

    # we use a clever trick here to keep each tx_in corresponding with its tx_out
    for tx in txs:
        smaller = min(len(tx.txs_in), len(tx.txs_out))
        txs_in.extend(tx.txs_in[:smaller])
        txs_out.extend(tx.txs_out[:smaller])
        unspents.extend(tx.unspents[:smaller])
    for tx in txs:
        smaller = min(len(tx.txs_in), len(tx.txs_out))
        txs_in.extend(tx.txs_in[smaller:])
        txs_out.extend(tx.txs_out[smaller:])
        unspents.extend(tx.unspents[smaller:])
    for spendable in spendables:
        txs_in.append(spendable.tx_in())
        unspents.append(spendable)
    for address, coin_value in payables:
        script = standard_tx_out_script(address)
        txs_out.append(TxOut(coin_value, script))

    lock_time = args.lock_time
    version = args.transaction_version

    # if no lock_time is explicitly set, inherit from the first tx or use default
    if lock_time is None:
        if txs:
            lock_time = txs[0].lock_time
        else:
            lock_time = DEFAULT_LOCK_TIME

    # if no version is explicitly set, inherit from the first tx or use default
    if version is None:
        if txs:
            version = txs[0].version
        else:
            version = DEFAULT_VERSION

    if args.remove_tx_in:
        s = set(args.remove_tx_in)
        txs_in = [tx_in for idx, tx_in in enumerate(txs_in) if idx not in s]

    if args.remove_tx_out:
        s = set(args.remove_tx_out)
        txs_out = [
            tx_out for idx, tx_out in enumerate(txs_out) if idx not in s
        ]

    tx = Tx(txs_in=txs_in,
            txs_out=txs_out,
            lock_time=lock_time,
            version=version,
            unspents=unspents)

    fee = args.fee
    try:
        distribute_from_split_pool(tx, fee)
    except ValueError as ex:
        print("warning: %s" % ex.args[0], file=sys.stderr)

    unsigned_before = tx.bad_signature_count()
    unsigned_after = unsigned_before
    if unsigned_before > 0 and key_iters:

        def wif_iter(iters):
            while len(iters) > 0:
                for idx, iter in enumerate(iters):
                    try:
                        wif = next(iter)
                        yield wif
                    except StopIteration:
                        iters = iters[:idx] + iters[idx + 1:]
                        break

        print("signing...", file=sys.stderr)
        sign_tx(tx, wif_iter(key_iters), p2sh_lookup=p2sh_lookup)

        unsigned_after = tx.bad_signature_count()
        if unsigned_after > 0:
            print("warning: %d TxIn items still unsigned" % unsigned_after,
                  file=sys.stderr)

    if len(tx.txs_in) == 0:
        print("warning: transaction has no inputs", file=sys.stderr)

    if len(tx.txs_out) == 0:
        print("warning: transaction has no outputs", file=sys.stderr)

    include_unspents = (unsigned_after > 0)
    tx_as_hex = tx.as_hex(include_unspents=include_unspents)

    if args.output_file:
        f = args.output_file
        if f.name.endswith(".hex"):
            f.write(tx_as_hex.encode("utf8"))
        else:
            tx.stream(f)
            if include_unspents:
                tx.stream_unspents(f)
        f.close()
    elif args.show_unspents:
        for spendable in tx.tx_outs_as_spendable():
            print(spendable.as_text())
    else:
        if not tx.missing_unspents():
            check_fees(tx)
        dump_tx(tx, args.network, args.verbose_signature, args.disassemble,
                args.trace, args.pdb)
        if include_unspents:
            print(
                "including unspents in hex dump since transaction not fully signed"
            )
        print(tx_as_hex)

    if args.cache:
        if tx_db is None:
            warning_tx_cache = message_about_tx_cache_env()
            warning_tx_for_tx_hash = message_about_tx_for_tx_hash_env(
                args.network)
            tx_db = get_tx_db(args.network)
        tx_db.put(tx)

    if args.bitcoind_url:
        if tx_db is None:
            warning_tx_cache = message_about_tx_cache_env()
            warning_tx_for_tx_hash = message_about_tx_for_tx_hash_env(
                args.network)
            tx_db = get_tx_db(args.network)
        validate_bitcoind(tx, tx_db, args.bitcoind_url)

    if tx.missing_unspents():
        print("\n** can't validate transaction as source transactions missing",
              file=sys.stderr)
    else:
        try:
            if tx_db is None:
                warning_tx_cache = message_about_tx_cache_env()
                warning_tx_for_tx_hash = message_about_tx_for_tx_hash_env(
                    args.network)
                tx_db = get_tx_db(args.network)
            tx.validate_unspents(tx_db)
            print('all incoming transaction values validated')
        except BadSpendableError as ex:
            print("\n**** ERROR: FEES INCORRECTLY STATED: %s" % ex.args[0],
                  file=sys.stderr)
        except Exception as ex:
            print(
                "\n*** can't validate source transactions as untampered: %s" %
                ex.args[0],
                file=sys.stderr)

    # print warnings
    for m in [warning_tx_cache, warning_tx_for_tx_hash, warning_spendables]:
        if m:
            print("warning: %s" % m, file=sys.stderr)
Ejemplo n.º 8
0
def main(params=[]):
    """
    Main function that deals with the information

    Args:
    -----
        params: List of arguments received from the command line.
    """
    banner = """
     ____  _            _        _           _          ____ ____   ____
    | __ )| | ___   ___| | _____| |__   __ _(_)_ __    / ___|___ \ / ___|
    |  _ \| |/ _ \ / __| |/ / __| '_ \ / _` | | '_ \  | |     __) | |
    | |_) | | (_) | (__|   < (__| | | | (_| | | | | | | |___ / __/| |___
    |____/|_|\___/ \___|_|\_\___|_| |_|\__,_|_|_| |_|  \____|_____|\____|

                    A PoC to push data to several blockchains by:
                            - Yaiza Rubio (@yrubiosec)
                            - Félix Brezo (@febrezo)"""
    print(banner)
    # Grabbing the parser
    parser = getParser()

    if params != None:
        args = parser.parse_args(params)
    else:
        args = parser.parse_args()

    # Getting the brain wallet
    network = raw_input(
        "\n> Choose type of network (BTC, XTN, LTC, XLT...) [XTN] ") or "XTN"
    while network not in VALID_NETWORKS:
        print("> The value provided '" + network +
              "' is not a possible option. Choose one of the following:\n" +
              json.dumps(VALID_NETWORKS.keys(), indent=2))
        network = raw_input(
            "\n> Choose type of network (BTC, XTN, LTC, XLT...) [XTN] "
        ) or "XTN"
    print("\tNetwork: " + network)

    # Defining the target address
    admin_type = None
    while admin_type not in ["brain", "other"]:
        admin_type = raw_input(
            "\n> Set ADMIN address: 'brain' or 'other'? [brain] ") or "brain"
        if admin_type == "brain":
            brain = raw_input("\n> Say word for the ADMIN brainwallet: ")
            print("\tWe will generate the details for the target address:")
            priv = generatePrivateKey(brain)
            src_address = priv.address()
        elif admin_type == "other":
            print(
                "\tNote that you might not know the private key of this address so you can lose your balance:"
            )
            src_WIF = raw_input(
                "\n> Set the admin private key in WIF format: ")
            #TODO:
            priv = Key.from_text(src_WIF)
        else:
            admin_type = raw_input(
                "\n> Set ADMIN address: 'brain' or 'other'? [brain] "
            ) or "brain"

    # Get the spendable outputs we are going to use to pay the fee
    print("\n> Choosing a provider!")
    provider = getProvider(network=network)
    spendables = provider.spendables_for_address(priv.address())

    # Summing it up
    source_balance = sum(spendable.coin_value for spendable in spendables)
    print("\tBalance: " + str(source_balance))

    if source_balance <= 0:
        print(
            "\n> No money in the account! You will need an account with some! Exiting!"
        )
        sys.exit()

    # Defining the message to be send
    message_str = raw_input("\n> Set message to send: ")
    # No more than 80 caracters please!
    if (len(message_str) > 80):
        sys.exit("Message must be 80 characters or less")
    print("\tMessage (string): " + message_str)
    message_hex = hexlify(message_str.encode()).decode('utf8')
    print("\tMessage (hexadecimal): " + message_hex)

    # Defining the target address
    target_type = None
    while target_type not in ["brain", "other"]:
        target_type = raw_input(
            "\n> Set target address: 'brain' or 'other'? [brain] ") or "brain"
        if target_type == "brain":
            brain_dst = raw_input("\n> Say word for the TARGET brainwallet: ")
            print("\tWe will generate the details for the target address:")
            target = generatePrivateKey(brain_dst)
            dst_address = target.address()
        elif target_type == "other":
            print(
                "\tNote that you might not know the private key of this address so you can lose your balance:"
            )
            dst_address = raw_input("\n> Set the target address: ")
        else:
            target_type = raw_input(
                "\n> Set target address: 'brain' or 'other'? [brain] "
            ) or "brain"

    # Defining the default fee
    try:
        fee = int(raw_input("\n> Set the fee [10000]: "))
    except:
        fee = 10000
    print("\tFee assigned: " + str(fee))

    # Generating the transaction
    print(
        "\n> We'll try to create the transaction using all the spendables for "
        + priv.address())
    # Creating the transaction
    tx = tx_utils.create_tx(spendables, [(dst_address, source_balance - fee)],
                            fee=fee)
    print("\tTx:\n" + str(tx))

    print("\n> We will create the OP_RETURN script for the message '" +
          message_str + "'.")
    # We need the hexadecimal representation of the message
    op_return_output_script = script.tools.compile("OP_RETURN %s" %
                                                   message_hex)
    print("\tOP_RETURN script:\n" + str([str(op_return_output_script)]))

    print("\n> Appending the new OP_RETURN script to the transaction:")
    tx.txs_out.append(TxOut(0, op_return_output_script))
    print("\tTx:\n" + str(tx))
    print("\tNumber of outputs: " + str(len(tx.txs_out)))
    print("\tDisplaying the outputs:\n")
    for o in tx.txs_out:
        print("\t\t- " + str(o))
    #print "\tDictionary representing the transaction:\n" + tx.__dict__

    print("\n> Signing the transaction:")
    tx_utils.sign_tx(tx, netcode=network, wifs=[priv.wif()])
    print("\tNow tx is a signed transaction:")
    print("\tTx:\n" + str(tx))

    print("\n> Showing the hexadecimal information of the SIGNED transaction:")
    print(tx.as_hex())

    if args.push:
        print("\n> We will try to push the signed transaction now:")
        pushTx(network=network, tx_hex=tx.as_hex())
    else:
        print("\n> You can push this transaction manually using curl:")
        print("\tcurl -d 'tx_hex=" + tx.as_hex() +
              "' https://chain.so/api/v2/send_tx/" + VALID_NETWORKS[network])
        print(
            "\n> You can also manually push this with the Web UI of BlockExplorer at <https://testnet.blockexplorer.com/tx/send>."
        )
        print(
            "\n> You might want to do it using Tor Browser Bundle or torify to not let even a trace to know who you are in the provider."
        )
Ejemplo n.º 9
0
                                   sec_keys=[key.sec()
                                             for key in keys[:M]]).script()

# multisig address. Just hash the redeem script
address = address_for_pay_to_script(underlying_script)

## going to create a spend from this address. This should be the code on the web server
spendables = insight.spendables_for_address(address)
txs_in = []
for s in spendables:
    print s
    txs_in.append(s.tx_in())

# make tx_out on web server
script = standard_tx_out_script(address)
tx_out = TxOut(100000, script)
txs_out = [tx_out]

tx1 = Tx(version=1, txs_in=txs_in, txs_out=txs_out)
tx1.set_unspents(txs_out)

txhex = tx1.as_hex(include_unspents=True)

# send txhex to private key server
tx2 = Tx.tx_from_hex(txhex)
script = standard_tx_out_script("1F8P3QEErMhm3fw6o23brRNQVaSMrG1maE")
tx_out = TxOut(50000, script)
script = standard_tx_out_script("1Dv9YWfVYMK1FjBhrCBc1diajSZKBj78MB")
tx2_out = TxOut(50000, script)

txs_out = [tx_out, tx2_out]
Ejemplo n.º 10
0
def format_msg(msg):
    op = 'OP_RETURN %s' % msg
    op = tools.compile(op)
    return TxOut(10**4, op)