Пример #1
0
 def address(self, netcode=None):
     from pycoin.networks import pay_to_script_prefix_for_netcode
     from pycoin.networks.default import get_current_netcode
     if netcode is None:
         netcode = get_current_netcode()
     address_prefix = pay_to_script_prefix_for_netcode(netcode)
     return encoding.hash160_sec_to_bitcoin_address(self.hash160, address_prefix=address_prefix)
Пример #2
0
def address_for_pay_to_script_wit(script, netcode=None):
    if netcode is None:
        netcode = get_current_netcode()
    bech32_hrp = bech32_hrp_for_netcode(netcode)
    address = segwit_addr.encode(bech32_hrp, 0,
                                 iterbytes(hashlib.sha256(script).digest()))
    return address
Пример #3
0
 def __init__(self, base_url="https://insight.bitpay.com", base_path="/api/", netcode=None):
     if netcode is None:
         netcode = get_current_netcode()
     while base_url[-1] == '/':
         base_url = base_url[:-1]
     self.base_url = base_url
     self.base_path = base_path
Пример #4
0
 def address_f(netcode=netcode):
     from pycoin.networks import address_prefix_for_netcode
     from pycoin.networks.default import get_current_netcode
     if netcode is None:
         netcode = get_current_netcode()
     address_prefix = address_prefix_for_netcode(netcode)
     address = encoding.hash160_sec_to_bitcoin_address(self.hash160, address_prefix=address_prefix)
     return address
Пример #5
0
def provider_for_descriptor_and_netcode(descriptor, netcode=None):
    if netcode is None:
        netcode = get_current_netcode()
    for cre, f in DESCRIPTOR_CRE_INIT_TUPLES:
        m = cre.match(descriptor)
        if m:
            return f(m, netcode)
    return None
Пример #6
0
def provider_for_descriptor_and_netcode(descriptor, netcode=None):
    if netcode is None:
        netcode = get_current_netcode()
    for cre, f in DESCRIPTOR_CRE_INIT_TUPLES:
        m = cre.match(descriptor)
        if m:
            return f(m, netcode)
    return None
Пример #7
0
def get_default_providers_for_netcode(netcode=None):
    if netcode is None:
        netcode = get_current_netcode()
    if not hasattr(THREAD_LOCALS, "providers"):
        THREAD_LOCALS.providers = {}
    if netcode not in THREAD_LOCALS.providers:
        THREAD_LOCALS.providers[netcode] = providers_for_netcode_from_env(netcode)
    return THREAD_LOCALS.providers[netcode]
Пример #8
0
def get_default_providers_for_netcode(netcode=None):
    if netcode is None:
        netcode = get_current_netcode()
    if not hasattr(THREAD_LOCALS, "providers"):
        THREAD_LOCALS.providers = {}
    if netcode not in THREAD_LOCALS.providers:
        THREAD_LOCALS.providers[netcode] = providers_for_netcode_from_env(netcode)
    return THREAD_LOCALS.providers[netcode]
Пример #9
0
    def __init__(self, api_key="", netcode=None):
        NETWORK_PATHS = {"BTC": "main", "XTN": "test3"}

        if netcode is None:
            netcode = get_current_netcode()

        self.network_path = NETWORK_PATHS.get(netcode)
        self.api_key = api_key
Пример #10
0
def address_for_pay_to_script(script, netcode=None):
    if netcode is None:
        netcode = get_current_netcode()
    address_prefix = pay_to_script_prefix_for_netcode(netcode)
    if address_prefix:
        return encoding.hash160_sec_to_bitcoin_address(
            encoding.hash160(script), address_prefix=address_prefix)
    return None
Пример #11
0
 def address_f(netcode=netcode):
     from pycoin.networks import address_prefix_for_netcode
     from pycoin.networks.default import get_current_netcode
     if netcode is None:
         netcode = get_current_netcode()
     address_prefix = address_prefix_for_netcode(netcode)
     address = encoding.hash160_sec_to_bitcoin_address(hash160, address_prefix=address_prefix)
     return address
Пример #12
0
def create_parser():
    parser = argparse.ArgumentParser(description="Dump a block in human-readable form.")
    parser.add_argument('-n', "--network", default=get_current_netcode(), type=network_for_netcode,
                        help=('Default network code (environment variable PYCOIN_DEFAULT_NETCODE '
                              'or "BTC"=Bitcoin mainnet if unset'))
    parser.add_argument("block_file", nargs="+", type=argparse.FileType('rb'),
                        help='The file containing the binary block.')
    return parser
Пример #13
0
 def address_f(netcode=netcode):
     from pycoin.networks import address_wit_prefix_for_netcode
     from pycoin.networks.default import get_current_netcode
     if netcode is None:
         netcode = get_current_netcode()
     address_prefix = address_wit_prefix_for_netcode(netcode)
     address = encoding.b2a_hashed_base58(address_prefix + b'\0\0' + self.hash160)
     # address = encoding.hash160_sec_to_bitcoin_address(self.hash160, address_prefix=address_prefix)
     return address
Пример #14
0
 def addresses_f(self, netcode=None):
     from pycoin.networks import address_prefix_for_netcode
     from pycoin.networks.default import get_current_netcode
     if netcode is None:
         netcode = get_current_netcode()
     address_prefix = address_prefix_for_netcode(netcode)
     addresses = [encoding.hash160_sec_to_bitcoin_address(h1, address_prefix=address_prefix)
                  for h1 in self.hash160s()]
     return addresses
        def address_f(netcode=netcode):
            from pycoin.networks import bech32_hrp_for_netcode
            from pycoin.networks.default import get_current_netcode
            if netcode is None:
                netcode = get_current_netcode()

            bech32_hrp = bech32_hrp_for_netcode(netcode)
            address = segwit_addr.encode(bech32_hrp, self.version, self.hash256)
            return address
Пример #16
0
    def __init__(self, secret_exponent=None, public_pair=None, hash160=None,
                 prefer_uncompressed=None, is_compressed=None, is_pay_to_script=False, netcode=None):
        """
        secret_exponent:
            a long representing the secret exponent
        public_pair:
            a tuple of long integers on the ecdsa curve
        hash160:
            a hash160 value corresponding to a bitcoin address

        Include at most one of secret_exponent, public_pair or hash160.

        prefer_uncompressed:
            whether or not to produce text outputs as compressed or uncompressed.

        is_pay_to_script:
            whether or not this key is for a pay-to-script style transaction

        netcode:
            the code for the network (as defined in pycoin.networks)

        Include at most one of secret_exponent, public_pair or hash160.
        prefer_uncompressed, is_compressed (booleans) are optional.
        """

        if is_compressed is None:
            is_compressed = False if hash160 else True
        if netcode is None:
            netcode = get_current_netcode()
        if [secret_exponent, public_pair, hash160].count(None) != 2:
            raise ValueError("exactly one of secret_exponent, public_pair, hash160 must be passed.")
        if prefer_uncompressed is None:
            prefer_uncompressed = not is_compressed
        self._prefer_uncompressed = prefer_uncompressed
        self._secret_exponent = secret_exponent
        self._public_pair = public_pair
        self._hash160_uncompressed = None
        self._hash160_compressed = None
        if hash160:
            if is_compressed:
                self._hash160_compressed = hash160
            else:
                self._hash160_uncompressed = hash160
        self._netcode = netcode

        if self._public_pair is None and self._secret_exponent is not None:
            if self._secret_exponent < 1 \
                    or self._secret_exponent >= secp256k1_generator.order():
                raise InvalidSecretExponentError()
            public_pair = self._secret_exponent * secp256k1_generator
            self._public_pair = public_pair

        if self._public_pair is not None \
                and (None in self._public_pair or
                     not secp256k1_generator.contains_point(*self._public_pair)):
            raise InvalidPublicPairError()
Пример #17
0
 def __init__(self, netcode=None):
     NETWORK_PATHS = {
         "BTC": "BTC",
         "XTN": "BTCTEST",
         "DOGE": "DOGE",
         "XDT": "DOGETEST",
     }
     if netcode is None:
         netcode = get_current_netcode()
     self.network_path = NETWORK_PATHS.get(netcode)
        def address_f(netcode=netcode):
            from pycoin.networks import bech32_hrp_for_netcode
            from pycoin.networks.default import get_current_netcode
            if netcode is None:
                netcode = get_current_netcode()

            bech32_hrp = bech32_hrp_for_netcode(netcode)
            if bech32_hrp:
                return segwit_addr.encode(bech32_hrp, self.version, iterbytes(self.hash160))
            return None
Пример #19
0
 def __init__(self, netcode=None):
     NETWORK_PATHS = {
         "BTC": "BTC",
         "XTN": "BTCTEST",
         "DOGE": "DOGE",
         "XDT": "DOGETEST",
     }
     if netcode is None:
         netcode = get_current_netcode()
     self.network_path = NETWORK_PATHS.get(netcode)
Пример #20
0
    def __init__(self, secret_exponent=None, public_pair=None, hash160=None,
                 prefer_uncompressed=None, is_compressed=True, is_pay_to_script=False, netcode=None):
        """
        secret_exponent:
            a long representing the secret exponent
        public_pair:
            a tuple of long integers on the ecdsa curve
        hash160:
            a hash160 value corresponding to a bitcoin address

        Include at most one of secret_exponent, public_pair or hash160.

        prefer_uncompressed:
            whether or not to produce text outputs as compressed or uncompressed.

        is_pay_to_script:
            whether or not this key is for a pay-to-script style transaction

        netcode:
            the code for the network (as defined in pycoin.networks)

        Include at most one of secret_exponent, public_pair or hash160.
        prefer_uncompressed, is_compressed (booleans) are optional.
        """

        if netcode is None:
            netcode = get_current_netcode()
        if [secret_exponent, public_pair, hash160].count(None) != 2:
            raise ValueError("exactly one of secret_exponent, public_pair, hash160 must be passed.")
        if prefer_uncompressed is None:
            prefer_uncompressed = not is_compressed
        self._prefer_uncompressed = prefer_uncompressed
        self._secret_exponent = secret_exponent
        self._public_pair = public_pair
        self._hash160_uncompressed = None
        self._hash160_compressed = None
        if hash160:
            if is_compressed:
                self._hash160_compressed = hash160
            else:
                self._hash160_uncompressed = hash160
        self._netcode = netcode

        if self._public_pair is None and self._secret_exponent is not None:
            if self._secret_exponent < 1 \
                    or self._secret_exponent >= ecdsa.generator_secp256k1.order():
                raise InvalidSecretExponentError()
            public_pair = ecdsa.public_pair_for_secret_exponent(
                ecdsa.generator_secp256k1, self._secret_exponent)
            self._public_pair = public_pair

        if self._public_pair is not None \
                and (None in self._public_pair or
                     not ecdsa.is_public_pair_valid(ecdsa.generator_secp256k1, self._public_pair)):
            raise InvalidPublicPairError()
Пример #21
0
def ku(args, parser):
    fallback_network = network_for_netcode(args.network
                                           or get_current_netcode())
    parse_networks = [fallback_network] + [
        network_for_netcode(netcode) for netcode in network_codes()
    ]
    if args.network:
        parse_networks = [network_for_netcode(args.network)]

    override_network = None
    if args.override_network:
        # Override the network value, so we can take the same xpubkey and view what
        # the values would be on each other network type.
        override_network = network_for_netcode(args.override_network)

    def parse_stdin():
        return [
            item for item in sys.stdin.readline().strip().split(' ')
            if len(item) > 0
        ]

    output_key_set = set(args.brief or [])
    if args.wallet:
        output_key_set.add("wallet_key")
    elif args.wif:
        output_key_set.add("wif_uncompressed" if args.uncompressed else "wif")
    elif args.address:
        output_key_set.add("address" +
                           ("_uncompressed" if args.uncompressed else ""))

    items = args.item if len(args.item) > 0 else parse_stdin()

    for item in items:
        key = parse_key(item, parse_networks)
        if key is None:
            print("can't parse %s" % item, file=sys.stderr)
            continue

        if override_network:
            key = key.override_network(override_network)

        display_network = override_network or key._network or fallback_network

        if hasattr(key, "subkeys"):
            key_iter = key.subkeys(args.subkey)
        else:
            key_iter = [key]
        for key in key_iter:
            if args.public:
                key = key.public_copy()

            output_dict, output_order = create_output(item, key,
                                                      output_key_set)

            generate_output(args, output_dict, output_order)
Пример #22
0
 def addresses_f(self, netcode=None):
     from pycoin.networks import address_prefix_for_netcode
     from pycoin.networks.default import get_current_netcode
     if netcode is None:
         netcode = get_current_netcode()
     address_prefix = address_prefix_for_netcode(netcode)
     addresses = [
         encoding.hash160_sec_to_bitcoin_address(
             h1, address_prefix=address_prefix) for h1 in self.hash160s()
     ]
     return addresses
Пример #23
0
    def __init__(self, api_key="", netcode=None):
        NETWORK_PATHS = {
            "BTC": "main",
            "XTN": "test3"
        }

        if netcode is None:
            netcode = get_current_netcode()

        self.network_path = NETWORK_PATHS.get(netcode)
        self.api_key = api_key
Пример #24
0
def fetch_unspent(args):
    netcode = get_current_netcode()

    m = message_about_spendables_for_address_env(netcode)
    if m:
        print("warning: %s" % m)

    for address in args.bitcoin_address:
        spendables = spendables_for_address(address, netcode, format="text")
        for spendable in spendables:
            print(spendable)
Пример #25
0
 def __init__(self):
     self.app = QtWidgets.QApplication(sys.argv)
     self.first = QtWidgets.QDialog()
     self.second = QtWidgets.QDialog()
     self.ui = Ui_first()
     self.ui.setupUi(self.first)
     self.ui.gen_key_button.clicked.connect(self.gen_seed)
     self.ui.secret_exponent.textChanged.connect(self.detect_text)
     self.ui.next_button.clicked.connect(self.next)
     self.first.show()
     self.netcode = get_current_netcode()
     self.privkeychain = KeyChain()
     self.pubkeychain = KeyChain()
Пример #26
0
def dump_block(block, netcode=None):
    if netcode is None:
        netcode = get_current_netcode()
    blob = stream_to_bytes(block.stream)
    print("%d bytes   block hash %s" % (len(blob), block.id()))
    print("version %d" % block.version)
    print("prior block hash %s" % b2h_rev(block.previous_block_hash))
    print("merkle root %s" % b2h(block.merkle_root))
    print("timestamp %s" % datetime.datetime.utcfromtimestamp(block.timestamp).isoformat())
    print("difficulty %d" % block.difficulty)
    print("nonce %s" % block.nonce)
    print("%d transaction%s" % (len(block.txs), "s" if len(block.txs) != 1 else ""))
    for idx, tx in enumerate(block.txs):
        print("Tx #%d:" % idx)
        dump_tx(tx, netcode=netcode, verbose_signature=False, disassembly_level=0, do_trace=False, use_pdb=False)
Пример #27
0
def dump_block(block, netcode=None):
    if netcode is None:
        netcode = get_current_netcode()
    blob = stream_to_bytes(block.stream)
    print("%d bytes   block hash %s" % (len(blob), block.id()))
    print("version %d" % block.version)
    print("prior block hash %s" % b2h_rev(block.previous_block_hash))
    print("merkle root %s" % b2h(block.merkle_root))
    print("timestamp %s" % datetime.datetime.utcfromtimestamp(block.timestamp).isoformat())
    print("difficulty %d" % block.difficulty)
    print("nonce %s" % block.nonce)
    print("%d transaction%s" % (len(block.txs), "s" if len(block.txs) != 1 else ""))
    for idx, tx in enumerate(block.txs):
        print("Tx #%d:" % idx)
        dump_tx(tx, netcode=network)
Пример #28
0
def create_parser():
    codes = network_codes()
    EPILOG = ('Known networks codes:\n  ' +
              ', '.join(['%s (%s)' % (i, full_network_name_for_netcode(i)) for i in codes]))

    parser = argparse.ArgumentParser(
        description="Compile or disassemble scripts.",
        epilog=EPILOG)

    parser.add_argument('-n', "--network", default=get_current_netcode(), choices=codes,
                        help=('Network code (environment variable PYCOIN_DEFAULT_NETCODE '
                              'or "BTC"=Bitcoin mainnet if unset'))

    parser.add_argument("argument", nargs="+", help='script to compile. To dump hex, prefix with 0x')

    return parser
Пример #29
0
def main():
    parser = argparse.ArgumentParser(
        description=
        "Create a hex dump of unspent TxOut items for Bitcoin addresses.")
    parser.add_argument("bitcoin_address", help='a bitcoin address', nargs="+")

    args = parser.parse_args()
    netcode = get_current_netcode()

    m = message_about_spendables_for_address_env(netcode)
    if m:
        print("warning: %s" % m)

    for address in args.bitcoin_address:
        spendables = spendables_for_address(address, netcode, format="text")
        for spendable in spendables:
            print(spendable)
Пример #30
0
def ku(args, parser):
    fallback_network = network_for_netcode(args.network or get_current_netcode())
    parse_networks = [fallback_network] + [network_for_netcode(netcode) for netcode in network_codes()]
    if args.network:
        parse_networks = [network_for_netcode(args.network)]

    override_network = None
    if args.override_network:
        # Override the network value, so we can take the same xpubkey and view what
        # the values would be on each other network type.
        override_network = network_for_netcode(args.override_network)

    def parse_stdin():
        return [item for item in sys.stdin.readline().strip().split(' ') if len(item) > 0]

    output_key_set = set(args.brief or [])
    if args.wallet:
        output_key_set.add("wallet_key")
    elif args.wif:
        output_key_set.add("wif_uncompressed" if args.uncompressed else "wif")
    elif args.address:
        output_key_set.add("address" + ("_uncompressed" if args.uncompressed else ""))

    items = args.item if len(args.item) > 0 else parse_stdin()

    for item in items:
        key_network, key = parse_key(item, parse_networks)
        if key is None:
            print("can't parse %s" % item, file=sys.stderr)
            continue

        display_network = override_network or key_network or fallback_network

        if hasattr(key, "subkeys"):
            key_iter = key.subkeys(args.subkey)
        else:
            key_iter = [key]
        for key in key_iter:
            if args.public:
                key = key.public_copy()

            output_dict, output_order = create_output(item, key, display_network, output_key_set)

            generate_output(args, output_dict, output_order)
Пример #31
0
def ku(args, parser):
    generator = secp256k1_generator

    fallback_network = network_for_netcode(args.network
                                           or get_current_netcode())
    parse_networks = [
        network_for_netcode(netcode) for netcode in network_codes()
    ]
    if args.network:
        parse_networks = [network_for_netcode(args.network)]

    override_network = None
    if args.override_network:
        # Override the network value, so we can take the same xpubkey and view what
        # the values would be on each other network type.
        override_network = network_for_netcode(args.override_network)

    def parse_stdin():
        return [
            item for item in sys.stdin.readline().strip().split(' ')
            if len(item) > 0
        ]

    items = args.item if len(args.item) > 0 else parse_stdin()

    for item in items:
        key_network, key = parse_key(item, parse_networks, generator)
        if key is None:
            print("can't parse %s" % item, file=sys.stderr)
            continue

        display_network = override_network or key_network or fallback_network

        for key in key.subkeys(args.subkey or ""):
            if args.public:
                key = key.public_copy()

            output_dict, output_order = create_output(item, key,
                                                      display_network)

            generate_output(args, output_dict, output_order)
Пример #32
0
def create_parser():
    codes = network_codes()
    parser = argparse.ArgumentParser(
        description='Crypto coin utility ku ("key utility") to show'
        ' information about Bitcoin or other cryptocoin data structures.',
        epilog=('Known networks codes:\n  ' +
                ', '.join(['%s (%s)' % (i, full_network_name_for_netcode(i)) for i in codes]))
    )
    parser.add_argument('-w', "--wallet", help='show just Bitcoin wallet key', action='store_true')
    parser.add_argument('-W', "--wif", help='show just Bitcoin WIF', action='store_true')
    parser.add_argument('-a', "--address", help='show just Bitcoin address', action='store_true')
    parser.add_argument(
        '-u', "--uncompressed", help='show output in uncompressed form',
        action='store_true')
    parser.add_argument(
        '-P', "--public", help='only show public version of wallet keys',
        action='store_true')

    parser.add_argument('-j', "--json", help='output as JSON', action='store_true')

    parser.add_argument('-s', "--subkey", help='subkey path (example: 0H/2/15-20)')
    parser.add_argument('-n', "--network", help='specify network',
                        default=get_current_netcode(), choices=codes)
    parser.add_argument("--override-network", help='override detected network type',
                        default=None, choices=codes)

    parser.add_argument(
        'item', nargs="+", help='a BIP0032 wallet key string;'
        ' a WIF;'
        ' a bitcoin address;'
        ' an SEC (ie. a 66 hex chars starting with 02, 03 or a 130 hex chars starting with 04);'
        ' the literal string "create" to create a new wallet key using strong entropy sources;'
        ' P:wallet passphrase (NOT RECOMMENDED);'
        ' H:wallet passphrase in hex (NOT RECOMMENDED);'
        ' E:electrum value (either a master public, master private, or initial data);'
        ' secret_exponent (in decimal or hex);'
        ' x,y where x,y form a public pair (y is a number or one of the strings "even" or "odd");'
        ' hash160 (as 40 hex characters)')
    return parser
Пример #33
0
def address_for_pay_to_script(script, netcode=None):
    if netcode is None:
        netcode = get_current_netcode()
    address_prefix = pay_to_script_prefix_for_netcode(netcode)
    return encoding.hash160_sec_to_bitcoin_address(encoding.hash160(script), address_prefix=address_prefix)
Пример #34
0
 def __init__(self, base_url="https://insight.bitpay.com", netcode=None):
     if netcode is None:
         netcode = get_current_netcode()
     while base_url[-1] == '/':
         base_url = base_url[:-1]
     self.base_url = base_url
Пример #35
0
 def address(self, netcode=None):
     from pycoin.networks.default import get_current_netcode
     if netcode is None:
         netcode = get_current_netcode()
     return self.info()["address_f"](netcode)
Пример #36
0
def address_for_pay_to_script_wit(script, netcode=None):
    if netcode is None:
        netcode = get_current_netcode()
    address_prefix = pay_to_script_wit_prefix_for_netcode(netcode)
    return encoding.b2a_hashed_base58(address_prefix + b'\0\0' +
                                      hashlib.sha256(script).digest())
Пример #37
0
 def address(self, netcode=None):
     from pycoin.networks.default import get_current_netcode
     if netcode is None:
         netcode = get_current_netcode()
     return self.info().get("address_f", lambda n: "(unknown)")(netcode)
Пример #38
0
 def __init__(self, base_url, netcode=None):
     if netcode is None:
         netcode = get_current_netcode()
     while base_url[-1] == '/':
         base_url = base_url[:-1]
     self.base_url = base_url
Пример #39
0
 def __init__(self, base_url, netcode=None):
     if netcode is None:
         netcode = get_current_netcode()
     while base_url[-1] == '/':
         base_url = base_url[:-1]
     self.base_url = base_url
Пример #40
0
 def address(self, netcode=None):
     from pycoin.networks.default import get_current_netcode
     if netcode is None:
         netcode = get_current_netcode()
     return self.info(netcode=netcode)["address_f"](netcode)
Пример #41
0
def address_for_pay_to_script_wit(script, netcode=None):
    if netcode is None:
        netcode = get_current_netcode()
    address_prefix = pay_to_script_wit_prefix_for_netcode(netcode)
    return encoding.b2a_hashed_base58(address_prefix + b'\0\0' + hashlib.sha256(script).digest())
Пример #42
0
def create_parser():
    codes = network_codes()
    parser = argparse.ArgumentParser(
        description='Crypto coin utility ku ("key utility") to show'
        ' information about Bitcoin or other cryptocoin data structures.',
        epilog=('Known networks codes:\n  ' + ', '.join(
            ['%s (%s)' % (i, full_network_name_for_netcode(i))
             for i in codes])))
    parser.add_argument('-w',
                        "--wallet",
                        help='show just Bitcoin wallet key',
                        action='store_true')
    parser.add_argument('-W',
                        "--wif",
                        help='show just Bitcoin WIF',
                        action='store_true')
    parser.add_argument('-a',
                        "--address",
                        help='show just Bitcoin address',
                        action='store_true')
    parser.add_argument('-u',
                        "--uncompressed",
                        help='show output in uncompressed form',
                        action='store_true')
    parser.add_argument('-P',
                        "--public",
                        help='only show public version of wallet keys',
                        action='store_true')

    parser.add_argument('-j',
                        "--json",
                        help='output as JSON',
                        action='store_true')

    parser.add_argument('-s',
                        "--subkey",
                        help='subkey path (example: 0H/2/15-20)')
    parser.add_argument('-n',
                        "--network",
                        help='specify network',
                        default=get_current_netcode(),
                        choices=codes)
    parser.add_argument("--override-network",
                        help='override detected network type',
                        default=None,
                        choices=codes)

    parser.add_argument(
        'item',
        nargs="+",
        help='a BIP0032 wallet key string;'
        ' a WIF;'
        ' a bitcoin address;'
        ' an SEC (ie. a 66 hex chars starting with 02, 03 or a 130 hex chars starting with 04);'
        ' the literal string "create" to create a new wallet key using strong entropy sources;'
        ' P:wallet passphrase (NOT RECOMMENDED);'
        ' H:wallet passphrase in hex (NOT RECOMMENDED);'
        ' E:electrum value (either a master public, master private, or initial data);'
        ' secret_exponent (in decimal or hex);'
        ' x,y where x,y form a public pair (y is a number or one of the strings "even" or "odd");'
        ' hash160 (as 40 hex characters)')
    return parser
Пример #43
0
def create_parser():
    codes = network_codes()
    EPILOG = ('Files are binary by default unless they end with the suffix ".hex". ' +
              'Known networks codes:\n  ' +
              ', '.join(['%s (%s)' % (i, full_network_name_for_netcode(i)) for i in codes]))

    parser = argparse.ArgumentParser(
        description="Manipulate bitcoin (or alt coin) transactions.",
        epilog=EPILOG)

    parser.add_argument('-t', "--transaction-version", type=range_int(0, 255, "version"),
                        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=get_current_netcode(), choices=codes,
                        help='Define network code (BTC=Bitcoin mainnet, XTN=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('-s', "--verbose-signature", action='store_true',
                        help='Display technical signature details.')

    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. With no outputs, incoming spendables will be printed.')

    parser.add_argument('-f', "--private-key-file", metavar="path-to-private-keys", action="append", default=[],
                        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("--db", type=Tx.from_hex, help='force the transaction expressed by the given hex '
                        'into a RAM-based transaction cache. Mostly for testing.', action="append"),

    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('-d', "--disassemble", action='store_true',
                        help='Disassemble scripts.')

    parser.add_argument("--pdb", action="store_true", help='Enter PDB debugger on each script instruction.')

    parser.add_argument("--trace", action='store_true', help='Trace scripts.')

    parser.add_argument('-p', "--pay-to-script", metavar="pay-to-script", action="append",
                        help='a hex version of a script required for a pay-to-script'
                        'input (a bitcoin address that starts with 3)')

    parser.add_argument('-P', "--pay-to-script-file", metavar="pay-to-script-file", nargs=1,
                        type=argparse.FileType('r'), help='a file containing hex scripts '
                        '(one per line) corresponding to pay-to-script inputs')

    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".')

    return parser
Пример #44
0
def block(args, parser):
    network = network_for_netcode(get_current_netcode())
    for f in args.block_file:
        block = Block.parse(f)
        dump_block(block, network)
        print('')
Пример #45
0
 def address(self, netcode=None):
     from pycoin.networks.default import get_current_netcode
     if netcode is None:
         netcode = get_current_netcode()
     return self.info().get("address_f", lambda n: "(unknown)")(netcode)
Пример #46
0
def create_parser():
    codes = network_codes()
    EPILOG = (
        'Files are binary by default unless they end with the suffix ".hex". '
        + 'Known networks codes:\n  ' + ', '.join([
            '%s (%s)' % (i, network_for_netcode(i).full_name()) for i in codes
        ]))

    parser = argparse.ArgumentParser(
        description="Manipulate bitcoin (or alt coin) transactions.",
        epilog=EPILOG)

    parser.add_argument(
        '-t',
        "--transaction-version",
        type=range_int(0, 255, "version"),
        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=get_current_netcode(),
        choices=codes,
        help=(
            'Default network code (environment variable PYCOIN_DEFAULT_NETCODE '
            'or "BTC"=Bitcoin mainnet if unset'))

    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('-s',
                        "--verbose-signature",
                        action='store_true',
                        help='Display technical signature details.')

    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. With no outputs, incoming spendables will be printed.'
    )

    parser.add_argument("-I",
                        "--dump-inputs",
                        action='store_true',
                        help='Dump inputs to this transaction.')

    parser.add_argument(
        "-k",
        "--keychain",
        default=":memory:",
        help=
        "path to keychain file for hierarchical key hints (SQLite3 file created with keychain tool)"
    )

    parser.add_argument(
        "-K",
        "--key-paths",
        default="",
        help=
        "Key path hints to search hiearachical private keys (example: 0/0H/0-20)"
    )

    parser.add_argument(
        '-f',
        "--private-key-file",
        metavar="path-to-private-keys",
        action="append",
        default=[],
        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(
        "--replace-input-script",
        metavar="tx_in_script_slash_hex",
        action="append",
        default=[],
        type=parse_script_index_hex,
        help='replace an input script: arg looks like "1/796a"')

    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(
        "--db",
        help='force the transaction expressed by the given hex '
        'into a RAM-based transaction cache. Mostly for testing.',
        action="append"),

    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('-d',
                        "--disassemble",
                        action='store_true',
                        help='Disassemble scripts.')

    parser.add_argument("--pdb",
                        action="store_true",
                        help='Enter PDB debugger on each script instruction.')

    parser.add_argument("--trace", action='store_true', help='Trace scripts.')

    parser.add_argument(
        '-p',
        "--pay-to-script",
        metavar="pay-to-script",
        action="append",
        help='a hex version of a script required for a pay-to-script'
        'input (a bitcoin address that starts with 3)')

    parser.add_argument(
        "--signature",
        metavar="known-good-signature",
        action="append",
        help='a hex version of a signature that will be used if useful')

    parser.add_argument(
        "--sec",
        metavar="known-sec",
        action="append",
        help='a hex version of an SEC that will be used if useful')

    parser.add_argument('-P',
                        "--pay-to-script-file",
                        metavar="pay-to-script-file",
                        nargs=1,
                        type=argparse.FileType('r'),
                        help='a file containing hex scripts '
                        '(one per line) corresponding to pay-to-script inputs')

    parser.add_argument("--dump-signatures",
                        action="store_true",
                        help="print signatures (for use with --signature)")

    parser.add_argument("--dump-secs",
                        action="store_true",
                        help="print secs (for use with --sec)")

    parser.add_argument(
        "--coinbase",
        type=str,
        help="add an input as a coinbase from the given address")

    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 or script to be added to the TxOut list and placed in the '
        '"split pool".')

    return parser