Exemplo n.º 1
0
def get_speendable(address):
    URL = "%s%saddr/%s/utxo" % ('https://test-insight.bitpay.com', '/api/',
                                from_address)
    utxos = json.loads(urlopen(URL).read().decode("utf8"))

    utxo = utxos[0]

    return Spendable(utxo['amount'], h2b(utxo.get("scriptPubKey")),
                     h2b_rev(utxo.get("txid")), utxo.get("vout"))
Exemplo n.º 2
0
    def spendables_for_address(self, address, amount=None):
        """
        Return a list of Spendable objects for the
        given bitcoin address.
        """
        if amount is None:
            spendables = []
            url_append = "?unspentOnly=true&token=%s&includeScript=true" % self.api_key
            url = self.base_url("addrs/%s%s" % (address, url_append))
            result = json.loads(urlopen(url).read().decode("utf8"))
            for txn in result.get("txrefs", []):
                coin_value = txn.get("value")
                script = h2b(txn.get("script"))
                previous_hash = h2b_rev(txn.get("tx_hash"))
                previous_index = txn.get("tx_output_n")
                spendables.append(
                    Spendable(coin_value, script, previous_hash,
                              previous_index))
            return spendables

        else:
            spendables = []
            url_append = "?unspentOnly=true&token=%s&includeScript=true" % self.api_key
            url = self.base_url("addrs/%s%s" % (address, url_append))
            result = json.loads(urlopen(url).read().decode("utf8"))
            total_amount = 0
            list_spend = result.get("txrefs", [])
            if len(list_spend) == 0:
                raise Exception("No spendable outputs found")
            unspents = sorted(list_spend,
                              key=lambda d: d['value'],
                              reverse=True)
            for txn in unspents:
                coin_value = txn.get("value")
                total_amount = total_amount + coin_value
                script = h2b(txn.get("script"))
                previous_hash = h2b_rev(txn.get("tx_hash"))
                previous_index = txn.get("tx_output_n")
                spendables.append(
                    Spendable(coin_value, script, previous_hash,
                              previous_index))
                if total_amount > amount:
                    break
            return [spendables, total_amount]
Exemplo n.º 3
0
 def spendables_for_address(self, address, amount=None):
     """
     Return a list of Spendable objects for the
     given bitcoin address.
     """
     if amount == None:
         spendables = []
         r = json.loads(
             urlopen(self.base_url('get_tx_unspent',
                                   address)).read().decode("utf8"))
         for u in r['data']['txs']:
             coin_value = int(float(u['value']) * 100000000)
             script = h2b(u["script_hex"])
             previous_hash = h2b_rev(u["txid"])
             previous_index = u["output_no"]
             spendables.append(
                 Spendable(coin_value, script, previous_hash,
                           previous_index))
         return spendables
     else:
         spendables = []
         r = json.loads(
             urlopen(self.base_url('get_tx_unspent',
                                   address)).read().decode("utf8"))
         list_spend = r['data']['txs']
         total_amount = 0
         if len(list_spend) == 0:
             raise Exception("No spendable outputs found")
         unspents = sorted(list_spend,
                           key=lambda d: d['value'],
                           reverse=True)
         for u in unspents:
             coin_value = int(float(u['value']) * 100000000)
             script = h2b(u["script_hex"])
             previous_hash = h2b_rev(u["txid"])
             previous_index = u["output_no"]
             spendables.append(
                 Spendable(coin_value, script, previous_hash,
                           previous_index))
             total_amount = total_amount + coin_value
             if total_amount >= amount:
                 break
         return [spendables, total_amount]
Exemplo n.º 4
0
 def spendables_for_address(self, bitcoin_address, amount=None):
     """
     Return a list of Spendable objects for the
     given bitcoin address.
     """
     URL = "%s/addr/%s/utxo" % (self.base_url, bitcoin_address)
     print(URL)
     r = json.loads(urlopen(URL).read().decode("utf8"))
     r = sorted(r, key=lambda d: d['amount'], reverse=True)
     if len(r) == 0:
         raise Exception("No spendable outputs found")
     if amount == None:
         spendables = []
         for u in r:
             coin_value = btc_to_satoshi(str(u.get("amount")))
             script = h2b(u.get("scriptPubKey"))
             previous_hash = h2b_rev(u.get("txid"))
             previous_index = u.get("vout")
             spendables.append(
                 Spendable(coin_value, script, previous_hash,
                           previous_index))
         return spendables
     else:
         total_amount = 0
         spendables = []
         for u in r:
             coin_value = btc_to_satoshi(str(u.get("amount")))
             script = h2b(u.get("scriptPubKey"))
             previous_hash = h2b_rev(u.get("txid"))
             previous_index = u.get("vout")
             spendables.append(
                 Spendable(coin_value, script, previous_hash,
                           previous_index))
             total_amount = total_amount + coin_value
             if total_amount >= amount:
                 break
         return [spendables, total_amount]
Exemplo n.º 5
0
 def spendables_for_address(self, bitcoin_address):
     """
     Return a list of Spendable objects for the
     given bitcoin address.
     """
     URL = "%s%saddr/%s/utxo" % (self.base_url, self.base_path, bitcoin_address)
     r = json.loads(urlopen(URL).read().decode("utf8"))
     spendables = []
     for u in r:
         coin_value = btc_to_satoshi(str(u.get("amount")))
         script = h2b(u.get("scriptPubKey"))
         previous_hash = h2b_rev(u.get("txid"))
         previous_index = u.get("vout")
         spendables.append(Spendable(coin_value, script, previous_hash, previous_index))
     return spendables
Exemplo n.º 6
0
 def get_unspents(self, address):
     """
     Return a list of Spendable objects for the given bitcoin address.
     """
     URL = "%s/addr/%s/utxo" % (self.base_url, address)
     r = requests.get(URL)
     r.raise_for_status()
     spendables = []
     for u in r.json():
         coin_value = btc_to_satoshi(str(u.get("amount")))
         script = h2b(u.get("scriptPubKey"))
         previous_hash = h2b_rev(u.get("txid"))
         previous_index = u.get("vout")
         spendables.append(Spendable(coin_value, script, previous_hash, previous_index))
     return spendables
Exemplo n.º 7
0
def parse_parts(arg, spendables, payables, network):
    parts = arg.split("/")
    if 4 <= len(parts) <= 7:
        # spendable
        try:
            spendables.append(Spendable.from_text(arg))
            return True
        except Exception:
            pass

    if len(parts) == 2 and is_address_valid(parts[0], allowable_netcodes=[network]):
        try:
            payables.append(parts)
            return True
        except ValueError:
            pass
Exemplo n.º 8
0
 def spendables_for_address(self, address):
     """
     Return a list of Spendable objects for the
     given bitcoin address.
     """
     url_append = "unspent/%s" % address
     URL = "%s/address/%s" % (self.url, url_append)
     r = json.loads(urlopen(URL).read().decode("utf8"))
     spendables = []
     for u in r.get("data", {}).get("unspent", []):
         coin_value = btc_to_satoshi(u.get("amount"))
         script = h2b(u.get("script"))
         previous_hash = h2b_rev(u.get("tx"))
         previous_index = u.get("n")
         spendables.append(Spendable(coin_value, script, previous_hash, previous_index))
     return spendables
Exemplo n.º 9
0
def parse_parts(arg, spendables, payables, network):
    parts = arg.split("/")
    if 4 <= len(parts) <= 7:
        # spendable
        try:
            spendables.append(Spendable.from_text(arg))
            return True
        except Exception:
            pass

    if len(parts) == 2 and is_address_valid(parts[0], allowable_netcodes=[network]):
        try:
            payables.append(parts)
            return True
        except ValueError:
            pass
Exemplo n.º 10
0
 def spendables_for_address(self, address):
     """
     Return a list of Spendable objects for the
     given bitcoin address.
     """
     spendables = []
     url_append = "?unspentOnly=true&token=%s&includeScript=true" % self.api_key
     url = self.base_url("addrs/%s%s" % (address, url_append))
     result = json.loads(urlopen(url).read().decode("utf8"))
     for txn in result.get("txrefs", []):
         coin_value = txn.get("value")
         script = h2b(txn.get("script"))
         previous_hash = h2b_rev(txn.get("tx_hash"))
         previous_index = txn.get("tx_output_n")
         spendables.append(Spendable(coin_value, script, previous_hash, previous_index))
     return spendables
Exemplo n.º 11
0
    def spendables_for_address(self, address):
        """
        Return a list of Spendable objects for the
        given bitcoin address.
        """
        spendables = []
        r = json.loads(
            urlopen(self.base_url('get_tx_unspent',
                                  address)).read().decode("utf8"))

        for u in r['data']['txs']:
            coin_value = int(float(u['value']) * 100000000)
            script = h2b(u["script_hex"])
            previous_hash = h2b_rev(u["txid"])
            previous_index = u["output_no"]
            spendables.append(
                Spendable(coin_value, script, previous_hash, previous_index))

        return spendables
Exemplo n.º 12
0
# that's work for insight
# TODO: 设计通用utxo
def get_speendable(address):
    URL = "%s%saddr/%s/utxo" % ('https://test-insight.bitpay.com', '/api/',
                                from_address)
    utxos = json.loads(urlopen(URL).read().decode("utf8"))

    utxo = utxos[0]

    return Spendable(utxo['amount'], h2b(utxo.get("scriptPubKey")),
                     h2b_rev(utxo.get("txid")), utxo.get("vout"))


amount, script_hex = get_spendable(from_address)

spendable = Spendable(amount, script_hex)
##################
# TODO: 设计amount计算
tx = create_signed_tx([spendable],
                      [(to_address, btc_to_satoshi("0.00005")),
                       (btc_withdraw_address, btc_to_satoshi("0.0015"))],
                      fee=btc_to_satoshi("0.00005"),
                      wifs=[master_key.wif()],
                      netcode=args.netcode)

tx_as_hex = tx.as_hex()
print tx_as_hex
# TODO 节点选取
# url = "https://test-insight.bitpay.com/api/tx/send"
# data = urlencode(dict(rawtx=tx_as_hex)).encode("utf8")
Exemplo n.º 13
0
def parse_context(args, parser):
    # 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_tx_for_tx_hash = 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)

    # update p2sh_lookup
    p2sh_lookup = {}
    if args.pay_to_script:
        for p2s in args.pay_to_script:
            try:
                script = h2b(p2s)
                p2sh_lookup[hash160(script)] = script
            except Exception:
                print("warning: error parsing pay-to-script value %s" % p2s)

    if args.pay_to_script_file:
        hex_re = re.compile(r"[0-9a-fA-F]+")
        for f in args.pay_to_script_file:
            count = 0
            for l in f:
                try:
                    m = hex_re.search(l)
                    if m:
                        p2s = m.group(0)
                        script = h2b(p2s)
                        p2sh_lookup[hash160(script)] = script
                        count += 1
                except Exception:
                    print("warning: error parsing pay-to-script file %s" %
                          f.name)
            if count == 0:
                print("warning: no scripts found in %s" % f.name)

    # we create the tx_db lazily
    tx_db = None

    if args.db:
        the_ram_tx_db = dict((tx.hash(), tx) for tx in args.db)
        if tx_db is None:
            tx_db = get_tx_db(args.network)
        tx_db.lookup_methods.append(the_ram_tx_db.get)

    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_tx_for_tx_hash = message_about_tx_for_tx_hash_env(
                    args.network)
                tx_db = get_tx_db(args.network)
            tx = tx_db.get(h2b_rev(arg))
            if not tx:
                for m in [
                        warning_tx_cache, warning_tx_for_tx_hash,
                        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.from_hex(arg)
            txs.append(tx)
            continue
        except Exception:
            pass

        is_valid = is_address_valid(arg, allowable_netcodes=[args.network])
        if is_valid:
            payables.append((arg, 0))
            continue

        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

        if len(parts) == 2 and is_address_valid(
                parts[0], allowable_netcodes=[args.network]):
            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(
            args.network)
        for address in args.fetch_spendables:
            spendables.extend(spendables_for_address(address))

    for tx in txs:
        if tx.missing_unspents() and (args.augment or tx_db):
            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.unspents_from_db(tx_db, ignore_missing=True)

    return (txs, spendables, payables, key_iters, p2sh_lookup, tx_db,
            warning_tx_cache, warning_tx_for_tx_hash, warning_spendables)