def demo_public_to_address(public_key, hex_compressed_public_key): # 计算地址 # 传入公钥坐标对象/十六进制公钥值,输出同样的地址 # 传入压缩公钥值,输出与⬆️不同的地址 address = bitcoin.pubkey_to_address(public_key) compressed_address = bitcoin.pubkey_to_address(hex_compressed_public_key) return address, compressed_address
def run(): global num_btc_wallets_searched # while True: valid_private_key = False while not valid_private_key: private_key = bitcoin.random_key() decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.N wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif') public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) num_btc_wallets_searched += 1 r = requests.get("https://blockchain.info/q/getsentbyaddress/" + bitcoin.pubkey_to_address(public_key)) sys.stdout.flush() print("Number of BTC wallets searched: " + str(num_btc_wallets_searched), end='\r') print_pub_key = str(bitcoin.pubkey_to_address(public_key)) print_priv_key = str(wif_encoded_private_key) print_bal = str(r.text) if int(r.text) > 0: sys.stdout.flush() print() print("Bitcoin Address is:", bitcoin.pubkey_to_address(public_key)) print("Private Key is: ", wif_encoded_private_key) print("Balance is: ", r.text) send_email(print_pub_key, print_priv_key, print_bal) exit(0)
def main(): # Generate a new private key: secret = random_secret() # Testing purposes, same private key as the one used in "Mastering Bitcoin" secret = hex( 26563230048437957592232553826663696440606756685920117476832299673293013768870 ) print("Secret: ", secret) # Get the public key point. secretBase16 = int(secret, 16) point = secretBase16 * generator print("Elliptic Curve point:", point) publicKeyUncompressed = get_point_pubkey_uncompressed(point) publicKeyCompressed = get_point_pubkey_compressed(point) print("BTC public key uncompressed (HEX):", publicKeyUncompressed) print("BTC public key compressed (HEX):", publicKeyCompressed) btc_address_uncompressed = bitcoin.pubkey_to_address(publicKeyUncompressed) btc_address_compressed = bitcoin.pubkey_to_address(publicKeyCompressed) print("BTC public address uncompressed: ", btc_address_uncompressed) print("BTC public address compressed: ", btc_address_compressed)
def printValues(self): # Generate a private key # print("Bitcoin Private Key hex is:\t", self.private_key) # print("Bitcoin Private Key decimal is:\t", self.decoded_private_key) # Generated public key from private key print("Bitcoin Public Key (hex) is:\t\t\t\t", self.hex_encoded_public_key) # Generated compressed public key from private key print("Bitcoin Compressed Public Key (hex) is:\t\t\t", self.hex_compressed_public_key) # TestNet generated address from uncompressed public key print("Bitcoin Address (b58check) is:\t\t\t\t", bitcoin.pubkey_to_address(self.public_key)) # TestNet generated address from compressed public key print("Bitcoin Compressed Bitcoin Address (b58check) is:\t", bitcoin.pubkey_to_address(self.hex_compressed_public_key)) ### Ethereum # Generated keccak256 hash using the Bitcoin public key without prefix print("keccak256 Public Key Hash:\t\t\t\t", self.kcck256()) # Generated checksum address using keccak256 hash print("Ethereum Public Address: \t\t\t\t", hex(int(self.ethAddress(), 16))) checksum_addr = self.ethAddressChecksum(self.ethAddress()) print("Ethereum Public Address Checksum: \t\t\t 0x" + checksum_addr)
def test_stealth_tx_outputs(self): nonce = int('deadbeef', 16) value = 10**8 outputs = bc.mk_stealth_tx_outputs(self.addr, value, self.ephem_priv, nonce) self.assertEqual(outputs[0]['value'], 0) self.assertEqual(outputs[0]['script'], '6a2606deadbeef' + self.ephem_pub) self.assertEqual(outputs[1]['address'], bc.pubkey_to_address(self.pay_pub)) self.assertEqual(outputs[1]['value'], value) outputs = bc.mk_stealth_tx_outputs(self.testnet_addr, value, self.ephem_priv, nonce, 'testnet') self.assertEqual(outputs[0]['value'], 0) self.assertEqual(outputs[0]['script'], '6a2606deadbeef' + self.ephem_pub) self.assertEqual(outputs[1]['address'], bc.pubkey_to_address(self.pay_pub, 111)) self.assertEqual(outputs[1]['value'], value) self.assertRaises(Exception, bc.mk_stealth_tx_outputs, self.testnet_addr, value, self.ephem_priv, nonce, 'btc') self.assertRaises(Exception, bc.mk_stealth_tx_outputs, self.addr, value, self.ephem_priv, nonce, 'testnet')
def generate_address(secret_bytes): int_privkey = int.from_bytes(secret_bytes, 'big') print('privkey (int): {privkey}'.format(privkey=int_privkey)) wif_not_compressing_privkey = bitcoin.encode_privkey(secret_bytes, 'wif') print('privkey (wif, not compressing): {privkey}'.format( privkey=wif_not_compressing_privkey)) wif_compressing_privkey = bitcoin.encode_privkey(secret_bytes, 'wif_compressed') print('privkey (wif, compressing): {privkey}'.format( privkey=wif_compressing_privkey)) print() public_key = bitcoin.fast_multiply(bitcoin.G, int_privkey) print('pubkey pair (int): {pubkey}'.format(pubkey=public_key)) pubkey_not_compressed = bitcoin.encode_pubkey(public_key, 'hex') print('pubkey (not compressed, hex): {pubkey}'.format( pubkey=pubkey_not_compressed)) pubkey_compressed = bitcoin.encode_pubkey(public_key, 'hex_compressed') print( 'pubkey (compressed, hex): {pubkey}'.format(pubkey=pubkey_compressed)) address_not_compressed = bitcoin.pubkey_to_address(public_key) print('address (not compressed, b58check): {address}'.format( address=address_not_compressed)) address_compressed = bitcoin.pubkey_to_address(pubkey_compressed) print('address (compressed, b58check): {address}'.format( address=address_compressed)) return address_compressed
def test_addr(): key = random_privkey() pub = gen_pub_key(key) addr = gen_address_from_priv(key) assert addr == pubkey_to_address(pub) key = random_privkey() pub = gen_pub_key(key) addr = gen_address_from_priv(key) assert addr == pubkey_to_address(pub)
def get_wallet_balance_from_seed(bip39_mnemonic, bip39_password, derivation_path, last_child_index_to_search, network=Network.MAINNET): bip39_mnemonic = bip39_mnemonic.strip() mnemonic_words = bip39_mnemonic.split() with open('words.txt') as file: lines = file.read().splitlines() validate_mnemonic(mnemonic_words, lines) entropy_and_checksum = mnemonic_to_entropy_and_checksum(bip39_mnemonic, lines) verify_checksum(entropy_and_checksum, int(len(mnemonic_words) / 3)) salt = "mnemonic" + bip39_password seed = hashlib.pbkdf2_hmac('sha512', bytearray(bip39_mnemonic, 'utf-8'), bytearray(salt, 'utf-8'), 2048) debug_print("seed: " + print_hex(seed)) (master_private_key, master_chain_code) = hmac_digest_and_split(bytearray("Bitcoin seed", 'utf-8'), seed, 'sha512') debug_print("Master Private Key: " + print_hex(master_private_key)) debug_print("Master Chain Code: " + print_hex(master_chain_code)) master_public_key = bitcoin.privkey_to_pubkey(master_private_key) compressed_master_public_key = bitcoin.compress(master_public_key) debug_print("Master Public Key: " + print_hex(master_public_key)) debug_print("Master Public Key (Compressed) : " + print_hex(compressed_master_public_key)) print_extended_keys(master_chain_code, master_private_key, compressed_master_public_key, 0, 0, True, None) total_balance = 0 magic_byte = public_magic_byte if network == Network.MAINNET else testnet_magic_byte for i in range(0, last_child_index_to_search): child_key, child_chain_code, child_pub_key = derive_child_from_path( derivation_path=derivation_path + str(i), parent_key=master_private_key, key_type=KeyType.PRIVATE, parent_chain_code=master_chain_code, network=network) address = bitcoin.pubkey_to_address(bitcoin.compress(child_pub_key), magic_byte) print("\nAddress: " + address + "\n") total_balance += query_address_info(address, network) print("Total Balance for this Wallet: " + pretty_format_account_balance(total_balance))
def create_invoice_user (email): cur = BMMySQL().conn().cursor(MySQLdb.cursors.DictCursor) cur.execute ("SELECT bm, masterpubkey_btc, offset_btc, feeamount, feecurrency FROM user WHERE email = %s AND active = 1", (email)) result = False for row in cur.fetchall(): result = row if result: if result['masterpubkey_btc'][0:4] == "xpub": # BIP44 dpk1 = bitcoin.bip32_ckd(result['masterpubkey_btc'], 0) dpk2 = bitcoin.bip32_ckd(dpk1, result['offset_btc']) pubkey = bitcoin.bip32_extract_key(dpk2) else: # Electrum 1.x pubkey = bitcoin.electrum_pubkey(result['masterpubkey_btc'], result['offset_btc']) address = bitcoin.pubkey_to_address(pubkey) bitcoind_importaddress(address) cur.execute ("UPDATE user SET offset_btc = offset_btc + 1 WHERE email = %s AND active = 1 AND masterpubkey_btc = %s", (email, result['masterpubkey_btc'])) if result['feecurrency'] in ("USD", "GBP", "EUR"): result['feeamount'] /= decimal.Decimal(get_bitcoin_price(result['feecurrency'])) cur.execute ("INSERT INTO invoice (issuer, address, coin, amount, type, paid) VALUES (%s, %s, 'BTC', %s, 1, 0)", (result['bm'], address, result['feeamount'])) cur.close() return address, result['feeamount']; cur.close() return False
def create_invoice_domain (domain, payer): cur = BMMySQL().conn().cursor(MySQLdb.cursors.DictCursor) filterwarnings('ignore', category = MySQLdb.Warning) cur.execute ("SELECT bm, masterpubkey_btc, offset_btc, feeamount, feecurrency FROM domain WHERE name = %s AND active = 1", (domain)) result = False for row in cur.fetchall(): result = row while result: if result['masterpubkey_btc'][0:4] == "xpub": # BIP44 dpk1 = bitcoin.bip32_ckd(result['masterpubkey_btc'], 0) dpk2 = bitcoin.bip32_ckd(dpk1, result['offset_btc']) pubkey = bitcoin.bip32_extract_key(dpk2) else: # Electrum 1.x pubkey = bitcoin.electrum_pubkey(result['masterpubkey_btc'], result['offset_btc']) address = bitcoin.pubkey_to_address(pubkey) bitcoind_importaddress(address) cur.execute ("UPDATE domain SET offset_btc = offset_btc + 1 WHERE name = %s AND active = 1 AND masterpubkey_btc = %s", (domain, result['masterpubkey_btc'])) if result['feecurrency'] in ("USD", "GBP", "EUR"): result['feeamount'] /= decimal.Decimal(get_bitcoin_price(result['feecurrency'])) cur.execute ("INSERT IGNORE INTO invoice (issuer, payer, address, coin, amount, type, paid) VALUES (%s, %s, %s, 'BTC', %s, 0, 0)", (result['bm'], payer, address, result['feeamount'])) # invoice already exists for that address, increment if cur.rowcount == 0: cur.execute ("SELECT bm, masterpubkey_btc, offset_btc, feeamount, feecurrency FROM domain WHERE name = %s AND active = 1", (domain)) result = False for row in cur.fetchall(): result = row continue cur.close() return address, result['feeamount']; cur.close() return False
def sign(tx, i, priv, t="default", script="", hashcode=SIGHASH_ALL): i = int(i) #if (not is_python2 and isinstance(re, bytes)) or not re.match('^[0-9a-fA-F]*$', tx): if not re.match('^[0-9a-fA-F]*$', tx): return binascii.unhexlify( custom_sign(safe_hexlify(tx), i, priv, hashcode)) if len(priv) <= 33: priv = b.safe_hexlify(priv) pub = b.privkey_to_pubkey(priv) address = b.pubkey_to_address(pub) if t not in ["atomic_1", "atomic_2"]: script = b.mk_pubkey_script(address) if script == "": error() signing_tx = b.signature_form( tx, i, script, hashcode) #mk_pubkey_scrip needs to be our custom scriptn sig = b.ecdsa_tx_sign(signing_tx, priv, hashcode) txobj = b.deserialize(tx) if t == "atomic_1": txobj["ins"][i]["script"] = b.serialize_script([sig]) if t == "atomic_2": old_sig = txobj["ins"][i]["script"] txobj["ins"][i]["script"] = b.serialize_script([old_sig, sig, 1]) else: txobj["ins"][i]["script"] = b.serialize_script([sig, pub]) return b.serialize(txobj)
def main(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument( '-k', '--key', default= '48f0ba87db8c803933caad92756647f753f07f5a1cd5735a62349b640e81bf94', type=str, help='BTC Private Key') args = parser.parse_args() inputprivatekey = args.key print("inputprivatekey=", inputprivatekey) public_key = private_key_to_public_key(inputprivatekey) #print("Public key (x,y) coordinates:", public_key) compressed_public_key = bitcoin.compress(public_key) #print("Public key (hex compressed):", compressed_public_key) address = pubkey_to_address(compressed_public_key) #print("Compressed Bitcoin address (base58check):", address) print("address=", bitcoin.pubkey_to_address(public_key))
def segwit_sign(tx, i, priv, amount, hashcode=SIGHASH_ALL, script=None, separator_index=None): i = int(i) txobj = tx if isinstance(tx, dict) else deserialize(tx) if not isinstance(tx, dict) and ((not is_python2 and isinstance(re, bytes)) or not re.match('^[0-9a-fA-F]*$', tx)): return binascii.unhexlify(sign(binascii.hexlify(tx), i, priv)) if len(priv) <= 33: priv = binascii.hexlify(priv) pub = privkey_to_pubkey(priv) address = pubkey_to_address(pub) wscript = mk_pubkey_script(address) if not script else script stripped_script = segwit_strip_script_separator(wscript, separator_index) signing_tx = segwit_signature_form(tx, i, stripped_script, amount, hashcode=hashcode) rawsig = ecdsa_raw_sign( hashlib.sha256( hashlib.sha256( binascii.unhexlify(signing_tx)).digest()).hexdigest(), priv) sig = der_encode_sig(*rawsig) + encode(hashcode, 16, 2) txobj['ins'][i]['txinwitness'] = [sig, pub if not script else script] return serialize(txobj)
def sign_donation_tx(tx, i, priv): from bitcoin.main import fast_multiply, decode_privkey, G, inv, N from bitcoin.transaction import der_encode_sig k = sign_k hashcode = btc.SIGHASH_ALL i = int(i) if len(priv) <= 33: priv = btc.safe_hexlify(priv) pub = btc.privkey_to_pubkey(priv) address = btc.pubkey_to_address(pub) signing_tx = btc.signature_form( tx, i, btc.mk_pubkey_script(address), hashcode) msghash = btc.bin_txhash(signing_tx, hashcode) z = btc.hash_to_int(msghash) # k = deterministic_generate_k(msghash, priv) r, y = fast_multiply(G, k) s = inv(k, N) * (z + r * decode_privkey(priv)) % N rawsig = 27 + (y % 2), r, s sig = der_encode_sig(*rawsig) + btc.encode(hashcode, 16, 2) # sig = ecdsa_tx_sign(signing_tx, priv, hashcode) txobj = btc.deserialize(tx) txobj["ins"][i]["script"] = btc.serialize_script([sig, pub]) return btc.serialize(txobj)
def generatekey(): keyword = request.args.get('keyword') mypriv = bitcoin.sha256(keyword) mypubl = bitcoin.privkey_to_pubkey(mypriv) myaddress = bitcoin.pubkey_to_address(mypubl) myInfo = {'mypriv': mypriv, 'mypubl': mypubl, 'myaddress': myaddress} return json.dumps(myInfo)
def carlisle_method(data, compress=False): """ Use the Carlisle method to generate a bitcoin address the hash of data. Args: data: bytes, data to hash compress: bool, whether to compress the public key Returns: dictionary with address generation information """ # Compute the sha256 hash of the data sha256_hash = hashlib.sha256(data) private_key = sha256_hash.hexdigest() # Generate public key public_key = bitcoin.privkey_to_pubkey(private_key) if compress: public_key = bitcoin.compress(public_key) # Generate bitcoin address address = bitcoin.pubkey_to_address(public_key) return { 'private_key': private_key, 'public_key': public_key, 'compressed': compress, 'address': address, 'url ': 'https://blockchain.info/address/{}'.format(address), }
def sign_donation_tx(tx, i, priv): from bitcoin.main import fast_multiply, decode_privkey, G, inv, N from bitcoin.transaction import der_encode_sig k = sign_k hashcode = btc.SIGHASH_ALL i = int(i) if len(priv) <= 33: priv = btc.safe_hexlify(priv) pub = btc.privkey_to_pubkey(priv) address = btc.pubkey_to_address(pub) signing_tx = btc.signature_form(tx, i, btc.mk_pubkey_script(address), hashcode) msghash = btc.bin_txhash(signing_tx, hashcode) z = btc.hash_to_int(msghash) # k = deterministic_generate_k(msghash, priv) r, y = fast_multiply(G, k) s = inv(k, N) * (z + r * decode_privkey(priv)) % N rawsig = 27 + (y % 2), r, s sig = der_encode_sig(*rawsig) + btc.encode(hashcode, 16, 2) # sig = ecdsa_tx_sign(signing_tx, priv, hashcode) txobj = btc.deserialize(tx) txobj["ins"][i]["script"] = btc.serialize_script([sig, pub]) return btc.serialize(txobj)
def sarah(hexli): private_key = hexli decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif') compressed_private_key = private_key + '01' wif_compressed_private_key = bitcoin.encode_privkey(bitcoin.decode_privkey(private_key, 'hex'), 'wif_compressed') public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex') (public_key_x, public_key_y) = public_key if public_key_y % 2 == 0: compressed_prefix = '02' else: compressed_prefix = '03' hex_compressed_public_key = compressed_prefix + bitcoin.encode(public_key_x, 16) non_compressed_adress = bitcoin.pubkey_to_address(public_key) compressed_address = bitcoin.pubkey_to_address(hex_compressed_public_key.encode("utf8")) return non_compressed_adress, compressed_address, wif_encoded_private_key, wif_compressed_private_key, private_key
def run(): while True: valid_private_key = False while not valid_private_key: private_key = bitcoin.random_key() decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.N wif_encoded_private_key = bitcoin.encode_privkey( decoded_private_key, 'wif') public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) r = requests.get("https://blockchain.info/q/getsentbyaddress/" + bitcoin.pubkey_to_address(public_key)) if int(r.text) > 0: print("Bitcoin Address is:", bitcoin.pubkey_to_address(public_key)) print("Private Key is: ", wif_encoded_private_key) print("Balance is: ", r.text)
def generate_key(): #generate a random private key valid_private_key = False while not valid_private_key: private_key = bitcoin.random_key() decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.N #print ('Private Key (hex) is: ' + private_key) #print ('private Key (decimal) is: ' + str(decoded_private_key)) #convert private key to WIF format wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif') #print('Private Key (WIF) is: ' + wif_encoded_private_key) # Add sufix '01' to indicate a compressed private Key compressed_private_key = private_key + '01' #print ('Private Key Compressed (hex) is: ' + compressed_private_key) # generate a WIF format from the compressed private key (WIF-compressed) wif_compressed_private_key = bitcoin.encode_privkey( bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif') #print ('Private Key (WIF-compressed) is: ' + wif_compressed_private_key) # Multiply de EC generator G with the priveate key to get a public key point public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) #print ('Public Key (x,y) coordinates are: ' + str(public_key)) # Encode as hex, prefix 04 hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex') #print ('Public Key (hex) is: ' + hex_encoded_public_key) # Compress public key, adjust prefix depending on whether y is even or odd (public_key_x, public_key_y) = public_key if public_key_y % 2 == 0: compressed_prefix = '02' else: compressed_prefix = '03' hex_compressed_public_key = compressed_prefix + bitcoin.encode( public_key_x, 16) #print ('Compressed Public Key is: ' + hex_compressed_public_key) # Generate bitcoin address from public Key #print ('Bitcoin Address (b58check) is: ' + bitcoin.pubkey_to_address(public_key)) # Generate compressedd bitcoin address from compressed public key #print ('Compressed Bitcoin Address (b58check) is: ' + bitcoin.pubkey_to_address(hex_compressed_public_key)) compressed_address_base58check = bitcoin.pubkey_to_address( hex_compressed_public_key) kson = { "wif1": wif_encoded_private_key, "wif": wif_compressed_private_key, "key": compressed_address_base58check } return kson
def generate_new_address(self, index): """ Generate new bitcoin address from a hd public master key based on a particlar index Address can be generated sequentially like in the case of electrum :param index: Index to use to generate address :return: Generated address """ address = btc.pubkey_to_address( btc.bip32_descend(self.public_key, [0, index])) return address
def function_keys(): valid_private_key = False #randomize private key while not valid_private_key: private_key = bitcoin.random_key() decode_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decode_private_key < bitcoin.N print "Private Key (hex) is:", private_key print "Private Key (decimal) is:", decode_private_key wif_encode_private_key = bitcoin.encode_privkey(decode_private_key, 'wif') print "Private key (WIF) is:", wif_encode_private_key # convert private key to wif format compressed_private_key = private_key + '01' print "Private key Compressed (hex) is:", compressed_private_key # add '01' to indicate compressed private key wif_compressed_private_key = bitcoin.encode_privkey( bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif') print "Private Key (Wif-compressed) is:", wif_compressed_private_key public_key = bitcoin.fast_multiply( bitcoin.G, decode_private_key ) # multiply EC generator with the private key to have public key point print "Public Key (x, y) coordinates is:", public_key hex_encoded_public_key = bitcoin.encode_pubkey( public_key, 'hex') # encoded public key with '04' print "Public Key (hex) is:", hex_encoded_public_key (public_key_x, public_key_y) = public_key # compressed public key if (public_key_y % 2) == 0: compressed_prefix = '02' else: compressed_prefix = '03' hex_compressed_public_key = compressed_prefix + bitcoin.encode( public_key_x, 16) print "Compressed Public Key (hex) is:", hex_compressed_public_key print "Bitcoin Address (b58check) is:", bitcoin.pubkey_to_address( public_key) print "Compressed Bitcoin Address (b58check) is:", bitcoin.pubkey_to_address( hex_compressed_public_key)
def get_key_pair(): v = False while not v: private_key = bitcoin.random_key() private_key = bitcoin.decode_privkey(private_key) v = 0 < private_key < bitcoin.N wif_private_key = bitcoin.encode_privkey(private_key, 'wif') public_key = bitcoin.privkey_to_pubkey(wif_private_key) address = bitcoin.pubkey_to_address(public_key) return address, wif_private_key
def auth_counterparty(self, nick, cr): #deserialize the commitment revelation cr_dict = btc.PoDLE.deserialize_revelation(cr) #check the validity of the proof of discrete log equivalence tries = jm_single().config.getint("POLICY", "taker_utxo_retries") def reject(msg): log.info("Counterparty commitment not accepted, reason: " + msg) return False if not btc.verify_podle(cr_dict['P'], cr_dict['P2'], cr_dict['sig'], cr_dict['e'], self.maker.commit, index_range=range(tries)): reason = "verify_podle failed" return reject(reason) #finally, check that the proffered utxo is real, old enough, large enough, #and corresponds to the pubkey res = jm_single().bc_interface.query_utxo_set([cr_dict['utxo']], includeconf=True) if len(res) != 1 or not res[0]: reason = "authorizing utxo is not valid" return reject(reason) age = jm_single().config.getint("POLICY", "taker_utxo_age") if res[0]['confirms'] < age: reason = "commitment utxo not old enough: " + str(res[0]['confirms']) return reject(reason) reqd_amt = int(self.cj_amount * jm_single().config.getint( "POLICY", "taker_utxo_amtpercent") / 100.0) if res[0]['value'] < reqd_amt: reason = "commitment utxo too small: " + str(res[0]['value']) return reject(reason) if res[0]['address'] != btc.pubkey_to_address(cr_dict['P'], get_p2pk_vbyte()): reason = "Invalid podle pubkey: " + str(cr_dict['P']) return reject(reason) # authorisation of taker passed # Send auth request to taker # Need to choose an input utxo pubkey to sign with # (no longer using the coinjoin pubkey from 0.2.0) # Just choose the first utxo in self.utxos and retrieve key from wallet. auth_address = self.utxos[self.utxos.keys()[0]]['address'] auth_key = self.maker.wallet.get_key_from_addr(auth_address) auth_pub = btc.privtopub(auth_key) btc_sig = btc.ecdsa_sign(self.kp.hex_pk(), auth_key) self.maker.msgchan.send_ioauth(nick, self.utxos.keys(), auth_pub, self.cj_addr, self.change_addr, btc_sig) #In case of *blacklisted (ie already used) commitments, we already #broadcasted them on receipt; in case of valid, and now used commitments, #we broadcast them here, and not early - to avoid accidentally #blacklisting commitments that are broadcast between makers in real time #for the same transaction. self.maker.transfer_commitment(self.maker.commit) #now persist the fact that the commitment is actually used. check_utxo_blacklist(self.maker.commit, persist=True) return True
def key_address(masterkey, path): """Compute address and private key (hex) for path""" derived_key = descend(masterkey, path) priv_key = btc.bip32_deserialize(derived_key)[-1] pub_key = btc.bip32_extract_key(btc.bip32_privtopub(derived_key)) priv_key_hex = btc.encode_privkey( btc.decode_privkey(priv_key, 'bin_compressed'), 'hex') address = btc.pubkey_to_address(pub_key) return priv_key_hex, address
def save_memo(request): encrypted_text = request.POST['encrypted_text'] pubkey = request.POST['pubkey'] sig = request.POST['signature'] txid = request.POST['txid'].lower() crypto = request.POST.get('currency', 'btc').lower() if len(encrypted_text) > settings.MAX_MEMO_SIZE_BYTES: return http.JsonResponse( { 'error': "Memo exceeds maximum size of: %s bytes" % settings.MAX_MEMO_SIZE_BYTES }, status=400) data = dict(pubkey=pubkey, crypto=crypto, txid=txid, encrypted_text=encrypted_text) if Memo.objects.filter(**data).exists(): return http.HttpResponse("OK") data['signature'] = sig try: version_byte = crypto_data[crypto]['address_version_byte'] except IndexError: return http.HttpResponse("Currency not supported", status=400) address = pubkey_to_address(pubkey, version_byte) tx = CachedTransaction.fetch_full_tx(crypto, txid=txid) for item in tx['inputs'] + tx['outputs']: if item['address'] == address: break else: return http.HttpResponse("Pubkey not in TXID", status=400) if ecdsa_verify(encrypted_text, sig, pubkey): memo, c = Memo.objects.get_or_create(crypto=crypto, txid=txid, pubkey=pubkey) memo.encrypted_text = encrypted_text memo.signature = sig memo.save() else: return http.HttpResponse("Invalid signature", status=400) return http.HttpResponse("OK")
def segwit_sign(tx, i, priv, amount, hashcode=SIGHASH_ALL, script=None, separator_index=None): i = int(i) txobj = tx if isinstance(tx, dict) else deserialize(tx) if not isinstance(tx, dict) and ((not is_python2 and isinstance(re, bytes)) or not re.match('^[0-9a-fA-F]*$', tx)): return binascii.unhexlify(sign(binascii.hexlify(tx), i, priv)) if len(priv) <= 33: priv = binascii.hexlify(priv) pub = privkey_to_pubkey(priv) address = pubkey_to_address(pub) wscript = mk_pubkey_script(address) if not script else script stripped_script = segwit_strip_script_separator(wscript, separator_index) signing_tx = segwit_signature_form(tx, i, stripped_script, amount, hashcode=hashcode) rawsig = ecdsa_raw_sign(hashlib.sha256(hashlib.sha256(binascii.unhexlify(signing_tx)).digest()).hexdigest(), priv) sig = der_encode_sig(*rawsig)+encode(hashcode, 16, 2) txobj['ins'][i]['txinwitness'] = [sig, pub if not script else script] return serialize(txobj)
def save_memo(request): encrypted_text = request.POST['encrypted_text'] pubkey = request.POST['pubkey'] sig = request.POST['signature'] txid = request.POST['txid'].lower() crypto = request.POST.get('currency', 'btc').lower() if len(encrypted_text) > settings.MAX_MEMO_SIZE_BYTES: return http.JsonResponse( {'error': "Memo exceeds maximum size of: %s bytes" % settings.MAX_MEMO_SIZE_BYTES}, status=400 ) data = dict(pubkey=pubkey, crypto=crypto, txid=txid, encrypted_text=encrypted_text) if Memo.objects.filter(**data).exists(): return http.HttpResponse("OK") data['signature'] = sig try: version_byte = crypto_data[crypto]['address_version_byte'] except IndexError: return http.HttpResponse("Currency not supported", status=400) address = pubkey_to_address(pubkey, version_byte) tx = CachedTransaction.fetch_full_tx(crypto, txid=txid) for item in tx['inputs'] + tx['outputs']: if item['address'] == address: break else: return http.HttpResponse("Pubkey not in TXID", status=400) if ecdsa_verify(encrypted_text, sig, pubkey): memo, c = Memo.objects.get_or_create( crypto=crypto, txid=txid, pubkey=pubkey ) memo.encrypted_text = encrypted_text memo.signature = sig memo.save() else: return http.HttpResponse("Invalid signature", status=400) return http.HttpResponse("OK")
def address_search(search_for='1Love'): privkey = random.randrange(2**256) address = '' count = 0 start = timeit.default_timer() print("Searching for %s (pid %s)" % (search_for, os.getpid())) while not search_for in address: privkey += 1 pubkey_point = fast_multiply(G, privkey) address = pubkey_to_address(pubkey_point) count += 1 if not count % 1000: print("Searched %d in %d seconds (pid %d)" % (count, timeit.default_timer() - start, os.getpid())) private_key, public_key, pid, wif_key = key_data(privkey) key_data_output(private_key, public_key, pid, wif_key, search_for, address, count, start)
def checkSigBitcoin(message, signature, authorname): try: # FIXME: is base64.b64decode(...) safe? pub = bitcoin.ecdsa_recover(message, signature) except: raise jvalidate.ValidationError( "Bitcoin signature or message invalid.") author = Member.by_name(authorname) if author is None: raise jvalidate.ValidationError( "Member '%s' not found for PGP signature check." % authorname) addr = author.address addr_from_pub = bitcoin.pubkey_to_address(pub) # is this enough? FIXME: review! # FIXME: check type(?) bug in bitcoin.ecsda_verify_addr if addr != addr_from_pub: raise jvalidate.ValidationError( "Bitcoin signature validation failed (%s, %s, %s)." % (repr(message), signature, addr))
def get_wallet_balance_from_extended_public_key(extended_public_key, derivation_path, last_child_index_to_search, network=Network.MAINNET): (versionBytes, depth, parentKeyFingerprint, index, chainCode, pubKey) = deserialize_extended_key( extended_public_key) index = int.from_bytes(index, 'big') hardened = index >= 2 ** 31 if hardened: index -= 2 ** 31 debug_print("XPUB Info: Depth: " + str(ord(depth)) + " index: " + str(index) + " hardened: " + str(hardened)) total_balance = 0 magic_byte = public_magic_byte if network == Network.MAINNET else testnet_magic_byte for i in range(0, last_child_index_to_search): child_key, child_chain_code, child_pub_key = derive_child_from_path( derivation_path=derivation_path + str(i), parent_key=pubKey, key_type=KeyType.PUBLIC, parent_chain_code=chainCode, network=network) address = bitcoin.pubkey_to_address(bitcoin.compress(child_pub_key), magic_byte) total_balance += query_address_info(address) print("Total Balance for this Wallet: " + pretty_format_account_balance(total_balance))
def sign(tx, i, priv, t="default", script="", hashcode=SIGHASH_ALL): i = int(i) #if (not is_python2 and isinstance(re, bytes)) or not re.match('^[0-9a-fA-F]*$', tx): if not re.match('^[0-9a-fA-F]*$', tx): return binascii.unhexlify(custom_sign(safe_hexlify(tx), i, priv, hashcode)) if len(priv) <= 33: priv = b.safe_hexlify(priv) pub = b.privkey_to_pubkey(priv) address = b.pubkey_to_address(pub) if t not in ["atomic_1", "atomic_2"]: script=b.mk_pubkey_script(address) if script=="": error() signing_tx = b.signature_form(tx, i, script, hashcode)#mk_pubkey_scrip needs to be our custom scriptn sig = b.ecdsa_tx_sign(signing_tx, priv, hashcode) txobj = b.deserialize(tx) if t=="atomic_1": txobj["ins"][i]["script"] = b.serialize_script([sig]) if t=="atomic_2": old_sig = txobj["ins"][i]["script"] txobj["ins"][i]["script"] = b.serialize_script([old_sig, sig, 1]) else: txobj["ins"][i]["script"] = b.serialize_script([sig, pub]) return b.serialize(txobj)
def KeyToAddress(key): private_key = str(key) decoded_private_key = bitcoin.decode_privkey(private_key.encode("utf-8"), 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.N wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif') keys = wif_encoded_private_key public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) (public_key_x, public_key_y) = public_key if (public_key_y % 2) == 0: compressed_prefix = '02' else: compressed_prefix = '03' hex_compressed_public_key = compressed_prefix + bitcoin.encode( public_key_x, 16) address1 = bitcoin.pubkey_to_address(public_key) #address2 = bitcoin.pubkey_to_address(hex_compressed_public_key.encode("utf-8")) #balance1 = balanceApi(address1) #balance1 = btcApi(address1) #if balance1 ==None: # balance1 = 0 if Address.objects.filter(address=address1): balance = "可能有余额" else: balance = "没有" return keys, address1, balance
pubKeyBytes = binascii.unhexlify(pubKey) sha256val = hashlib.sha256(pubKeyBytes).digest() ripemd160val = hashlib.new('ripemd160', sha256val).digest() return bitcoin.bin_to_b58check(ripemd160val, magic_byte) priv_key = base58.b58decode('5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ') private_key = binascii.hexlify(priv_key) prKey = private_key[2:-8] print("Private Key (hex): ", prKey) public_key = private_key_to_public_key(prKey) print("Public key (x,y) coordinates: ", public_key) compressed_public_key = bitcoin.compress(public_key) print("Public key (hex compressed): ", compressed_public_key) print() address = bitcoin.pubkey_to_address(public_key) print("Address: ", address) address1 = pubkey_to_address(compressed_public_key) print("Compressed Bitcoin Address (bas58check): ", address1) addressDEC = base58.b58decode(address1) print(addressDEC)
# Add suffix "01" to indicate a compressed private key compressed_private_key = private_key + '01' print("Private Key Compressed (hex) is: ", compressed_private_key) # Generate a WIF format from the compressed private key (WIF-compressed) wif_compressed_private_key = bitcoin.encode_privkey( bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif') print("Private Key (WIF-Compressed) is: ", wif_compressed_private_key) # Multiply the EC generator point G with the private key to get a public key point public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) print("Public Key (x,y) coordinates is:", public_key) # Encode as hex, prefix 04 hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex') print("Public Key (hex) is:", hex_encoded_public_key) # Compress public key, adjust prefix depending on whether y is even or odd (public_key_x, public_key_y) = public_key compressed_prefix = '02' if (public_key_y % 2) == 0 else '03' hex_compressed_public_key = compressed_prefix + bitcoin.encode( public_key_x, 16) print("Compressed Public Key (hex) is:", hex_compressed_public_key) # Generate bitcoin address from public key print("Bitcoin Address (b58check) is:", bitcoin.pubkey_to_address(public_key)) # Generate compressed bitcoin address from compressed public key print("Compressed Bitcoin Address (b58check) is:", bitcoin.pubkey_to_address(hex_compressed_public_key))
def recv_txio(self, nick, utxo_list, auth_pub, cj_addr, change_addr): if nick: if nick not in self.nonrespondants: log.debug(('recv_txio => nick={} not in ' 'nonrespondants {}').format(nick, self.nonrespondants)) return self.utxos[nick] = utxo_list utxo_data = jm_single().bc_interface.query_utxo_set(self.utxos[nick]) if None in utxo_data: log.error(('ERROR outputs unconfirmed or already spent. ' 'utxo_data={}').format(pprint.pformat(utxo_data))) # when internal reviewing of makers is created, add it here to # immediately quit; currently, the timeout thread suffices. return #Complete maker authorization: #Extract the address fields from the utxos #Construct the Bitcoin address for the auth_pub field #Ensure that at least one address from utxos corresponds. input_addresses = [d['address'] for d in utxo_data] auth_address = btc.pubkey_to_address(auth_pub, get_p2pk_vbyte()) if not auth_address in input_addresses: log.error("ERROR maker's authorising pubkey is not included " "in the transaction: " + str(auth_address)) return total_input = sum([d['value'] for d in utxo_data]) real_cjfee = calc_cj_fee(self.active_orders[nick]['ordertype'], self.active_orders[nick]['cjfee'], self.cj_amount) change_amount = (total_input - self.cj_amount - self.active_orders[nick]['txfee'] + real_cjfee) # certain malicious and/or incompetent liquidity providers send # inputs totalling less than the coinjoin amount! this leads to # a change output of zero satoshis, so the invalid transaction # fails harmlessly; let's fail earlier, with a clear message. if change_amount < jm_single().BITCOIN_DUST_THRESHOLD: fmt = ('ERROR counterparty requires sub-dust change. No ' 'action required. nick={}' 'totalin={:d} cjamount={:d} change={:d}').format log.warn(fmt(nick, total_input, self.cj_amount, change_amount)) return # timeout marks this maker as nonresponsive self.outputs.append({'address': change_addr, 'value': change_amount}) fmt = ('fee breakdown for {} totalin={:d} ' 'cjamount={:d} txfee={:d} realcjfee={:d}').format log.debug(fmt(nick, total_input, self.cj_amount, self.active_orders[nick]['txfee'], real_cjfee)) self.outputs.append({'address': cj_addr, 'value': self.cj_amount}) self.cjfee_total += real_cjfee self.maker_txfee_contributions += self.active_orders[nick]['txfee'] self.nonrespondants.remove(nick) if len(self.nonrespondants) > 0: log.debug('nonrespondants = ' + str(self.nonrespondants)) return #Note we fall through here immediately if nick is None; #this is the case for recovery where we are going to do a join with #less participants than originally intended. If minmakers is set to 0, #disallowing completion with subset, assert is still true. assert len(self.active_orders.keys()) >= jm_single().config.getint( "POLICY", "minimum_makers") log.info('got all parts, enough to build a tx') self.nonrespondants = list(self.active_orders.keys()) my_total_in = sum([va['value'] for u, va in self.input_utxos.iteritems()]) if self.my_change_addr: #Estimate fee per choice of next/3/6 blocks targetting. estimated_fee = estimate_tx_fee(len(sum( self.utxos.values(),[])), len(self.outputs)+2) log.info("Based on initial guess: "+str( self.total_txfee)+", we estimated a miner fee of: "+str(estimated_fee)) #reset total self.total_txfee = estimated_fee my_txfee = max(self.total_txfee - self.maker_txfee_contributions, 0) my_change_value = ( my_total_in - self.cj_amount - self.cjfee_total - my_txfee) #Since we could not predict the maker's inputs, we may end up needing #too much such that the change value is negative or small. Note that #we have tried to avoid this based on over-estimating the needed amount #in SendPayment.create_tx(), but it is still a possibility if one maker #uses a *lot* of inputs. if self.my_change_addr and my_change_value <= 0: raise ValueError("Calculated transaction fee of: "+str( self.total_txfee)+" is too large for our inputs;Please try again.") elif self.my_change_addr and my_change_value <= jm_single().BITCOIN_DUST_THRESHOLD: log.info("Dynamically calculated change lower than dust: "+str( my_change_value)+"; dropping.") self.my_change_addr = None my_change_value = 0 log.info('fee breakdown for me totalin=%d my_txfee=%d makers_txfee=%d cjfee_total=%d => changevalue=%d' % (my_total_in, my_txfee, self.maker_txfee_contributions, self.cjfee_total, my_change_value)) if self.my_change_addr is None: if my_change_value != 0 and abs(my_change_value) != 1: # seems you wont always get exactly zero because of integer # rounding so 1 satoshi extra or fewer being spent as miner # fees is acceptable log.debug(('WARNING CHANGE NOT BEING ' 'USED\nCHANGEVALUE = {}').format(my_change_value)) else: self.outputs.append({'address': self.my_change_addr, 'value': my_change_value}) self.utxo_tx = [dict([('output', u)]) for u in sum(self.utxos.values(), [])] self.outputs.append({'address': self.coinjoin_address(), 'value': self.cj_amount}) random.shuffle(self.utxo_tx) random.shuffle(self.outputs) tx = btc.mktx(self.utxo_tx, self.outputs) log.debug('obtained tx\n' + pprint.pformat(btc.deserialize(tx))) #Re-calculate a sensible timeout wait based on the throttling #settings and the tx size. #Calculation: Let tx size be S; tx undergoes two b64 expansions, 1.8*S #So we're sending N*1.8*S over the wire, and the #maximum bytes/sec = B, means we need (1.8*N*S/B) seconds, #and need to add some leeway for network delays, we just add the #contents of jm_single().maker_timeout_sec (the user configured value) self.maker_timeout_sec = (len(tx) * 1.8 * len( self.active_orders.keys()))/(B_PER_SEC) + jm_single().maker_timeout_sec log.info("Based on transaction size: " + str( len(tx)) + ", calculated time to wait for replies: " + str( self.maker_timeout_sec)) self.all_responded = True with self.timeout_lock: self.timeout_lock.notify() self.msgchan.send_tx(self.active_orders.keys(), tx) self.latest_tx = btc.deserialize(tx) for index, ins in enumerate(self.latest_tx['ins']): utxo = ins['outpoint']['hash'] + ':' + str( ins['outpoint']['index']) if utxo not in self.input_utxos.keys(): continue # placeholders required ins['script'] = 'deadbeef'
import bitcoin valid_private_key = False while not valid_private_key: private_key = bitcoin.random_key() decoded_private_key = bitcoin.decode_privkey(private_key, 'hex') valid_private_key = 0 < decoded_private_key < bitcoin.N print("Private key in hexadecimal is {}".format(private_key)) print("Private key in decimal is {}".format(decoded_private_key)) wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif') print("Private key in WIF is {}".format(wif_encoded_private_key)) compressed_private_key = private_key + '01' print("Private key compressed in hexadecimal {}".format(compressed_private_key)) wif_compressed_private_key = bitcoin.encode_privkey(bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif') print("Private key WIF compressed is {}".format(wif_compressed_private_key)) public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key) print("Public key (x,y) coordinates is".format(public_key)) hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex') print("Hex encoded public key is {}".format(hex_encoded_public_key)) (public_key_x, public_key_y) = public_key if (public_key_y % 2) == 0: compressed_prefix = '02' else: compressed_prefix = '03' hex_compressed_public_key = compressed_prefix + bitcoin.encode(public_key_x, 16) print("Compressed Public Key (hex) is {}".format(hex_compressed_public_key)) print("Bitcoin Address (b58check) is {}".format(bitcoin.pubkey_to_address(public_key))) print("Compressed Bitcoin Address (b58check) is: {}".format(bitcoin.pubkey_to_address(hex_compressed_public_key)))
closeLibrary() openLibrary() """ return pub def test(): sign = "HGbib2kv9gm9IJjDt1FXbXFczZi35u0rZR3iPUIt5GglDDCeIQ7v8eYXVNIaLoJRI4URGZrhwmsYQ9aVtRTnTfQ=" pubkey = "044827c756561b8ef6b28b5e53a000805adbf4938ab82e1c2b7f7ea16a0d6face9a509a0a13e794d742210b00581f3e249ebcc705240af2540ea19591091ac1d41" assert getMessagePubkey("hello", sign).encode("hex") == pubkey test() # Make sure it working right if __name__ == "__main__": import time import os import sys sys.path.append("../pybitcointools") import bitcoin as btctools print "OpenSSL version %s" % openssl_version print ssl._lib priv = "5JsunC55XGVqFQj5kPGK4MWgTL26jKbnPhjnmchSNPo75XXCwtk" address = "1N2XWu5soeppX2qUjvrf81rpdbShKJrjTr" sign = btctools.ecdsa_sign("hello", priv) # HGbib2kv9gm9IJjDt1FXbXFczZi35u0rZR3iPUIt5GglDDCeIQ7v8eYXVNIaLoJRI4URGZrhwmsYQ9aVtRTnTfQ= s = time.time() for i in range(1000): pubkey = getMessagePubkey("hello", sign) verified = btctools.pubkey_to_address(pubkey) == address print "100x Verified", verified, time.time() - s