def test_build_spends(self): # first, here is the tx database TX_DB = {} # create a coinbase Tx where we know the public & private key exponent = wif_to_secret_exponent("5JMys7YfK72cRVTrbwkq5paxU7vgkMypB55KyXEtN5uSnjV7K8Y") compressed = False public_key_sec = public_pair_to_sec( ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, exponent), compressed=compressed ) the_coinbase_tx = Tx.coinbase_tx(public_key_sec, int(50 * 1e8), COINBASE_BYTES_FROM_80971) TX_DB[the_coinbase_tx.hash()] = the_coinbase_tx # now create a Tx that spends the coinbase compressed = False exponent_2 = int("137f3276686959c82b454eea6eefc9ab1b9e45bd4636fb9320262e114e321da1", 16) bitcoin_address_2 = public_pair_to_bitcoin_address( ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, exponent_2), compressed=compressed ) self.assertEqual("12WivmEn8AUth6x6U8HuJuXHaJzDw3gHNZ", bitcoin_address_2) coins_from = [(the_coinbase_tx.hash(), 0, the_coinbase_tx.txs_out[0])] coins_to = [(int(50 * 1e8), bitcoin_address_2)] unsigned_coinbase_spend_tx = standard_tx(coins_from, coins_to) solver = build_hash160_lookup([exponent]) coinbase_spend_tx = unsigned_coinbase_spend_tx.sign(solver) # now check that it validates self.assertEqual(coinbase_spend_tx.bad_signature_count(), 0) TX_DB[coinbase_spend_tx.hash()] = coinbase_spend_tx ## now try to respend from priv_key_2 to priv_key_3 compressed = True exponent_3 = int("f8d39b8ecd0e1b6fee5a340519f239097569d7a403a50bb14fb2f04eff8db0ff", 16) bitcoin_address_3 = public_pair_to_bitcoin_address( ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, exponent_3), compressed=compressed ) self.assertEqual("13zzEHPCH2WUZJzANymow3ZrxcZ8iFBrY5", bitcoin_address_3) coins_from = [(coinbase_spend_tx.hash(), 0, coinbase_spend_tx.txs_out[0])] unsigned_spend_tx = standard_tx(coins_from, [(int(50 * 1e8), bitcoin_address_3)]) solver.update(build_hash160_lookup([exponent_2])) spend_tx = unsigned_spend_tx.sign(solver) # now check that it validates self.assertEqual(spend_tx.bad_signature_count(), 0)
def test_build_spends(self): # create a coinbase Tx where we know the public & private key exponent = wif_to_secret_exponent( "5JMys7YfK72cRVTrbwkq5paxU7vgkMypB55KyXEtN5uSnjV7K8Y") compressed = False public_key_sec = public_pair_to_sec( ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, exponent), compressed=compressed) the_coinbase_tx = Tx.coinbase_tx(public_key_sec, int(50 * 1e8), COINBASE_BYTES_FROM_80971) # now create a Tx that spends the coinbase compressed = False exponent_2 = int( "137f3276686959c82b454eea6eefc9ab1b9e45bd4636fb9320262e114e321da1", 16) bitcoin_address_2 = public_pair_to_bitcoin_address( ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, exponent_2), compressed=compressed) self.assertEqual("12WivmEn8AUth6x6U8HuJuXHaJzDw3gHNZ", bitcoin_address_2) TX_DB = dict((tx.hash(), tx) for tx in [the_coinbase_tx]) coins_from = [(the_coinbase_tx.hash(), 0)] coins_to = [(int(50 * 1e8), bitcoin_address_2)] coinbase_spend_tx = Tx.standard_tx(coins_from, coins_to, TX_DB, [exponent]) coinbase_spend_tx.validate(TX_DB) ## now try to respend from priv_key_2 to priv_key_3 compressed = True exponent_3 = int( "f8d39b8ecd0e1b6fee5a340519f239097569d7a403a50bb14fb2f04eff8db0ff", 16) bitcoin_address_3 = public_pair_to_bitcoin_address( ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, exponent_3), compressed=compressed) self.assertEqual("13zzEHPCH2WUZJzANymow3ZrxcZ8iFBrY5", bitcoin_address_3) TX_DB = dict((tx.hash(), tx) for tx in [coinbase_spend_tx]) spend_tx = Tx.standard_tx([(coinbase_spend_tx.hash(), 0)], [(int(50 * 1e8), bitcoin_address_3)], TX_DB, [exponent_2]) spend_tx.validate(TX_DB)
def test_build_spends(self): # first, here is the tx database TX_DB = {} def tx_out_for_hash_index_f(tx_hash, tx_out_idx): tx = TX_DB.get(tx_hash) return tx.txs_out[tx_out_idx] # create a coinbase Tx where we know the public & private key exponent = wif_to_secret_exponent("5JMys7YfK72cRVTrbwkq5paxU7vgkMypB55KyXEtN5uSnjV7K8Y") compressed = False public_key_sec = public_pair_to_sec(ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, exponent), compressed=compressed) the_coinbase_tx = Tx.coinbase_tx(public_key_sec, int(50 * 1e8), COINBASE_BYTES_FROM_80971) TX_DB[the_coinbase_tx.hash()] = the_coinbase_tx # now create a Tx that spends the coinbase compressed = False exponent_2 = int("137f3276686959c82b454eea6eefc9ab1b9e45bd4636fb9320262e114e321da1", 16) bitcoin_address_2 = public_pair_to_bitcoin_address( ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, exponent_2), compressed=compressed) self.assertEqual("12WivmEn8AUth6x6U8HuJuXHaJzDw3gHNZ", bitcoin_address_2) coins_from = [(the_coinbase_tx.hash(), 0, the_coinbase_tx.txs_out[0])] coins_to = [(int(50 * 1e8), bitcoin_address_2)] unsigned_coinbase_spend_tx = UnsignedTx.standard_tx(coins_from, coins_to) solver = SecretExponentSolver([exponent]) coinbase_spend_tx = unsigned_coinbase_spend_tx.sign(solver) # now check that it validates coinbase_spend_tx.validate(tx_out_for_hash_index_f) TX_DB[coinbase_spend_tx.hash()] = coinbase_spend_tx ## now try to respend from priv_key_2 to priv_key_3 compressed = True exponent_3 = int("f8d39b8ecd0e1b6fee5a340519f239097569d7a403a50bb14fb2f04eff8db0ff", 16) bitcoin_address_3 = public_pair_to_bitcoin_address( ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, exponent_3), compressed=compressed) self.assertEqual("13zzEHPCH2WUZJzANymow3ZrxcZ8iFBrY5", bitcoin_address_3) unsigned_spend_tx = UnsignedTx.standard_tx([(coinbase_spend_tx.hash(), 0, coinbase_spend_tx.txs_out[0])], [(int(50 * 1e8), bitcoin_address_3)]) solver.add_secret_exponents([exponent_2]) spend_tx = unsigned_spend_tx.sign(solver) # now check that it validates spend_tx.validate(tx_out_for_hash_index_f)
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))
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))
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))
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))
def test_signature_hash(self): compressed = False exponent_2 = int( "137f3276686959c82b454eea6eefc9ab1b9e45bd4636fb9320262e114e321da1", 16) bitcoin_address_2 = public_pair_to_bitcoin_address( ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, exponent_2), compressed=compressed) exponent = wif_to_secret_exponent( "5JMys7YfK72cRVTrbwkq5paxU7vgkMypB55KyXEtN5uSnjV7K8Y") public_key_sec = public_pair_to_sec( ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, exponent), compressed=compressed) the_coinbase_tx = Tx.coinbase_tx(public_key_sec, int(50 * 1e8), COINBASE_BYTES_FROM_80971) coins_from = [(the_coinbase_tx.hash(), 0, the_coinbase_tx.txs_out[0])] coins_to = [(int(50 * 1e8), bitcoin_address_2)] unsigned_coinbase_spend_tx = standard_tx(coins_from, coins_to) tx_out_script_to_check = the_coinbase_tx.txs_out[0].script idx = 0 actual_hash = unsigned_coinbase_spend_tx.signature_hash( tx_out_script_to_check, idx, hash_type=SIGHASH_ALL) self.assertEqual( actual_hash, 29819170155392455064899446505816569230970401928540834591675173488544269166940 )
def __init__(self, **kwargs): """Create an address for this color <color_set> and index <index> with the pycoin_wallet <pycoin_wallet> and on testnet or not <testnet> The address record returned for the same variables will be the same every time, hence "deterministic". """ super(BIP0032AddressRecord, self).__init__(**kwargs) pycoin_wallet = kwargs.get('pycoin_wallet') color_string = hashlib.sha256(self.color_set.get_earliest()).digest() self.index = kwargs.get('index') # use the hash of the color string to get the subkey we need while len(color_string): # XXX 'number' was to large, have a feeling this will break compatibility number = int(color_string[:4].encode('hex'), 16) & (0x80000000 - 0x1) pycoin_wallet = pycoin_wallet.subkey(i=number, as_private=True) color_string = color_string[4:] # now get the nth address in this wallet pycoin_wallet = pycoin_wallet.subkey(i=self.index, as_private=True) self.rawPrivKey = pycoin_wallet.secret_exponent() self.publicPoint = BasePoint * self.rawPrivKey self.address = public_pair_to_bitcoin_address( self.publicPoint.pair(), compressed=False, address_prefix=self.prefix)
def pubkey_to_address(pubkey_hex): sec = binascii.unhexlify(pubkey_hex) compressed = encoding.is_sec_compressed(sec) public_pair = encoding.sec_to_public_pair(sec) address_prefix = b'\x6f' if config.TESTNET else b'\x00' return encoding.public_pair_to_bitcoin_address( public_pair, compressed=compressed, address_prefix=address_prefix)
def __init__(self, **kwargs): """Create an address for this color <color_set> and index <index> with the pycoin_wallet <pycoin_wallet> and on testnet or not <testnet> The address record returned for the same variables will be the same every time, hence "deterministic". """ super(BIP0032AddressRecord, self).__init__(**kwargs) pycoin_wallet = kwargs.get('pycoin_wallet') color_string = hashlib.sha256(self.color_set.get_earliest()).digest() self.index = kwargs.get('index') # use the hash of the color string to get the subkey we need while len(color_string): # XXX 'number' was to large, have a feeling this will break compatibility number = int(color_string[:4].encode('hex'), 16) & (0x80000000-0x1) pycoin_wallet = pycoin_wallet.subkey(i=number, as_private=True) color_string = color_string[4:] # now get the nth address in this wallet pycoin_wallet = pycoin_wallet.subkey(i=self.index, as_private=True) self.rawPrivKey = pycoin_wallet.secret_exponent() self.publicPoint = BasePoint * self.rawPrivKey self.address = public_pair_to_bitcoin_address( self.publicPoint.pair(), compressed=False, address_prefix=self.prefix )
def importprivkey(self, wif): secret_exponent = wif_to_secret_exponent(wif) public_pair = ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, secret_exponent) address = public_pair_to_bitcoin_address(public_pair) secret_exponent = hex(secret_exponent)[2:].encode('utf8') self.insertaddress(address, secret_exponent) return address
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))
def importprivkey(self, wif): secret_exponent = wif_to_secret_exponent(wif) public_pair = ecdsa.public_pair_for_secret_exponent( ecdsa.generator_secp256k1, secret_exponent) address = public_pair_to_bitcoin_address(public_pair) secret_exponent = hex(secret_exponent)[2:].encode('utf8') self.insertaddress(address, secret_exponent) return address
def add_sec_annotations(a1, data, address_prefix): pair = sec_to_public_pair(data) is_compressed = is_sec_compressed(data) a1.append( "SEC for %scompressed %s" % ("" if is_compressed else "un", public_pair_to_bitcoin_address( pair, compressed=is_compressed, address_prefix=address_prefix)))
def test_build_spends(self): # create a coinbase Tx where we know the public & private key exponent = wif_to_secret_exponent("5JMys7YfK72cRVTrbwkq5paxU7vgkMypB55KyXEtN5uSnjV7K8Y") compressed = False public_key_sec = public_pair_to_sec(ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, exponent), compressed=compressed) the_coinbase_tx = Tx.coinbase_tx(public_key_sec, int(50 * 1e8), COINBASE_BYTES_FROM_80971) # now create a Tx that spends the coinbase compressed = False exponent_2 = int("137f3276686959c82b454eea6eefc9ab1b9e45bd4636fb9320262e114e321da1", 16) bitcoin_address_2 = public_pair_to_bitcoin_address( ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, exponent_2), compressed=compressed) self.assertEqual("12WivmEn8AUth6x6U8HuJuXHaJzDw3gHNZ", bitcoin_address_2) TX_DB = dict((tx.hash(), tx) for tx in [the_coinbase_tx]) coins_from = [(the_coinbase_tx.hash(), 0)] coins_to = [(int(50 * 1e8), bitcoin_address_2)] coinbase_spend_tx = Tx.standard_tx(coins_from, coins_to, TX_DB, [exponent]) coinbase_spend_tx.validate(TX_DB) ## now try to respend from priv_key_2 to priv_key_3 compressed = True exponent_3 = int("f8d39b8ecd0e1b6fee5a340519f239097569d7a403a50bb14fb2f04eff8db0ff", 16) bitcoin_address_3 = public_pair_to_bitcoin_address( ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, exponent_3), compressed=compressed) self.assertEqual("13zzEHPCH2WUZJzANymow3ZrxcZ8iFBrY5", bitcoin_address_3) TX_DB = dict((tx.hash(), tx) for tx in [coinbase_spend_tx]) spend_tx = Tx.standard_tx([(coinbase_spend_tx.hash(), 0)], [(int(50 * 1e8), bitcoin_address_3)], TX_DB, [exponent_2]) spend_tx.validate(TX_DB)
def parse_sig(script_hex): """Takes a hex string of the script signature and returns the corresponding user obj Its in the format: [3a05e435... 027efd7...] where: [Signature, Sec_pubkey] """ pubkey_hex = script_hex.split(' ')[1] sec = sec_to_public_pair(a2b_hex(pubkey_hex)) addr = public_pair_to_bitcoin_address(sec, address_prefix=NETWORK) return Username(addr)
def do_test(as_public_pair, as_sec, is_compressed, as_hash160_sec, as_bitcoin_address): self.assertEqual(encoding.sec_to_public_pair(as_sec), as_public_pair) self.assertEqual(encoding.public_pair_to_sec(as_public_pair, compressed=is_compressed), as_sec) self.assertEqual(encoding.is_sec_compressed(as_sec), is_compressed) self.assertEqual(encoding.public_pair_to_hash160_sec(as_public_pair, compressed=is_compressed), as_hash160_sec) self.assertEqual(encoding.hash160_sec_to_bitcoin_address(as_hash160_sec), as_bitcoin_address) self.assertEqual(encoding.public_pair_to_bitcoin_address(as_public_pair, compressed=is_compressed), as_bitcoin_address) self.assertTrue(encoding.is_valid_bitcoin_address(as_bitcoin_address)) bad_address = as_bitcoin_address[:17] + chr(ord(as_bitcoin_address[17]) + 1) + as_bitcoin_address[18:] self.assertFalse(encoding.is_valid_bitcoin_address(bad_address))
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))
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))
def address_from_pubkey(pubkey, netcode="BTC"): """ Get bitcoin address from given public key. Args: pubkey (str): Hex encoded 33Byte compressed public key netcode (str): Netcode for resulting bitcoin address. Return: str: Bitcoin address """ prefix = networks.address_prefix_for_netcode(netcode) public_pair = encoding.sec_to_public_pair(h2b(pubkey)) return encoding.public_pair_to_bitcoin_address(public_pair, address_prefix=prefix)
def add_signature_annotations(annotations, signature_blob, signature_for_hash_type_f, output_script): sig_pair, sig_type = parse_signature_blob(signature_blob) annotations.append("r: {0:#066x}".format(sig_pair[0])) annotations.append("s: {0:#066x}".format(sig_pair[1])) sig_hash = signature_for_hash_type_f(sig_type, output_script) annotations.append("z: {0:#066x}".format(sig_hash)) annotations.append("signature type %s" % sighash_type_to_string(sig_type)) addresses = [] pairs = possible_public_pairs_for_signature(generator_secp256k1, sig_hash, sig_pair) for pair in pairs: for comp in (True, False): address = public_pair_to_bitcoin_address(pair, compressed=comp, address_prefix=b'\0') addresses.append(address) annotations.append(" sig for %s" % " ".join(addresses))
def bitcoin_address_for_script(self, is_test=False): try: r = self.match_script_to_templates() if len(r) != 1 or len(r[0]) != 2: return None if r[0][0] == opcodes.OP_PUBKEYHASH: return hash160_sec_to_bitcoin_address(r[0][1], is_test=is_test) if r[0][0] == opcodes.OP_PUBKEY: sec = r[0][1] return public_pair_to_bitcoin_address( sec_to_public_pair(sec), compressed=is_sec_compressed(sec), is_test=is_test) except SolvingError: pass return None
def msg_verify(args, parser): message_hash = get_message_hash(args) try: pair, is_compressed = pair_for_message(args.signature, msg_hash=message_hash, netcode=args.network) except encoding.EncodingError: pass prefix = address_prefix_for_netcode(args.network) ta = encoding.public_pair_to_bitcoin_address(pair, compressed=is_compressed, address_prefix=prefix) if args.address: if ta == args.address: print("signature ok") return 0 else: print("bad signature, matches %s" % ta) return 1 else: print(ta)
def __init__(self, **kwargs): """Create a LooseAddressRecord for a given wallet <model>, color <color_set> and address <address_data>. Also let the constructor know whether it's on <testnet> (optional). <address_data> is the privKey in base58 format """ super(LooseAddressRecord, self).__init__(**kwargs) bin_privkey = a2b_hashed_base58(kwargs['address_data']) key_type = bin_privkey[0] if key_type != self.prefix: raise InvalidAddressError self.rawPrivKey = from_bytes_32(bin_privkey[1:]) self.publicPoint = BasePoint * self.rawPrivKey self.address = public_pair_to_bitcoin_address( self.publicPoint.pair(), compressed=False, is_test=self.testnet)
def test_signature_hash(self): compressed = False exponent_2 = int("137f3276686959c82b454eea6eefc9ab1b9e45bd4636fb9320262e114e321da1", 16) bitcoin_address_2 = public_pair_to_bitcoin_address(exponent_2 * secp256k1_generator, compressed=compressed) exponent = wif_to_secret_exponent("5JMys7YfK72cRVTrbwkq5paxU7vgkMypB55KyXEtN5uSnjV7K8Y") public_key_sec = public_pair_to_sec(exponent * secp256k1_generator, compressed=compressed) the_coinbase_tx = Tx.coinbase_tx(public_key_sec, int(50 * 1e8), COINBASE_BYTES_FROM_80971) coins_from = [(the_coinbase_tx.hash(), 0, the_coinbase_tx.txs_out[0])] coins_to = [(int(50 * 1e8), bitcoin_address_2)] unsigned_coinbase_spend_tx = standard_tx(coins_from, coins_to) tx_out_script_to_check = the_coinbase_tx.txs_out[0].script idx = 0 actual_hash = unsigned_coinbase_spend_tx.signature_hash(tx_out_script_to_check, idx, hash_type=SIGHASH_ALL) self.assertEqual(actual_hash, 29819170155392455064899446505816569230970401928540834591675173488544269166940)
def __init__(self, **kwargs): """Create a LooseAddressRecord for a given wallet <model>, color <color_set> and address <address_data>. Also let the constructor know whether it's on <testnet> (optional). <address_data> is the privKey in base58 format """ super(LooseAddressRecord, self).__init__(**kwargs) bin_privkey = a2b_hashed_base58(kwargs['address_data']) key_type = bin_privkey[0] if key_type != self.prefix: raise InvalidAddressError self.rawPrivKey = from_bytes_32(bin_privkey[1:]) self.publicPoint = BasePoint * self.rawPrivKey self.address = public_pair_to_bitcoin_address(self.publicPoint.pair(), compressed=False, is_test=self.testnet)
def __call__(self, tx_out_script, signature_hash, signature_type): """Figure out how to create a signature for the incoming transaction, and sign it. tx_out_script: the tx_out script that needs to be "solved" signature_hash: the bignum hash value of the new transaction reassigning the coins signature_type: always SIGHASH_ALL (1) """ if signature_hash == 0: raise SolvingError("signature_hash can't be 0") tx_script = TxScript(tx_out_script) opcode_value_list = tx_script.match_script_to_templates() ba = bytearray() compressed = True for opcode, v in opcode_value_list: if opcode == opcodes.OP_PUBKEY: public_pair = sec_to_public_pair(v) bitcoin_address = public_pair_to_bitcoin_address( public_pair, compressed=compressed) elif opcode == opcodes.OP_PUBKEYHASH: bitcoin_address = hash160_sec_to_bitcoin_address(v) else: raise SolvingError("can't determine how to sign this script") secret_exponent = self.wallet.getsecretexponent(bitcoin_address) r, s = ecdsa.sign(ecdsa.generator_secp256k1, secret_exponent, signature_hash) sig = der.sigencode_der(r, s) + bytes_from_int(signature_type) ba += tools.compile(binascii.hexlify(sig).decode("utf8")) if opcode == opcodes.OP_PUBKEYHASH: public_pair = ecdsa.public_pair_for_secret_exponent( ecdsa.generator_secp256k1, secret_exponent) ba += tools.compile( binascii.hexlify( public_pair_to_sec( public_pair, compressed=compressed)).decode("utf8")) return bytes(ba)
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
def __init__(self, **kwargs): """Create an address for this color <color_set> and index <index> with the master key <master_key>. The address record returned for the same three variables will be the same every time, hence "deterministic". """ super(DeterministicAddressRecord, self).__init__(**kwargs) if len(self.color_set.get_data()) == 0: color_string = "genesis block" else: color_string = self.color_set.get_hash_string() self.index = kwargs.get('index') h = hmac.new(str(kwargs['master_key']), "%s|%s" % (color_string, self.index), hashlib.sha256) string = h.digest() self.rawPrivKey = from_bytes_32(string) self.publicPoint = BasePoint * self.rawPrivKey self.address = public_pair_to_bitcoin_address(self.publicPoint.pair(), compressed=False, is_test=self.testnet)
def __call__(self, tx_out_script, signature_hash, signature_type): """Figure out how to create a signature for the incoming transaction, and sign it. tx_out_script: the tx_out script that needs to be "solved" signature_hash: the bignum hash value of the new transaction reassigning the coins signature_type: always SIGHASH_ALL (1) """ if signature_hash == 0: raise SolvingError("signature_hash can't be 0") tx_script = TxScript(tx_out_script) opcode_value_list = tx_script.match_script_to_templates() ba = bytearray() compressed = True for opcode, v in opcode_value_list: if opcode == opcodes.OP_PUBKEY: public_pair = sec_to_public_pair(v) bitcoin_address = public_pair_to_bitcoin_address(public_pair, compressed=compressed) elif opcode == opcodes.OP_PUBKEYHASH: bitcoin_address = hash160_sec_to_bitcoin_address(v) else: raise SolvingError("can't determine how to sign this script") secret_exponent = self.wallet.getsecretexponent(bitcoin_address) r, s = ecdsa.sign(ecdsa.generator_secp256k1, secret_exponent, signature_hash) sig = der.sigencode_der(r, s) + bytes_from_int(signature_type) ba += tools.compile(binascii.hexlify(sig).decode("utf8")) if opcode == opcodes.OP_PUBKEYHASH: public_pair = ecdsa.public_pair_for_secret_exponent(ecdsa.generator_secp256k1, secret_exponent) ba += tools.compile( binascii.hexlify(public_pair_to_sec(public_pair, compressed=compressed)).decode("utf8") ) return bytes(ba)
def pubkey_to_address(pubkey_hex): sec = binascii.unhexlify(pubkey_hex) compressed = encoding.is_sec_compressed(sec) public_pair = encoding.sec_to_public_pair(sec) address_prefix = b'\x6f' if config.TESTNET else b'\x00' return encoding.public_pair_to_bitcoin_address(public_pair, compressed=compressed, address_prefix=address_prefix)
def get_address_of_pubkey(pubkey): public_pair=encoding.sec_to_public_pair(encoding.binascii.unhexlify(pubkey)) return encoding.public_pair_to_bitcoin_address(public_pair)
#!/usr/bin/env python import hashlib import struct 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.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
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') #print("Private key hexlify: ", hexlify(cec_key.get_privkey())) print("Public key hex: ", bitcoin.core.b2x(cec_key.get_pubkey())) cec_key.set_compressed(False) print(" uncompressed: ", bitcoin.core.b2x(cec_key.get_pubkey())) addr_compressed = encoding.public_pair_to_bitcoin_address( pubkey_pair, True, address_prefix=my_pubaddr_prefix) addr_uncompressed = encoding.public_pair_to_bitcoin_address( pubkey_pair, False, address_prefix=my_pubaddr_prefix) # convert public key pair to public key to address pubkey_hashed = encoding.public_pair_to_hash160_sec(pubkey_pair, True) print("Public key hash160: ", bitcoin.core.b2x(pubkey_hashed)) pubkey_addr = encoding.hash160_sec_to_bitcoin_address( pubkey_hashed, address_prefix=my_pubaddr_prefix) assert (addr_compressed == pubkey_addr) pubkey_hashed = encoding.public_pair_to_hash160_sec(pubkey_pair, False) print(" uncompressed: ", bitcoin.core.b2x(pubkey_hashed)) pubkey_addr = encoding.hash160_sec_to_bitcoin_address( pubkey_hashed, address_prefix=my_pubaddr_prefix) assert (addr_uncompressed == pubkey_addr)
def pubkey_to_address(pubkey_hex): sec = binascii.unhexlify(pubkey_hex) compressed = encoding.is_sec_compressed(sec) public_pair = encoding.sec_to_public_pair(sec) return encoding.public_pair_to_bitcoin_address(public_pair, compressed=compressed)
#my_netcode = "mainnet" bitcoin.SelectParams(my_netcode) my_params = bitcoin.params my_privkey_prefix = bytes(bytearray([my_params.BASE58_PREFIXES['SECRET_KEY']])) my_pubaddr_prefix = bytes(bytearray([my_params.BASE58_PREFIXES['PUBKEY_ADDR']])) # Create the (in)famous correct brainwallet secret key. h = hashlib.sha256(b'correct horse battery staple').digest() seckey = CBitcoinSecret.from_secret_bytes(h) cec_key = CECKey() cec_key.set_secretbytes(h) print("Secret key hex: ", seckey.hex()); btc_addr = encoding.public_pair_to_bitcoin_address(cec_key.get_pubkey(), address_prefix=my_pubaddr_prefix) print("Bitcoin address: ", btc_addr) # Create a redeemScript, with public key and checksig op code (0xac) # Similar to a scriptPubKey the redeemScript must be satisfied for the funds to be spent. txin_redeemScript = CScript([seckey.pub, OP_CHECKSIG]) print("Public key of address #", seckey.pub.hex()) # 0x21 + secret.pub + OP_CHECKSIG (0x87) print("Tx-in Redeem Script: ", b2x(txin_redeemScript)) # Create the magic P2SH scriptPubKey format from that redeemScript. You should # look at the CScript.to_p2sh_scriptPubKey() function in bitcoin.core.script to # understand what's happening, as well as read BIP16: # https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki txin_scriptPubKey = txin_redeemScript.to_p2sh_scriptPubKey() print("Redeem script hash160 #", b2x(bitcoin.core.Hash160(txin_redeemScript)))
def address(self): """Returns the well-known base58 bitcoin address for this PubKey""" return public_pair_to_bitcoin_address((self.x(), self.y()))
#ensure there is enough money to do it ... funding_amount = Decimal(options.funding_amount) total = funding_amount * code_count total_s = int(total * s_per_b) print "Checking that a total of %s BTC (%s satoshis) is available ..." % (total, total_s) #which means first taking the WIF, turn to secret exponent, ask for public_pair and get BTC address from public pair ... then ask blockchain service about that address. satoshis = 0 coin_sources = [] secret_exponent = None bitcoin_address_compressed = None try: secret_exponent = encoding.wif_to_secret_exponent(options.funding_source) public_pair = ecdsa.public_pair_for_secret_exponent(secp256k1.generator_secp256k1, secret_exponent) bitcoin_address_compressed = encoding.public_pair_to_bitcoin_address(public_pair, compressed=True) except: print "Hrm something went wrong in trying to figure out BTC address from WIF %s" % (options.funding_source) sys.exit() try: if not options.forced_tx_source: coin_sources = blockchain_info.coin_sources_for_address(bitcoin_address_compressed) else: #forced args should combine all the info we need to run the code below ... so, value in satoshis, script, tx_hash and tx_output_n #value is in satoshis. tx_output_n does appear to start at zero after all. #u can find a tx outputs info by putting the tx in here: https://blockchain.info/rawtx/8684f9ea9f35953d0235cd4f5c73485dcf0eeb4cada6d2f657b63bea1e425178?scripts=true #eg args below ... wanted to redo something that used output # 0 of this tx as a source: 8684f9ea9f35953d0235cd4f5c73485dcf0eeb4cada6d2f657b63bea1e425178, soooo from the https://blockchain.info/rawtx/8684f9ea9f35953d0235cd4f5c73485dcf0eeb4cada6d2f657b63bea1e425178?scripts=true link we got: #8684f9ea9f35953d0235cd4f5c73485dcf0eeb4cada6d2f657b63bea1e425178,0,500000,76a91439d61ff876886683142acf9b0235ea0bcc3ecf8788ac hash, tx_output_n, s_value, script = options.forced_tx_source.split(',') #the hash we get from rawtx will be the reverse byte order of the tx_hash that the unspent outputs thing that the pycoin normally uses (http://blockchain.info/unspent?active=%s ) reports (why?? only Satoshi knows.)
def wif2address(wif): secret_exponent = wif_to_secret_exponent(wif) public_pair = public_pair_for_secret_exponent(generator_secp256k1, secret_exponent) return public_pair_to_bitcoin_address(public_pair, False)
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))
import hashlib import struct import unittest from pycoin.ecdsa.secp256k1 import secp256k1_generator 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(i * secp256k1_generator) 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
#!/usr/bin/env python import hashlib import struct 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
#!/usr/bin/env python import hashlib import struct 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.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
print(" y as hex: ", hex(public_key[1])) #compressed_indicator_1 = '02' if (public_key_y % 2) == 0 else '03' compressed_indicator = True if (public_key_y % 2) == 0 else False print("Public key y parity: ", 'even' if compressed_indicator else 'odd') assert(compressed_indicator != my_key._use_uncompressed) print("Public key hex: ", my_key.sec_as_hex()) print(" uncompressed: ", my_key.sec_as_hex(use_uncompressed=True)) assert(my_key.sec_as_hex() == bitcoin.core.b2x(my_key.sec())) print("Public key hash160: ", b2h(my_key.hash160())) print(" uncompressed: ", b2h(my_key.hash160(use_uncompressed=True))) #print("Bitcoin Address : ", my_key.address()) addr_compressed = encoding.public_pair_to_bitcoin_address(public_key, True, my_addr_prefix) addr_uncompressed = encoding.public_pair_to_bitcoin_address(public_key, False, my_addr_prefix) print("Bitcoin Address: ", addr_compressed) print(" uncompressed: ", addr_uncompressed) assert(encoding.is_valid_bitcoin_address(addr_compressed, my_addr_prefix)) assert(encoding.is_valid_bitcoin_address(addr_uncompressed, my_addr_prefix)) assert(my_key.address() == addr_compressed) pubkey_bytes = encoding.public_pair_to_sec(public_key, True); assert(my_key.sec_as_hex() == b2h(pubkey_bytes)) pubkey_bytes = encoding.public_pair_to_sec(public_key, False); assert(my_key.sec_as_hex(use_uncompressed=True) == b2h(pubkey_bytes)) print()
def add_sec_annotations(a1, data, address_prefix): pair = sec_to_public_pair(data) is_compressed = is_sec_compressed(data) a1.append("SEC for %scompressed %s" % ( "" if is_compressed else "un", public_pair_to_bitcoin_address( pair, compressed=is_compressed, address_prefix=address_prefix)))