Пример #1
0
def create_output(item, key, subkey_path=None):
    output_dict = {}
    output_order = []

    def add_output(json_key, value=None, human_readable_key=None):
        if human_readable_key is None:
            human_readable_key = json_key.replace("_", " ")
        if value:
            output_dict[json_key.strip().lower()] = value
        output_order.append((json_key.lower(), human_readable_key))

    full_network_name = full_network_name_for_netcode(key._netcode)
    add_output("input", item)
    add_output("network", full_network_name)
    add_output("netcode", key._netcode)

    create_wallet_key_output(key, subkey_path, add_output)

    secret_exponent = key.secret_exponent()
    if secret_exponent:
        add_output("secret_exponent", '%d' % secret_exponent)
        add_output("secret_exponent_hex", '%x' % secret_exponent, " hex")
        add_output("wif", key.wif(use_uncompressed=False))
        add_output("wif_uncompressed", key.wif(use_uncompressed=True),
                   " uncompressed")

    create_public_pair_output(key, add_output)

    create_hash160_output(key, add_output, output_dict)

    return output_dict, output_order
Пример #2
0
def create_output(item, key, subkey_path=None):
    output_dict = {}
    output_order = []

    def add_output(json_key, value=None, human_readable_key=None):
        if human_readable_key is None:
            human_readable_key = json_key.replace("_", " ")
        if value:
            output_dict[json_key.strip().lower()] = value
        output_order.append((json_key.lower(), human_readable_key))

    full_network_name = full_network_name_for_netcode(key._netcode)
    add_output("input", item)
    add_output("network", full_network_name)
    add_output("netcode", key._netcode)

    create_wallet_key_output(key, subkey_path, add_output)

    secret_exponent = key.secret_exponent()
    if secret_exponent:
        add_output("secret_exponent", '%d' % secret_exponent)
        add_output("secret_exponent_hex", '%x' % secret_exponent, " hex")
        add_output("wif", key.wif(use_uncompressed=False))
        add_output("wif_uncompressed", key.wif(use_uncompressed=True), " uncompressed")

    create_public_pair_output(key, add_output)

    create_hash160_output(key, add_output, output_dict)

    return output_dict, output_order
Пример #3
0
def create_parser():
    codes = network_codes()
    parser = argparse.ArgumentParser(
        description='Create or verify a text signature using bitcoin standards',
        epilog=('Known networks codes:\n  ' + ', '.join(
            ['%s (%s)' % (i, full_network_name_for_netcode(i))
             for i in codes])))
    parser.add_argument(
        '-i',
        "--input",
        help=
        'file containing the message to be signed or verified, instead of stdin',
        type=argparse.FileType('r'),
        default=sys.stdin)
    parser.add_argument('-n',
                        "--network",
                        help='specify network (default: BTC = Bitcoin)',
                        default='BTC',
                        choices=codes)

    subparsers = parser.add_subparsers(dest="command")

    sign = subparsers.add_parser('sign',
                                 help='sign a message with a private key')
    sign.add_argument('WIF', help='the WIF to sign the message with')

    verify = subparsers.add_parser('verify')
    verify.add_argument('signature', help='the signature to verify')
    verify.add_argument('address', nargs="?", help='the signature to verify')

    return parser
def create_parser():
    codes = network_codes()
    parser = argparse.ArgumentParser(
        description='Create or verify a text signature using bitcoin standards',
        epilog=('Known networks codes:\n  ' + ', '.join(
            ['%s (%s)' % (i, full_network_name_for_netcode(i))
             for i in codes])))
    parser.add_argument('-n',
                        "--network",
                        help='specify network (default: BTC = Bitcoin)',
                        default='BTC',
                        choices=codes)

    subparsers = parser.add_subparsers(dest="command")

    sign = subparsers.add_parser('sign',
                                 help='sign a message with a private key')
    sign.add_argument('WIF', help='the WIF to sign the message with')
    add_read_msg_arguments(sign, "signed")

    verify = subparsers.add_parser('verify')
    verify.add_argument('signature', help='the signature to verify')
    verify.add_argument('address', nargs="?", help='the signature to verify')
    add_read_msg_arguments(verify, "verified")

    return parser
Пример #5
0
def create_output(item, key, subkey_path=None):
    output_dict = {}
    output_order = []

    def add_output(json_key, value=None, human_readable_key=None):
        if human_readable_key is None:
            human_readable_key = json_key.replace("_", " ")
        if value:
            output_dict[json_key.strip().lower()] = value
        output_order.append((json_key.lower(), human_readable_key))

    network_name = network_name_for_netcode(key._netcode)
    full_network_name = full_network_name_for_netcode(key._netcode)
    add_output("input", item)
    add_output("network", full_network_name)
    add_output("netcode", key._netcode)

    create_wallet_key_output(key, subkey_path, add_output)

    secret_exponent = key.secret_exponent()
    if secret_exponent:
        add_output("secret_exponent", '%d' % secret_exponent)
        add_output("secret_exponent_hex", '%x' % secret_exponent, " hex")
        add_output("wif", key.wif(use_uncompressed=False))
        add_output("wif_uncompressed", key.wif(use_uncompressed=True),
                   " uncompressed")

    create_public_pair_output(key, add_output)

    hash160_c = key.hash160(use_uncompressed=False)
    if hash160_c:
        add_output("hash160", b2h(hash160_c))
    hash160_u = key.hash160(use_uncompressed=True)
    if hash160_u:
        add_output("hash160_uncompressed", b2h(hash160_u), " uncompressed")

    if hash160_c:
        address = key.address(use_uncompressed=False)
        add_output("address", address, "%s address" % network_name)
        output_dict["%s_address" % key._netcode] = address

    if hash160_u:
        address = key.address(use_uncompressed=True)
        add_output("address_uncompressed", address,
                   "%s address uncompressed" % network_name)
        output_dict["%s_address_uncompressed" % key._netcode] = address

    if hash160_c and address_wit_prefix_for_netcode(key._netcode):
        address = ScriptPayToAddressWit(b'\0', hash160_c).info()["address_f"](
            key._netcode)
        add_output("address segwit", address,
                   "%s segwit address" % network_name)
        output_dict["%s_address_segwit" % key._netcode] = address

    return output_dict, output_order
Пример #6
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
Пример #7
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: BTC = Bitcoin)',
                        default='BTC', 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
Пример #8
0
def create_parser():
    codes = network_codes()
    parser = argparse.ArgumentParser(
        description='Create or verify a text signature using bitcoin standards',
        epilog=('Known networks codes:\n  ' +
                ', '.join(['%s (%s)' % (i, full_network_name_for_netcode(i)) for i in codes]))
    )
    parser.add_argument('-n', "--network", help='specify network (default: BTC = Bitcoin)',
                        default='BTC', choices=codes)

    subparsers = parser.add_subparsers(dest="command")

    sign = subparsers.add_parser('sign', help='sign a message with a private key')
    sign.add_argument('WIF', help='the WIF to sign the message with')
    add_read_msg_arguments(sign, "signed")

    verify = subparsers.add_parser('verify')
    verify.add_argument('signature', help='the signature to verify')
    verify.add_argument('address', nargs="?", help='the signature to verify')
    add_read_msg_arguments(verify, "verified")

    return parser
Пример #9
0
def main():
    networks = "MTLD"
    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 NETWORK_NAMES])
    )
    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: BTC = Bitcoin)',
                                default='BTC', choices=NETWORK_NAMES)
    parser.add_argument("--override-network", help='override detected network type',
                                default=None, choices=NETWORK_NAMES)

    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);'
        ' 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)')

    args = parser.parse_args()

    if args.override_network:
        # force network arg to match override, but also will override decoded data below.
        args.network = args.override_network

    def _create(_):
        max_retries = 64
        for _ in range(max_retries):
            try:
                return BIP32Node.from_master_secret(get_entropy(), netcode=args.network)
            except ValueError as e:
                continue
        # Probably a bug if we get here
        raise e

    PREFIX_TRANSFORMS = (
        ("P:", lambda s:
            BIP32Node.from_master_secret(s.encode("utf8"), netcode=args.network)),
        ("H:", lambda s:
            BIP32Node.from_master_secret(h2b(s), netcode=args.network)),
        ("create", _create),
    )

    for item in args.item:
        key = None
        for k, f in PREFIX_TRANSFORMS:
            if item.startswith(k):
                try:
                    key = f(item[len(k):])
                    break
                except Exception:
                    pass
        else:
            try:
                key = Key.from_text(item)
            except encoding.EncodingError:
                pass
        if key is None:
            secret_exponent = parse_as_secret_exponent(item)
            if secret_exponent:
                key = Key(secret_exponent=secret_exponent, netcode=args.network)

        if SEC_RE.match(item):
            key = Key.from_sec(h2b(item))

        if key is None:
            public_pair = parse_as_public_pair(item)
            if public_pair:
                key = Key(public_pair=public_pair, netcode=args.network)

        if HASH160_RE.match(item):
            key = Key(hash160=h2b(item), netcode=args.network)

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

        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.
            # XXX public interface for this is needed...
            key._netcode = args.override_network

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

            output_dict, output_order = create_output(item, key)

            if args.json:
                print(json.dumps(output_dict, indent=3, sort_keys=True))
            elif args.wallet:
                print(output_dict["wallet_key"])
            elif args.wif:
                print(output_dict["wif_uncompressed" if args.uncompressed else "wif"])
            elif args.address:
                print(output_dict["address" + ("_uncompressed" if args.uncompressed else "")])
            else:
                dump_output(output_dict, output_order)
Пример #10
0
def main():
    parser = argparse.ArgumentParser(description="Generate a private wallet key. WARNING: obsolete. Use ku instead.")

    parser.add_argument('-a', "--address", help='show as Bitcoin address', action='store_true')
    parser.add_argument('-i', "--info", help='show metadata', action='store_true')
    parser.add_argument('-j', "--json", help='output metadata as JSON', action='store_true')
    parser.add_argument('-w', "--wif", help='show as Bitcoin WIF', action='store_true')
    parser.add_argument('-f', "--wallet-key-file", help='initial wallet key', type=argparse.FileType('r'))
    parser.add_argument('-k', "--wallet-key", help='initial wallet key')
    parser.add_argument('-g', "--gpg", help='use gpg --gen-random to get additional entropy', action='store_true')
    parser.add_argument('-u', "--dev-random", help='use /dev/random to get additional entropy', action='store_true')
    parser.add_argument('-n', "--uncompressed", help='show in uncompressed form', action='store_true')
    parser.add_argument('-p', help='generate wallet key from passphrase. NOT RECOMMENDED', metavar='passphrase')
    parser.add_argument('-s', "--subkey", help='subkey path (example: 0p/2/1)')
    parser.add_argument('-t', help='generate test key', action="store_true")
    parser.add_argument('inputfile', help='source of entropy. stdin by default', type=argparse.FileType(mode='r+b'), nargs='?')
    args = parser.parse_args()

    # args.inputfile doesn't like binary when "-" is passed in. Deal with this.
    if args.inputfile == sys.stdin and hasattr(sys.stdin, "buffer"):
        args.inputfile = sys.stdin.buffer

    network = 'XTN' if args.t else 'BTC'

    entropy = bytearray()
    if args.gpg:
        entropy.extend(gpg_entropy())
    if args.dev_random:
        entropy.extend(dev_random_entropy())
    if args.inputfile:
        entropy.extend(args.inputfile.read())
    if args.p:
        entropy.extend(args.p.encode("utf8"))
    if len(entropy) == 0 and not args.wallet_key and not args.wallet_key_file:
        parser.error("you must specify at least one source of entropy")
    if args.wallet_key and len(entropy) > 0:
        parser.error("don't specify both entropy and a wallet key")
    if args.wallet_key_file:
        wallet = BIP32Node.from_wallet_key(args.wallet_key_file.readline()[:-1])
    elif args.wallet_key:
        wallet = BIP32Node.from_wallet_key(args.wallet_key)
    else:
        wallet = BIP32Node.from_master_secret(bytes(entropy), netcode=network)
    try:
        if args.subkey:
            wallet = wallet.subkey_for_path(args.subkey)
        if wallet.child_index() >= 0x80000000:
            wc = wallet.child_index() - 0x80000000
            child_index = "%dp (%d)" % (wc, wallet.child_index())
        else:
            child_index = "%d" % wallet.child_index()
        if args.json:
            d = dict(
                wallet_key=wallet.wallet_key(as_private=wallet.is_private()),
                public_pair_x=wallet.public_pair[0],
                public_pair_y=wallet.public_pair[1],
                tree_depth=wallet.depth,
                fingerprint=b2h(wallet.fingerprint()),
                parent_fingerprint=b2h(wallet.parent_fingerprint),
                child_index=child_index,
                chain_code=b2h(wallet.chain_code),
                bitcoin_addr=wallet.bitcoin_address(),
                bitcoin_addr_uncompressed=wallet.bitcoin_address(compressed=False),
                network="test" if wallet.is_test else "main",
            )
            if wallet.is_private():
                d.update(dict(
                    key="private",
                    secret_exponent=wallet.secret_exponent,
                    WIF=wallet.wif(),
                    WIF_uncompressed=wallet.wif(compressed=False)
                ))
            else:
                d.update(dict(key="public"))
            print(json.dumps(d, indent=3))
        elif args.info:
            print(wallet.wallet_key(as_private=wallet.is_private()))
            print(full_network_name_for_netcode(wallet.netcode()))
            if wallet.is_private():
                print("private key")
                print("secret exponent: %d" % wallet.secret_exponent())
            else:
                print("public key only")
            print("public pair x:   %d\npublic pair y:   %d" % wallet.public_pair())
            print("tree depth:      %d" % wallet.tree_depth())
            print("fingerprint:     %s" % b2h(wallet.fingerprint()))
            print("parent f'print:  %s" % b2h(wallet.parent_fingerprint()))
            print("child index:     %s" % child_index)
            print("chain code:      %s" % b2h(wallet.chain_code()))
            if wallet.is_private():
                print("WIF:             %s" % wallet.wif())
                print("  uncompressed:  %s" % wallet.wif(use_uncompressed=True))
            print("Bitcoin address: %s" % wallet.bitcoin_address())
            print("  uncompressed:  %s" % wallet.bitcoin_address(use_uncompressed=True))
        elif args.address:
            print(wallet.bitcoin_address(use_uncompressed=args.uncompressed))
        elif args.wif:
            print(wallet.wif(compressed=not args.uncompressed))
        else:
            print(wallet.wallet_key(as_private=wallet.is_private()))
    except PublicPrivateMismatchError as ex:
        print(ex.args[0])
Пример #11
0
def create_output(item, key, subkey_path=None):
    output_dict = {}
    output_order = []

    def add_output(json_key, value=None, human_readable_key=None):
        if human_readable_key is None:
            human_readable_key = json_key.replace("_", " ")
        if value:
            output_dict[json_key.strip().lower()] = value
        output_order.append((json_key.lower(), human_readable_key))

    network_name = network_name_for_netcode(key._netcode)
    full_network_name = full_network_name_for_netcode(key._netcode)
    add_output("input", item)
    add_output("network", full_network_name)
    add_output("netcode", key._netcode)

    if hasattr(key, "wallet_key"):
        if subkey_path:
            add_output("subkey_path", subkey_path)

        add_output("wallet_key", key.wallet_key(as_private=key.is_private()))
        if key.is_private():
            add_output("public_version", key.wallet_key(as_private=False))

        child_number = key.child_index()
        if child_number >= 0x80000000:
            wc = child_number - 0x80000000
            child_index = "%dH (%d)" % (wc, child_number)
        else:
            child_index = "%d" % child_number
        add_output("tree_depth", "%d" % key.tree_depth())
        add_output("fingerprint", b2h(key.fingerprint()))
        add_output("parent_fingerprint", b2h(key.parent_fingerprint()),
                   "parent f'print")
        add_output("child_index", child_index)
        add_output("chain_code", b2h(key.chain_code()))

        add_output("private_key", "yes" if key.is_private() else "no")

    secret_exponent = key.secret_exponent()
    if secret_exponent:
        add_output("secret_exponent", '%d' % secret_exponent)
        add_output("secret_exponent_hex", '%x' % secret_exponent, " hex")
        add_output("wif", key.wif(use_uncompressed=False))
        add_output("wif_uncompressed", key.wif(use_uncompressed=True),
                   " uncompressed")

    public_pair = key.public_pair()

    if public_pair:
        add_output("public_pair_x", '%d' % public_pair[0])
        add_output("public_pair_y", '%d' % public_pair[1])
        add_output("public_pair_x_hex", '%x' % public_pair[0], " x as hex")
        add_output("public_pair_y_hex", '%x' % public_pair[1], " y as hex")
        add_output("y_parity", "odd" if (public_pair[1] & 1) else "even")

        add_output("key_pair_as_sec", b2h(key.sec(use_uncompressed=False)))
        add_output("key_pair_as_sec_uncompressed",
                   b2h(key.sec(use_uncompressed=True)), " uncompressed")

    hash160_c = key.hash160(use_uncompressed=False)
    if hash160_c:
        add_output("hash160", b2h(hash160_c))
    hash160_u = key.hash160(use_uncompressed=True)
    if hash160_u:
        add_output("hash160_uncompressed", b2h(hash160_u), " uncompressed")

    if hash160_c:
        address = key.address(use_uncompressed=False)
        add_output("address", address, "%s address" % network_name)
        output_dict["%s_address" % key._netcode] = address

    if hash160_u:
        address = key.address(use_uncompressed=True)
        add_output("address_uncompressed", address,
                   "%s address uncompressed" % network_name)
        output_dict["%s_address_uncompressed" % key._netcode] = address

    return output_dict, output_order
Пример #12
0
def main():
    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: BTC = Bitcoin)',
                        default='BTC',
                        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)')

    args = parser.parse_args()

    if args.override_network:
        # force network arg to match override, but also will override decoded data below.
        args.network = args.override_network

    def _create(_):
        max_retries = 64
        for _ in range(max_retries):
            try:
                return BIP32Node.from_master_secret(get_entropy(),
                                                    netcode=args.network)
            except ValueError as e:
                continue
        # Probably a bug if we get here
        raise e

    PREFIX_TRANSFORMS = (
        ("P:", lambda s: BIP32Node.from_master_secret(s.encode("utf8"),
                                                      netcode=args.network)),
        ("H:",
         lambda s: BIP32Node.from_master_secret(h2b(s), netcode=args.network)),
        ("E:", lambda s: key_from_text(s)),
        ("create", _create),
    )

    for item in args.item:
        key = None
        for k, f in PREFIX_TRANSFORMS:
            if item.startswith(k):
                try:
                    key = f(item[len(k):])
                    break
                except Exception:
                    pass
        else:
            try:
                key = Key.from_text(item)
            except encoding.EncodingError:
                pass
        if key is None:
            secret_exponent = parse_as_secret_exponent(item)
            if secret_exponent:
                key = Key(secret_exponent=secret_exponent,
                          netcode=args.network)

        if SEC_RE.match(item):
            key = Key.from_sec(h2b(item))

        if key is None:
            public_pair = parse_as_public_pair(item)
            if public_pair:
                key = Key(public_pair=public_pair, netcode=args.network)

        if HASH160_RE.match(item):
            key = Key(hash160=h2b(item), netcode=args.network)

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

        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.
            # XXX public interface for this is needed...
            key._netcode = args.override_network

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

            output_dict, output_order = create_output(item, key)

            if args.json:
                print(json.dumps(output_dict, indent=3, sort_keys=True))
            elif args.wallet:
                print(output_dict["wallet_key"])
            elif args.wif:
                print(output_dict["wif_uncompressed" if args.
                                  uncompressed else "wif"])
            elif args.address:
                print(output_dict["address" + (
                    "_uncompressed" if args.uncompressed else "")])
            else:
                dump_output(output_dict, output_order)
Пример #13
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
Пример #14
0
APP_AUTHOR = 'Davide Gessa'
DATA_DIR = app_data_path (appauthor=APP_AUTHOR, appname=APP_NAME)
TEMP_DIR_RELATIVE = '/temp/'
TEMP_DIR = DATA_DIR + TEMP_DIR_RELATIVE
DAPPS_DIR_RELATIVE = '/dapps/'
DAPPS_DIR = DATA_DIR + DAPPS_DIR_RELATIVE

BACKEND_PROTOCOLS = ['rpc', 'chainsoapi', 'node']

CHAINS = {
		'XTN' : {
			'code': 'XTN',
			'base_fee': 60000,
			'genesis_block': "000000000003035559c9f67359e8822d4f5484c56d507e86ce0d20f37e2f1b07",
			'genesis_height': 678322,
			'name': networks.full_network_name_for_netcode ('XTN'),
			'seeds': [ ]
		},
		'BTC' : {
			'code': 'BTC',
			'base_fee': 40000,
			'genesis_block': "000000000000000002f214ea3bc2c195ed11f9195ab07229151befab03ada10b",
			'genesis_height': 385720,
			'name': networks.full_network_name_for_netcode ('BTC')
		},
		'XLT' : {
			'code': 'XLT',
			'base_fee': 450000,
			'genesis_block': "22f9d7316645dc02cdd05c32db902ae4aca582c7f138b2b7cecbc58d269e58a6",
			'genesis_height': 741198,
			'name': networks.full_network_name_for_netcode ('XLT')
Пример #15
0
def create_output(item, key, subkey_path=None):
    output_dict = {}
    output_order = []

    def add_output(json_key, value=None, human_readable_key=None):
        if human_readable_key is None:
            human_readable_key = json_key.replace("_", " ")
        if value:
            output_dict[json_key.strip().lower()] = value
        output_order.append((json_key.lower(), human_readable_key))

    network_name = network_name_for_netcode(key._netcode)
    full_network_name = full_network_name_for_netcode(key._netcode)
    add_output("input", item)
    add_output("network", full_network_name)
    add_output("netcode", key._netcode)

    if hasattr(key, "wallet_key"):
        if subkey_path:
            add_output("subkey_path", subkey_path)

        add_output("wallet_key", key.wallet_key(as_private=key.is_private()))
        if key.is_private():
            add_output("public_version", key.wallet_key(as_private=False))

        child_number = key.child_index()
        if child_number >= 0x80000000:
            wc = child_number - 0x80000000
            child_index = "%dH (%d)" % (wc, child_number)
        else:
            child_index = "%d" % child_number
        add_output("tree_depth", "%d" % key.tree_depth())
        add_output("fingerprint", b2h(key.fingerprint()))
        add_output("parent_fingerprint", b2h(key.parent_fingerprint()), "parent f'print")
        add_output("child_index", child_index)
        add_output("chain_code", b2h(key.chain_code()))

        add_output("private_key", "yes" if key.is_private() else "no")

    secret_exponent = key.secret_exponent()
    if secret_exponent:
        add_output("secret_exponent", '%d' % secret_exponent)
        add_output("secret_exponent_hex", '%x' % secret_exponent, " hex")
        add_output("wif", key.wif(use_uncompressed=False))
        add_output("wif_uncompressed", key.wif(use_uncompressed=True), " uncompressed")

    public_pair = key.public_pair()

    if public_pair:
        add_output("public_pair_x", '%d' % public_pair[0])
        add_output("public_pair_y", '%d' % public_pair[1])
        add_output("public_pair_x_hex", '%x' % public_pair[0], " x as hex")
        add_output("public_pair_y_hex", '%x' % public_pair[1], " y as hex")
        add_output("y_parity", "odd" if (public_pair[1] & 1) else "even")

        add_output("key_pair_as_sec", b2h(key.sec(use_uncompressed=False)))
        add_output("key_pair_as_sec_uncompressed", b2h(key.sec(use_uncompressed=True)), " uncompressed")

    hash160_c = key.hash160(use_uncompressed=False)
    if hash160_c:
        add_output("hash160", b2h(hash160_c))
    hash160_u = key.hash160(use_uncompressed=True)
    if hash160_u:
        add_output("hash160_uncompressed", b2h(hash160_u), " uncompressed")

    if hash160_c:
        address = key.address(use_uncompressed=False)
        add_output("address", address, "%s address" % network_name)
        output_dict["%s_address" % key._netcode] = address

    if hash160_u:
        address = key.address(use_uncompressed=True)
        add_output("address_uncompressed", address, "%s address uncompressed" % network_name)
        output_dict["%s_address_uncompressed" % key._netcode] = address

    return output_dict, output_order
Пример #16
0
DATA_DIR = app_data_path(appauthor=APP_AUTHOR, appname=APP_NAME)
TEMP_DIR_RELATIVE = '/temp/'
TEMP_DIR = DATA_DIR + TEMP_DIR_RELATIVE
DAPPS_DIR_RELATIVE = '/dapps/'
DAPPS_DIR = DATA_DIR + DAPPS_DIR_RELATIVE

BACKEND_PROTOCOLS = ['rpc', 'chainsoapi', 'node']

CHAINS = {
    'XTN': {
        'code': 'XTN',
        'base_fee': 60000,
        'genesis_block':
        "000000000000ac2fd12f94bc68cba48aec5b8c597b341aeb1951f878faddfdfb",
        'genesis_height': 627820,
        'name': networks.full_network_name_for_netcode('XTN'),
        'seeds': []
    },
    'BTC': {
        'code': 'BTC',
        'base_fee': 40000,
        'genesis_block':
        "000000000000000002f214ea3bc2c195ed11f9195ab07229151befab03ada10b",
        'genesis_height': 385720,
        'name': networks.full_network_name_for_netcode('BTC')
    },
    'XLT': {
        'code': 'XLT',
        'base_fee': 450000,
        'genesis_block':
        "22f9d7316645dc02cdd05c32db902ae4aca582c7f138b2b7cecbc58d269e58a6",
Пример #17
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
Пример #18
0
def main():
    parser = argparse.ArgumentParser(
        description='ECkey2coin.py by [email protected] for UTXO based Certificates UTXOC.',
        epilog='Known networks codes:\n  ' \
                + ', '.join(['%s (%s)'%(i, full_network_name_for_netcode(i)) for i in NETWORK_NAMES])
    )
    parser.add_argument('-k', '--key', required=False, type=argparse.FileType('r'), help='The EC private key in PEM format')
    parser.add_argument('-q', '--qrfilename', required=False, help='QR code output filename')
    parser.add_argument('-n', "--network", help='specify network (default: BTC = Bitcoin)',
                                default='BTC', choices=NETWORK_NAMES)
    args = parser.parse_args()
    network = args.network
    inputprivatekey = ''
    if args.key:
        keyfile = args.key        
        while True:
            line = keyfile.readline().strip()
            if not line: break
            inputprivatekey += line + '\n'
        print 'Loaded EC Key from %s' % keyfile
    else:    
        print ('Please enter EC KEY in pem format:')
        inputprivatekey  = ''
        while True:
            line = raw_input().strip()
            if not line: break
            inputprivatekey += line + '\n'
    if not args.qrfilename:
        qrfilename = raw_input("Please enter qrcode output filename: ")
    else:
        qrfilename = args.qrfilename
    pkey = decoder.decode(read_pem(inputprivatekey), asn1Spec=ECPrivateKey())
    print 'Key loaded'
    if not isValidECKey(pkey[0]):
        print "EC Key Supplied cannot be used"
        exit
    print "Key Validated OK"
    inputkey = encoding.to_long(256, pycoin.encoding.byte_to_int, pkey[0][1].asOctets())[0]
    if inputkey:
        key = Key(secret_exponent=inputkey, netcode=network)
        btcsecret = key.secret_exponent()
        btcpublic = key.public_pair()
        hash160_c = key.hash160(use_uncompressed=False)
        hash160_u = key.hash160(use_uncompressed=True)
        qrimg = qrcode.QRCode (
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qrimg.add_data(key.address(use_uncompressed=False))
        qrimg.make(fit=True)
        img = qrimg.make_image()
        img.save(qrfilename)
    print"----------------- BEGIN EC PRIVATE KEYS -----------------"
    print "Secret:     %d" % btcsecret
    print "Secret hex: %x" % btcsecret
    print "wif:        %s" % key.wif(use_uncompressed=False)
    print "----------------- END EC PRIVATE KEYS -----------------------------"
    print "----------------- BEGIN PUBLIC KEY -----------------------------"
    print "Public X: %d" % btcpublic[0]
    print "Public Y: %d" % btcpublic[1]
    print "hash160 uncompressed: %s" % b2h(hash160_u)
    print "Sec: (uncompressed): %s" % b2h(key.sec(use_uncompressed=True))
    print "%s address: %s (uncompressed)" % (key._netcode, key.address(use_uncompressed=True))
    print "Public X (hex): %x" % btcpublic[0]
    print "Public Y (hex): %x" % btcpublic[1]
    print "Sec: %s" % b2h(key.sec(use_uncompressed=False))
    print "hash160 compressed: %s" % b2h(hash160_c)
    print "----------------- END PUBLIC KEYS -----------------------------"
    print "------------------ BEGIN %s ADDRESSES -------------------------" % key._netcode
    print "%s address: %s" % (key._netcode, key.address(use_uncompressed=False))
    print "------------------ END %s ADDRESSES -------------------------" % key._netcode