Пример #1
0
        def do_test(exp_hex, wif, c_wif, public_pair_sec, c_public_pair_sec,
                    address_b58, c_address_b58):
            secret_exponent = int(exp_hex, 16)
            sec = binascii.unhexlify(public_pair_sec)
            c_sec = binascii.unhexlify(c_public_pair_sec)

            self.assertEqual(
                secret_exponent_to_wif(secret_exponent, compressed=False), wif)
            self.assertEqual(
                secret_exponent_to_wif(secret_exponent, compressed=True),
                c_wif)

            exponent, compressed = wif_to_tuple_of_secret_exponent_compressed(
                wif)
            self.assertEqual(exponent, secret_exponent)
            self.assertFalse(compressed)

            exponent, compressed = wif_to_tuple_of_secret_exponent_compressed(
                c_wif)
            self.assertEqual(exponent, secret_exponent)
            self.assertTrue(compressed)

            public_pair = public_pair_for_secret_exponent(
                generator_secp256k1, secret_exponent)

            pk_public_pair = public_pair_from_sec(sec)
            compressed = is_sec_compressed(sec)
            self.assertEqual(pk_public_pair, public_pair)
            self.assertFalse(is_sec_compressed(sec))
            self.assertEqual(
                public_pair_to_sec(pk_public_pair, compressed=False), sec)

            pk_public_pair = public_pair_from_sec(c_sec)
            compressed = is_sec_compressed(c_sec)
            self.assertEqual(pk_public_pair, public_pair)
            self.assertTrue(compressed)
            self.assertEqual(
                public_pair_to_sec(pk_public_pair, compressed=True), c_sec)

            bca = public_pair_to_bitcoin_address(pk_public_pair,
                                                 compressed=True)
            self.assertEqual(bca, c_address_b58)

            self.assertEqual(
                bitcoin_address_to_ripemd160_sha_sec(c_address_b58),
                public_pair_to_ripemd160_sha_sec(pk_public_pair,
                                                 compressed=True))

            bca = public_pair_to_bitcoin_address(pk_public_pair,
                                                 compressed=False)
            self.assertEqual(bca, address_b58)

            self.assertEqual(
                bitcoin_address_to_ripemd160_sha_sec(address_b58),
                public_pair_to_ripemd160_sha_sec(pk_public_pair,
                                                 compressed=False))
Пример #2
0
def main():
    parser = argparse.ArgumentParser(description="Bitcoin utilities. WARNING: obsolete. Use ku instead.")

    parser.add_argument('-a', "--address", help='show as Bitcoin address', action='store_true')
    parser.add_argument('-1', "--hash160", help='show as hash 160', action='store_true')
    parser.add_argument('-v', "--verbose", help='dump all information available', action='store_true')
    parser.add_argument('-w', "--wif", help='show as Bitcoin WIF', action='store_true')
    parser.add_argument('-n', "--uncompressed", help='show in uncompressed form', action='store_true')
    parser.add_argument('item', help='a WIF, secret exponent, X/Y public pair, SEC (as hex), hash160 (as hex), Bitcoin address', nargs="+")
    args = parser.parse_args()

    for c in args.item:
        # figure out what it is:
        #  - secret exponent
        #  - WIF
        #  - X/Y public key (base 10 or hex)
        #  - sec
        #  - hash160
        #  - Bitcoin address
        secret_exponent = parse_as_private_key(c)
        if secret_exponent:
            public_pair = ecdsa.public_pair_for_secret_exponent(secp256k1.generator_secp256k1, secret_exponent)
            print("secret exponent: %d" % secret_exponent)
            print("  hex:           %x" % secret_exponent)
            print("WIF:             %s" % encoding.secret_exponent_to_wif(secret_exponent, compressed=True))
            print("  uncompressed:  %s" % encoding.secret_exponent_to_wif(secret_exponent, compressed=False))
        else:
            public_pair = parse_as_public_pair(c)
        if public_pair:
            bitcoin_address_uncompressed = encoding.public_pair_to_bitcoin_address(public_pair, compressed=False)
            bitcoin_address_compressed = encoding.public_pair_to_bitcoin_address(public_pair, compressed=True)
            print("public pair x:   %d" % public_pair[0])
            print("public pair y:   %d" % public_pair[1])
            print("  x as hex:      %x" % public_pair[0])
            print("  y as hex:      %x" % public_pair[1])
            print("y parity:        %s" % "odd" if (public_pair[1] & 1) else "even")
            print("key pair as sec: %s" % b2h(encoding.public_pair_to_sec(public_pair, compressed=True)))
            s = b2h(encoding.public_pair_to_sec(public_pair, compressed=False))
            print("  uncompressed:  %s\\\n                   %s" % (s[:66], s[66:]))
            hash160 = encoding.public_pair_to_hash160_sec(public_pair, compressed=True)
            hash160_unc = encoding.public_pair_to_hash160_sec(public_pair, compressed=False)
            myeccpoint = encoding.public_pair_to_sec(public_pair, compressed=True)
            myhash     = encoding.ripemd160( myeccpoint ).digest(  )
            print("BTSX PubKey:     %s" % BTS_ADDRESS_PREFIX + encoding.b2a_base58(myeccpoint + myhash[ :4 ]))
        else:
            hash160 = parse_as_address(c)
            hash160_unc = None
        if not hash160:
            sys.stderr.write("can't decode input %s\n" % c)
            sys.exit(1)
        print("hash160:         %s" % b2h(hash160))
        if hash160_unc:
            print("  uncompressed:  %s" % b2h(hash160_unc))
        print("Bitcoin address: %s" % encoding.hash160_sec_to_bitcoin_address(hash160))
        if hash160_unc:
            print("  uncompressed:  %s" % encoding.hash160_sec_to_bitcoin_address(hash160_unc))
Пример #3
0
def main():
    parser = argparse.ArgumentParser(description="Bitcoin utilities.")

    parser.add_argument('-a', "--address", help='show as Bitcoin address', action='store_true')
    parser.add_argument('-1', "--hash160", help='show as hash 160', action='store_true')
    parser.add_argument('-v', "--verbose", help='dump all information available', action='store_true')
    parser.add_argument('-w', "--wif", help='show as Bitcoin WIF', action='store_true')
    parser.add_argument('-n', "--uncompressed", help='show in uncompressed form', action='store_true')
    parser.add_argument('item', help='a WIF, secret exponent, X/Y public pair, SEC (as hex), hash160 (as hex), Bitcoin address', nargs="+")
    args = parser.parse_args()

    for c in args.item:
        # figure out what it is:
        #  - secret exponent
        #  - WIF
        #  - X/Y public key (base 10 or hex)
        #  - sec
        #  - hash160
        #  - Bitcoin address
        secret_exponent = parse_as_private_key(c)
        if secret_exponent:
            public_pair = ecdsa.public_pair_for_secret_exponent(secp256k1.generator_secp256k1, secret_exponent)
            print("secret exponent: %d" % secret_exponent)
            print("  hex:           %x" % secret_exponent)
            print("WIF:             %s" % encoding.secret_exponent_to_wif(secret_exponent, compressed=True))
            print("  uncompressed:  %s" % encoding.secret_exponent_to_wif(secret_exponent, compressed=False))
        else:
            public_pair = parse_as_public_pair(c)
        if public_pair:
            bitcoin_address_uncompressed = encoding.public_pair_to_bitcoin_address(public_pair, compressed=False)
            bitcoin_address_compressed = encoding.public_pair_to_bitcoin_address(public_pair, compressed=True)
            print("public pair x:   %d" % public_pair[0])
            print("public pair y:   %d" % public_pair[1])
            print("  x as hex:      %x" % public_pair[0])
            print("  y as hex:      %x" % public_pair[1])
            print("y parity:        %s" % "odd" if (public_pair[1] & 1) else "even")
            print("key pair as sec: %s" % b2h(encoding.public_pair_to_sec(public_pair, compressed=True)))
            s = b2h(encoding.public_pair_to_sec(public_pair, compressed=False))
            print("  uncompressed:  %s\\\n                   %s" % (s[:66], s[66:]))
            hash160 = encoding.public_pair_to_hash160_sec(public_pair, compressed=True)
            hash160_unc = encoding.public_pair_to_hash160_sec(public_pair, compressed=False)
        else:
            hash160 = parse_as_address(c)
            hash160_unc = None
        if not hash160:
            sys.stderr.write("can't decode input %s\n" % c)
            sys.exit(1)
        print("hash160:         %s" % b2h(hash160))
        if hash160_unc:
            print("  uncompressed:  %s" % b2h(hash160_unc))
        print("Bitcoin address: %s" % encoding.hash160_sec_to_bitcoin_address(hash160))
        if hash160_unc:
            print("  uncompressed:  %s" % encoding.hash160_sec_to_bitcoin_address(hash160_unc))
Пример #4
0
        def do_test(exp_hex, wif, c_wif, public_pair_sec, c_public_pair_sec,
                    address_b58, c_address_b58):
            secret_exponent = int(exp_hex, 16)
            sec = h2b(public_pair_sec)
            c_sec = h2b(c_public_pair_sec)

            self.assertEqual(
                secret_exponent_to_wif(secret_exponent, compressed=False), wif)
            self.assertEqual(
                secret_exponent_to_wif(secret_exponent, compressed=True),
                c_wif)

            exponent, compressed = wif_to_tuple_of_secret_exponent_compressed(
                wif)
            self.assertEqual(exponent, secret_exponent)
            self.assertFalse(compressed)

            exponent, compressed = wif_to_tuple_of_secret_exponent_compressed(
                c_wif)
            self.assertEqual(exponent, secret_exponent)
            self.assertTrue(compressed)

            public_pair = secret_exponent * secp256k1_generator

            pk_public_pair = sec_to_public_pair(sec)
            compressed = is_sec_compressed(sec)
            self.assertEqual(pk_public_pair, public_pair)
            self.assertFalse(is_sec_compressed(sec))
            self.assertEqual(
                public_pair_to_sec(pk_public_pair, compressed=False), sec)

            pk_public_pair = sec_to_public_pair(c_sec)
            compressed = is_sec_compressed(c_sec)
            self.assertEqual(pk_public_pair, public_pair)
            self.assertTrue(compressed)
            self.assertEqual(
                public_pair_to_sec(pk_public_pair, compressed=True), c_sec)

            bca = public_pair_to_bitcoin_address(pk_public_pair,
                                                 compressed=True)
            self.assertEqual(bca, c_address_b58)

            self.assertEqual(
                bitcoin_address_to_hash160_sec(c_address_b58),
                public_pair_to_hash160_sec(pk_public_pair, compressed=True))

            bca = public_pair_to_bitcoin_address(pk_public_pair,
                                                 compressed=False)
            self.assertEqual(bca, address_b58)

            self.assertEqual(
                bitcoin_address_to_hash160_sec(address_b58),
                public_pair_to_hash160_sec(pk_public_pair, compressed=False))
Пример #5
0
def generate_redeem_link(email):

    #Generate (Public, Private) key pair
    rand = os.urandom(32).encode('hex')
    secret_exponent = int("0x" + rand, 0)
    private_key = encoding.secret_exponent_to_wif(secret_exponent,
                                                  compressed=True)
    public_pair = ecdsa.public_pair_for_secret_exponent(
        ecdsa.secp256k1.generator_secp256k1, secret_exponent)
    public_key1 = "04" + format(public_pair[0], 'x') + format(
        public_pair[1], 'x')

    #Only submit public_key/email to server
    post_request_data = {"public_key1": public_key1, "email": email}
    response = requests.post(SPLIT_KEY_API, data=post_request_data)
    result = response.json()
    btc_address = result.get("bitcoin_address")

    if btc_address:
        email_redeem_code(btc_address)
        redeem_url = "{}?key1={}&bitcoin_address={}".format(
            REDEEM_ENDPOINT, private_key, btc_address)
        return [email, btc_address, redeem_url]
    else:
        raise RuntimeError(result['message'])
Пример #6
0
def generate_redeem_link(email):

  #Generate (Public, Private) key pair
  rand = os.urandom(32).encode('hex')
  secret_exponent= int("0x"+rand, 0) % ecdsa.secp256k1._r
  private_key = encoding.secret_exponent_to_wif(secret_exponent, compressed=True)
  public_pair = ecdsa.public_pair_for_secret_exponent(ecdsa.secp256k1.generator_secp256k1,secret_exponent)
  public_key1 = "04" + format(public_pair[0], '064x') + format(public_pair[1], '064x')

  #Only submit public_key/email to server
  post_request_data = { "public_key1" : public_key1, "email" : email,
                       "refund_time": REFUND_TIME} 
  headers={'Authorization': 'Bearer {}'.format(API_KEY)}
  response = requests.post(SPLIT_KEY_API, data=post_request_data,
                           headers=headers)
  result = response.json()
  btc_address = result.get("bitcoin_address")

  if btc_address:
    email_redeem_code(btc_address)
    redeem_url="{}?key1={}&bitcoin_address={}".format(REDEEM_ENDPOINT,
                                                      private_key, btc_address)
    return dict(redeem_url = redeem_url, 
                bitcoin_address = btc_address)
  else:
    raise RuntimeError(result['message'])
Пример #7
0
def gen_address(private_key, compressed=True):
    # private_key = codecs.encode(os.urandom(32), 'hex').decode()
    secret_exponent = int('0x' + private_key, 0)
    print('WIF: ' + encoding.secret_exponent_to_wif(secret_exponent, compressed=compressed))
    public_pair = ecdsa.public_pair_for_secret_exponent(ecdsa.secp256k1.generator_secp256k1, secret_exponent)
    print('public pair:', public_pair)
    hash160 = encoding.public_pair_to_hash160_sec(public_pair, compressed=compressed)
    print("hash160: {}".format(hash160.hex()))
    return encoding.hash160_sec_to_bitcoin_address(hash160, address_prefix=b'\0')
Пример #8
0
 def dumpprivkey(self, address, return_sec_exp=False):
     if is_valid_bitcoin_address(address) == False:
         return Exception("Invalid address %s" % address)
     try:
         secret_exponent = self.getsecretexponent(address)
         wif = secret_exponent_to_wif(secret_exponent)
     except:
         raise Exception("Unknown address: %s" % address)
     return wif
Пример #9
0
 def dumpprivkey(self, address, return_sec_exp=False):
     if is_valid_bitcoin_address(address)==False:
         return Exception("Invalid address %s" % address)
     try:
         secret_exponent = self.getsecretexponent(address)
         wif = secret_exponent_to_wif(secret_exponent)
     except:
         raise Exception("Unknown address: %s" % address)
     return wif
Пример #10
0
 def do_test(as_secret_exponent, as_wif, is_compressed):
     self.assertEqual(
         as_wif,
         encoding.secret_exponent_to_wif(as_secret_exponent,
                                         compressed=is_compressed))
     se, comp = encoding.wif_to_tuple_of_secret_exponent_compressed(
         as_wif)
     self.assertEqual(se, as_secret_exponent)
     self.assertEqual(comp, is_compressed)
     self.assertTrue(encoding.is_valid_wif(as_wif))
Пример #11
0
        def do_test(exp_hex, wif, c_wif, public_pair_sec, c_public_pair_sec, address_b58, c_address_b58):
            secret_exponent = int(exp_hex, 16)
            sec = h2b(public_pair_sec)
            c_sec = h2b(c_public_pair_sec)

            self.assertEqual(secret_exponent_to_wif(secret_exponent, compressed=False), wif)
            self.assertEqual(secret_exponent_to_wif(secret_exponent, compressed=True), c_wif)

            exponent, compressed = wif_to_tuple_of_secret_exponent_compressed(wif)
            self.assertEqual(exponent, secret_exponent)
            self.assertFalse(compressed)

            exponent, compressed = wif_to_tuple_of_secret_exponent_compressed(c_wif)
            self.assertEqual(exponent, secret_exponent)
            self.assertTrue(compressed)

            public_pair = secret_exponent * secp256k1_generator

            pk_public_pair = sec_to_public_pair(sec)
            compressed = is_sec_compressed(sec)
            self.assertEqual(pk_public_pair, public_pair)
            self.assertFalse(is_sec_compressed(sec))
            self.assertEqual(public_pair_to_sec(pk_public_pair, compressed=False), sec)

            pk_public_pair = sec_to_public_pair(c_sec)
            compressed = is_sec_compressed(c_sec)
            self.assertEqual(pk_public_pair, public_pair)
            self.assertTrue(compressed)
            self.assertEqual(public_pair_to_sec(pk_public_pair, compressed=True), c_sec)

            bca = public_pair_to_bitcoin_address(pk_public_pair, compressed=True)
            self.assertEqual(bca, c_address_b58)

            self.assertEqual(bitcoin_address_to_hash160_sec(c_address_b58),
                             public_pair_to_hash160_sec(pk_public_pair, compressed=True))

            bca = public_pair_to_bitcoin_address(pk_public_pair, compressed=False)
            self.assertEqual(bca, address_b58)

            self.assertEqual(bitcoin_address_to_hash160_sec(address_b58),
                             public_pair_to_hash160_sec(pk_public_pair, compressed=False))
Пример #12
0
 def wif(self, use_uncompressed=None):
     """
     Return the WIF representation of this key, if available.
     If use_uncompressed is not set, the preferred representation is returned.
     """
     wif_prefix = wif_prefix_for_netcode(self._netcode)
     secret_exponent = self.secret_exponent()
     if secret_exponent is None:
         return None
     return secret_exponent_to_wif(secret_exponent,
                                   compressed=not self._use_uncompressed(use_uncompressed),
                                   wif_prefix=wif_prefix)
Пример #13
0
def privkey_to_wif(privkey, netcode="BTC"):
    """ Get private key from bitcoin wif.

    Args:
        privkey (str): Hex encoded private key

    Return:
        str: Private key encode in bitcoin wif format.
    """
    prefix = networks.wif_prefix_for_netcode(netcode)
    secret_exponent = encoding.from_bytes_32(h2b(privkey))
    return encoding.secret_exponent_to_wif(secret_exponent, wif_prefix=prefix)
Пример #14
0
 def wif(self, use_uncompressed=None):
     """
     Return the WIF representation of this key, if available.
     If use_uncompressed is not set, the preferred representation is returned.
     """
     wif_prefix = wif_prefix_for_netcode(self._netcode)
     secret_exponent = self.secret_exponent()
     if secret_exponent is None:
         return None
     return secret_exponent_to_wif(secret_exponent,
                                   compressed=not self._use_uncompressed(use_uncompressed),
                                   wif_prefix=wif_prefix)
Пример #15
0
    def _calculate_all(self):
        for attr in "_secret_exponent _public_pair _wif_uncompressed _wif_compressed _sec_compressed" \
                " _sec_uncompressed _hash160_compressed _hash160_uncompressed _address_compressed" \
                " _address_uncompressed _netcode".split():
            setattr(self, attr, getattr(self, attr, None))

        if self._hierarchical_wallet:
            if self._hierarchical_wallet.is_private:
                self._secret_exponent = self._hierarchical_wallet.secret_exponent
            else:
                self._public_pair = self._hierarchical_wallet.public_pair
            self._netcode = self._hierarchical_wallet.netcode

        wif_prefix = wif_prefix_for_netcode(self._netcode)

        if self._secret_exponent:
            self._wif_uncompressed = secret_exponent_to_wif(
                self._secret_exponent, compressed=False, wif_prefix=wif_prefix)
            self._wif_compressed = secret_exponent_to_wif(
                self._secret_exponent, compressed=True, wif_prefix=wif_prefix)
            self._public_pair = ecdsa.public_pair_for_secret_exponent(
                ecdsa.generator_secp256k1, self._secret_exponent)

        if self._public_pair:
            self._sec_compressed = public_pair_to_sec(self._public_pair,
                                                      compressed=True)
            self._sec_uncompressed = public_pair_to_sec(self._public_pair,
                                                        compressed=False)
            self._hash160_compressed = hash160(self._sec_compressed)
            self._hash160_uncompressed = hash160(self._sec_uncompressed)

        address_prefix = address_prefix_for_netcode(self._netcode)

        if self._hash160_compressed:
            self._address_compressed = hash160_sec_to_bitcoin_address(
                self._hash160_compressed, address_prefix=address_prefix)

        if self._hash160_uncompressed:
            self._address_uncompressed = hash160_sec_to_bitcoin_address(
                self._hash160_uncompressed, address_prefix=address_prefix)
        def do_test(exp_hex, wif, c_wif, public_pair_sec, c_public_pair_sec, address_b58, c_address_b58):
            secret_exponent = int(exp_hex, 16)
            sec = binascii.unhexlify(public_pair_sec)
            c_sec = binascii.unhexlify(c_public_pair_sec)

            self.assertEqual(secret_exponent_to_wif(secret_exponent, compressed=False), wif)
            self.assertEqual(secret_exponent_to_wif(secret_exponent, compressed=True), c_wif)

            exponent, compressed = wif_to_tuple_of_secret_exponent_compressed(wif)
            self.assertEqual(exponent, secret_exponent)
            self.assertFalse(compressed)

            exponent, compressed = wif_to_tuple_of_secret_exponent_compressed(c_wif)
            self.assertEqual(exponent, secret_exponent)
            self.assertTrue(compressed)

            public_pair = public_pair_for_secret_exponent(generator_secp256k1, secret_exponent)

            pk_public_pair = public_pair_from_sec(sec)
            compressed = is_sec_compressed(sec)
            self.assertEqual(pk_public_pair, public_pair)
            self.assertFalse(is_sec_compressed(sec))
            self.assertEqual(public_pair_to_sec(pk_public_pair, compressed=False), sec)

            pk_public_pair = public_pair_from_sec(c_sec)
            compressed = is_sec_compressed(c_sec)
            self.assertEqual(pk_public_pair, public_pair)
            self.assertTrue(compressed)
            self.assertEqual(public_pair_to_sec(pk_public_pair, compressed=True), c_sec)

            bca = public_pair_to_bitcoin_address(pk_public_pair, compressed=True)
            self.assertEqual(bca, c_address_b58)

            self.assertEqual(bitcoin_address_to_ripemd160_sha_sec(c_address_b58), public_pair_to_ripemd160_sha_sec(pk_public_pair, compressed=True))

            bca = public_pair_to_bitcoin_address(pk_public_pair, compressed=False)
            self.assertEqual(bca, address_b58)

            self.assertEqual(bitcoin_address_to_ripemd160_sha_sec(address_b58), public_pair_to_ripemd160_sha_sec(pk_public_pair, compressed=False))
Пример #17
0
def gen_address(private_key, compressed=True):
    # private_key = codecs.encode(os.urandom(32), 'hex').decode()
    secret_exponent = int('0x' + private_key, 0)
    print('WIF: ' + encoding.secret_exponent_to_wif(secret_exponent,
                                                    compressed=compressed))
    public_pair = ecdsa.public_pair_for_secret_exponent(
        ecdsa.secp256k1.generator_secp256k1, secret_exponent)
    print('public pair:', public_pair)
    hash160 = encoding.public_pair_to_hash160_sec(public_pair,
                                                  compressed=compressed)
    print("hash160: {}".format(hash160.hex()))
    return encoding.hash160_sec_to_bitcoin_address(hash160,
                                                   address_prefix=b'\0')
Пример #18
0
    def _calculate_all(self):
        for attr in "_secret_exponent _public_pair _wif_uncompressed _wif_compressed _sec_compressed" \
                " _sec_uncompressed _hash160_compressed _hash160_uncompressed _address_compressed" \
                " _address_uncompressed _netcode".split():
                setattr(self, attr, getattr(self, attr, None))

        if self._hierarchical_wallet:
            if self._hierarchical_wallet.is_private:
                self._secret_exponent = self._hierarchical_wallet.secret_exponent
            else:
                self._public_pair = self._hierarchical_wallet.public_pair
            self._netcode = self._hierarchical_wallet.netcode

        wif_prefix = wif_prefix_for_netcode(self._netcode)

        if self._secret_exponent:
            self._wif_uncompressed = secret_exponent_to_wif(
                self._secret_exponent, compressed=False, wif_prefix=wif_prefix)
            self._wif_compressed = secret_exponent_to_wif(
                self._secret_exponent, compressed=True, wif_prefix=wif_prefix)
            self._public_pair = ecdsa.public_pair_for_secret_exponent(
                ecdsa.generator_secp256k1, self._secret_exponent)

        if self._public_pair:
            self._sec_compressed = public_pair_to_sec(self._public_pair, compressed=True)
            self._sec_uncompressed = public_pair_to_sec(self._public_pair, compressed=False)
            self._hash160_compressed = hash160(self._sec_compressed)
            self._hash160_uncompressed = hash160(self._sec_uncompressed)

        address_prefix = address_prefix_for_netcode(self._netcode)

        if self._hash160_compressed:
            self._address_compressed = hash160_sec_to_bitcoin_address(
                self._hash160_compressed, address_prefix=address_prefix)

        if self._hash160_uncompressed:
            self._address_uncompressed = hash160_sec_to_bitcoin_address(
                self._hash160_uncompressed, address_prefix=address_prefix)
Пример #19
0
def GenerateKeys(indata):
    #Secret integer
    if indata == '0':
        k = random.randrange(
            1, 1000000
        )  #Valde bara mellan 1-1000,000 som ex. randrange är ju inte totalt random heller..
    else:
        k = int(indata)

    #Kodar om secret integer till uncompressed public key
    secp = ecdsa.secp256k1
    G = secp.generator_secp256k1
    P = k * G

    #Kodar om P till compressed format
    x = '%064x' % P.x()
    comp_pk = ('02' if P.x() % 2 == 0 else '03') + x

    #Kodar om secret integer till wif format
    wif = encoding.secret_exponent_to_wif(
        k
    )  #Skrev ingen kod för att göra om till wif då det fanns en färdig metod för det..

    print("Public key")
    print("   Public uncompressed key is:")
    print("    x:", P.x())
    print("    y:", P.y())
    print("   Public compressed key is:")
    print("    ", comp_pk)

    print("------------")
    print("Private key")
    print("   Tal: ", k)
    print("   Hex: ", hex(k)[2:])
    print("   Wif: ", wif)

    publicPair = [
        P.x(), P.y()
    ]  #Array som sparar X,Y för att kunna kodas om till bitcoin address
    print("------------------")
    print(
        "Bitcoin Address: "
    )  #Samma sak här, finns färdiga metoder för att koda om till bitcoin address
    print("   Uncompressed: ",
          encoding.public_pair_to_bitcoin_address(publicPair, False))
    print("   Compressed:   ",
          encoding.public_pair_to_bitcoin_address(publicPair, True))
Пример #20
0
	def _gen (self):
		logger.debug ('Generating entropy for new wallet...')

		# Generate entropy
		entropy = bytearray()
		try:
			entropy.extend(open("/dev/random", "rb").read(64))
		except Exception:
			print("warning: can't use /dev/random as entropy source")
		entropy = bytes(entropy)

		if len(entropy) < 64:
			raise OSError("can't find sources of entropy")

		secret_exponent = int(binascii.hexlify (entropy)[0:32], 16)
		wif = secret_exponent_to_wif(secret_exponent, compressed=True, wif_prefix=wif_prefix_for_netcode (self.chain))
		key = Key (secret_exponent=secret_exponent, netcode=self.chain)
		return (str (key.address ()), str (key.wif ()))
Пример #21
0
 def warp(self, passphrase, salt=""):
   """
   Return dictionary of WarpWallet public and private keys corresponding to
   the given passphrase and salt.
   """
   s1 = binascii.hexlify(self._scrypt(passphrase, salt))
   out = self._pbkdf2(passphrase, salt)
   s2 = binascii.hexlify(out)
   base = binascii.unhexlify(s1)
   s3 = binascii.hexlify(self._sxor(base,out))
   secret_exponent = int(s3, 16)
   public_pair = ecdsa.public_pair_for_secret_exponent(secp256k1.generator_secp256k1, secret_exponent)
   private_key = encoding.secret_exponent_to_wif(secret_exponent, compressed=False)
   public_key = encoding.public_pair_to_bitcoin_address(public_pair, compressed=False)
   out = { "keys" : { "private_key" : private_key,
                      "public_key" : public_key },
           "seeds" : [s1, s2, s3],
           "passphrase" : passphrase,
           "salt" : salt }
   return out
Пример #22
0
import unittest

from pycoin.ecdsa import generator_secp256k1, public_pair_for_secret_exponent
from pycoin.encoding import public_pair_to_bitcoin_address, secret_exponent_to_wif

from pycoin.tx.exceptions import BadSpendableError
from pycoin.tx.tx_utils import create_signed_tx
from pycoin.tx.Spendable import Spendable
from pycoin.ui import standard_tx_out_script


BITCOIN_ADDRESSES = [public_pair_to_bitcoin_address(
    public_pair_for_secret_exponent(generator_secp256k1, i))
    for i in range(1, 21)]

WIFS = [secret_exponent_to_wif(i) for i in range(1, 21)]

FAKE_HASHES = [hashlib.sha256(struct.pack("Q", idx)).digest() for idx in range(100)]


class SpendTest(unittest.TestCase):

    def test_simple_spend(self):

        FEE = 10000

        # create a fake Spendable
        COIN_VALUE = 100000000
        spendables = [Spendable(COIN_VALUE, standard_tx_out_script(BITCOIN_ADDRESSES[0]), FAKE_HASHES[1], 0)]

        EXPECTED_IDS = [
Пример #23
0
 def get_private_key(self):
     return secret_exponent_to_wif(self.rawPrivKey, False, self.testnet)
print()
print("CECKey example - ", my_netcode)
print("Pubkey Addr Ver: ", bitcoin.params.BASE58_PREFIXES['PUBKEY_ADDR'],
      ", Secret Key Ver: ", bitcoin.params.BASE58_PREFIXES['SECRET_KEY'])

# use CECKey class
cec_key = CECKey()
#cec_key.set_secretbytes(privkey_bytes)
random_nbr = 1  #util.randrange(ecdsa.generator_secp256k1.order())
my_secret_exp = b2h(encoding.to_bytes_32(random_nbr))
cec_key.set_secretbytes(bitcoin.core.x(my_secret_exp))

print("Private Key dec: ", random_nbr)
print("Private Key hex: ", my_secret_exp)
privkey_wif = encoding.secret_exponent_to_wif(eval('0x' + my_secret_exp),
                                              wif_prefix=my_privkey_prefix)
print("Private key WIF: ", privkey_wif)
privkey_wif = encoding.secret_exponent_to_wif(eval('0x' + my_secret_exp),
                                              False,
                                              wif_prefix=my_privkey_prefix)
print("   uncompressed: ", privkey_wif)

cec_key.set_compressed(True)

print()
pubkey_pair = encoding.sec_to_public_pair(cec_key.get_pubkey())
print("Public key pair: ", pubkey_pair)

(pub_key_x, pub_key_y) = pubkey_pair
compressed_indicator = True if (pub_key_y % 2) == 0 else False
print("Public key y parity? ", 'even' if compressed_indicator else 'odd')
Пример #25
0
 def get_private_key(self):
     return secret_exponent_to_wif(self.rawPrivKey, False, self.prefix)
Пример #26
0
#Below generate correct public address as found with money

import hashlib
from pycoin import ecdsa, encoding
import os
import codecs

if __name__ == '__main__':

    #rand = codecs.encode(os.urandom(32), 'hex').decode()
    #secret_exponent= int('0x'+rand, 0)

    secret_exponent = int(hp, 16)

    print('WIF: ' +
          encoding.secret_exponent_to_wif(secret_exponent, compressed=False))
    public_pair = ecdsa.public_pair_for_secret_exponent(
        ecdsa.secp256k1.generator_secp256k1, secret_exponent)
    hash160 = encoding.public_pair_to_hash160_sec(public_pair, compressed=True)

    codecs.encode(hash160, 'hex')

    print('Bitcoin address: %s' %
          encoding.hash160_sec_to_bitcoin_address(hash160))

    with open('../../Mining/dict/UrbanDictionary.txt', 'r') as f:
        contents = f.readlines()

    fout = open('privaddr-pair.txt', 'w')

    i = 0
Пример #27
0
 def wif(self, compressed=True):
     """Return the base58 representation (WIF format) for the private
     key
     """
     return secret_exponent_to_wif(self.exponent)
 def do_test(as_secret_exponent, as_wif, is_compressed):
     self.assertEqual(as_wif, encoding.secret_exponent_to_wif(as_secret_exponent, compressed=is_compressed))
     se, comp = encoding.wif_to_tuple_of_secret_exponent_compressed(as_wif)
     self.assertEqual(se, as_secret_exponent)
     self.assertEqual(comp, is_compressed)
     self.assertTrue(encoding.is_valid_wif(as_wif))
Пример #29
0
def main():
    parser = argparse.ArgumentParser(description="Bitcoin utilities.")

    parser.add_argument("-a", "--address", help="show as Bitcoin address", action="store_true")
    parser.add_argument("-1", "--hash160", help="show as hash 160", action="store_true")
    parser.add_argument("-v", "--verbose", help="dump all information available", action="store_true")
    parser.add_argument("-w", "--wif", help="show as Bitcoin WIF", action="store_true")
    parser.add_argument("-n", "--uncompressed", help="show in uncompressed form", action="store_true")
    parser.add_argument("-j", "--json", help="output in JSON format", action="store_true")
    parser.add_argument("-t", help="interpret fields as test values", action="store_true")
    parser.add_argument("-ltc", help="generate LTC address", action="store_true")
    parser.add_argument("-doge", help="generate DOGE address", action="store_true")
    parser.add_argument(
        "item",
        help="a WIF, secret exponent, X/Y public pair, SEC (as hex), hash160 (as hex), Bitcoin address",
        nargs="+",
    )
    args = parser.parse_args()

    if args.ltc:
        args.t = "litecoin"
    else:
        if args.doge:
            if args.t:
                args.t = "dogetest"
            else:
                args.t = "doge"

    if args.json:
        print("{")
        argcount = len(args.item)
        i = 0
        for c in args.item:
            i = i + 1
            print('  "%s" : { ' % c)
            secret_exponent = parse_as_private_key(c)
            if secret_exponent:
                public_pair = ecdsa.public_pair_for_secret_exponent(secp256k1.generator_secp256k1, secret_exponent)
                print('    "secret_exponent" : "%d",' % secret_exponent)
                print('    "secret_exponent_hex" : "%x",' % secret_exponent)
                print(
                    '    "wif" : "%s",'
                    % encoding.secret_exponent_to_wif(secret_exponent, compressed=True, is_test=args.t)
                )
                print(
                    '    "wif_uncompressed" : "%s",'
                    % encoding.secret_exponent_to_wif(secret_exponent, compressed=False, is_test=args.t)
                )
            else:
                public_pair = parse_as_public_pair(c)
            if public_pair:
                bitcoin_address_uncompressed = encoding.public_pair_to_bitcoin_address(
                    public_pair, compressed=False, is_test=args.t
                )
                bitcoin_address_compressed = encoding.public_pair_to_bitcoin_address(
                    public_pair, compressed=True, is_test=args.t
                )
                print('    "public_pair_x" : "%d",' % public_pair[0])
                print('    "public_pair_y" : "%d",' % public_pair[1])
                print('    "x_as_hex" : "%x",' % public_pair[0])
                print('    "y_as_hex" : "%x",' % public_pair[1])
                if public_pair[1] & 1:
                    print('    "y_parity" : "odd",')
                else:
                    print('    "y_parity" : "even",')
                print('    "key_pair_as_sec" : "%s",' % b2h(encoding.public_pair_to_sec(public_pair, compressed=True)))
                hash160 = encoding.public_pair_to_hash160_sec(public_pair, compressed=True)
                hash160_unc = encoding.public_pair_to_hash160_sec(public_pair, compressed=False)
            else:
                hash160 = parse_as_address(c)
                hash160_unc = None
            if not hash160:
                print('  "error" : "cannot decode input %s",' % c)
            print('    "hash160" : "%s",' % b2h(hash160))
            if hash160_unc:
                print('    "hash160_uncompressed" : "%s",' % b2h(hash160_unc))
            if hash160_unc:
                # print('    "bitcoind_addr_uncompressed" : "%s",' % encoding.hash160_sec_to_bitcoin_address(hash160_unc))
                print('    "bitcoind_addr_uncompressed" : "%s",' % bitcoin_address_uncompressed)
            # print('    "bitcoin_addr" : "%s"' % encoding.hash160_sec_to_bitcoin_address(hash160))
            print('    "bitcoin_addr" : "%s"' % bitcoin_address_compressed)
            if i == argcount:
                print("  }")
            else:
                print("  },")
        print("}")
    else:
        for c in args.item:
            # figure out what it is:
            #  - secret exponent
            #  - WIF
            #  - X/Y public key (base 10 or hex)
            #  - sec
            #  - hash160
            #  - Bitcoin address
            secret_exponent = parse_as_private_key(c)
            if secret_exponent:
                public_pair = ecdsa.public_pair_for_secret_exponent(secp256k1.generator_secp256k1, secret_exponent)
                print("secret exponent: %d" % secret_exponent)
                print("  hex:           %x" % secret_exponent)
                print("WIF:             %s" % encoding.secret_exponent_to_wif(secret_exponent, compressed=True))
                print("  uncompressed:  %s" % encoding.secret_exponent_to_wif(secret_exponent, compressed=False))
            else:
                public_pair = parse_as_public_pair(c)
            if public_pair:
                bitcoin_address_uncompressed = encoding.public_pair_to_bitcoin_address(public_pair, compressed=False)
                bitcoin_address_compressed = encoding.public_pair_to_bitcoin_address(public_pair, compressed=True)
                print("public pair x:   %d" % public_pair[0])
                print("public pair y:   %d" % public_pair[1])
                print("  x as hex:      %x" % public_pair[0])
                print("  y as hex:      %x" % public_pair[1])
                print("y parity:        %s" % "odd" if (public_pair[1] & 1) else "even")
                print("key pair as sec: %s" % b2h(encoding.public_pair_to_sec(public_pair, compressed=True)))
                s = b2h(encoding.public_pair_to_sec(public_pair, compressed=False))
                print("  uncompressed:  %s\\\n                   %s" % (s[:66], s[66:]))
                hash160 = encoding.public_pair_to_hash160_sec(public_pair, compressed=True)
                hash160_unc = encoding.public_pair_to_hash160_sec(public_pair, compressed=False)
            else:
                hash160 = parse_as_address(c)
                hash160_unc = None
            if not hash160:
                sys.stderr.write("can't decode input %s\n" % c)
                sys.exit(1)
            print("hash160:         %s" % b2h(hash160))
            if hash160_unc:
                print("  uncompressed:  %s" % b2h(hash160_unc))
            print("Bitcoin address: %s" % encoding.hash160_sec_to_bitcoin_address(hash160))
            if hash160_unc:
                print("  uncompressed:  %s" % encoding.hash160_sec_to_bitcoin_address(hash160_unc))
Пример #30
0
from pycoin.ecdsa import generator_secp256k1, public_pair_for_secret_exponent
from pycoin.encoding import public_pair_to_bitcoin_address, secret_exponent_to_wif

from pycoin.tx.Tx import BadSpendableError
from pycoin.tx.TxOut import standard_tx_out_script
from pycoin.tx.tx_utils import create_signed_tx
from pycoin.tx.Spendable import Spendable

BITCOIN_ADDRESSES = [
    public_pair_to_bitcoin_address(
        public_pair_for_secret_exponent(generator_secp256k1, i))
    for i in range(1, 21)
]

WIFS = [secret_exponent_to_wif(i) for i in range(1, 21)]

FAKE_HASHES = [
    hashlib.sha256(struct.pack("Q", idx)).digest() for idx in range(100)
]


class SpendTest(unittest.TestCase):
    def test_simple_spend(self):

        FEE = 10000

        # create a fake Spendable
        COIN_VALUE = 100000000
        spendables = [
            Spendable(COIN_VALUE, standard_tx_out_script(BITCOIN_ADDRESSES[0]),