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 sign_tx(certificate_metadata, last_input, allowable_wif_prefixes=None): """sign the transaction with private key""" with open(certificate_metadata.unsigned_tx_file_name, 'rb') as in_file: hextx = str(in_file.read(), 'utf-8') logging.info( 'Signing tx with private key for recipient id: %s ...', certificate_metadata.uid) tx = Tx.from_hex(hextx) if allowable_wif_prefixes: wif = wif_to_secret_exponent( helpers.import_key(), allowable_wif_prefixes) else: wif = wif_to_secret_exponent(helpers.import_key()) lookup = build_hash160_lookup([wif]) tx.set_unspents( [TxOut(coin_value=last_input.amount, script=last_input.script_pub_key)]) signed_tx = tx.sign(lookup) signed_hextx = signed_tx.as_hex() with open(certificate_metadata.unsent_tx_file_name, 'wb') as out_file: out_file.write(bytes(signed_hextx, 'utf-8')) logging.info('Finished signing transaction for certificate uid=%s', certificate_metadata.uid)
def sign_tx(certificate_metadata, last_input, allowable_wif_prefixes=None): """sign the transaction with private key""" with open(certificate_metadata.unsigned_tx_file_name, 'rb') as in_file: hextx = str(in_file.read(), 'utf-8') logging.info('Signing tx with private key for recipient id: %s ...', certificate_metadata.uid) tx = Tx.from_hex(hextx) if allowable_wif_prefixes: wif = wif_to_secret_exponent(helpers.import_key(), allowable_wif_prefixes) else: wif = wif_to_secret_exponent(helpers.import_key()) lookup = build_hash160_lookup([wif]) tx.set_unspents([ TxOut(coin_value=last_input.amount, script=last_input.script_pub_key) ]) signed_tx = tx.sign(lookup) signed_hextx = signed_tx.as_hex() with open(certificate_metadata.unsent_tx_file_name, 'wb') as out_file: out_file.write(bytes(signed_hextx, 'utf-8')) logging.info('Finished signing transaction for certificate uid=%s', certificate_metadata.uid)
def sign_tx(hextx, tx_input, allowable_wif_prefixes=None): """ Sign the transaction with private key :param hextx: :param tx_input: :param allowable_wif_prefixes: :return: """ logging.info('Signing tx with private key') tx = Tx.from_hex(hextx) if allowable_wif_prefixes: wif = wif_to_secret_exponent( helpers.import_key(), allowable_wif_prefixes) else: wif = wif_to_secret_exponent(helpers.import_key()) lookup = build_hash160_lookup([wif]) tx.set_unspents( [TxOut(coin_value=tx_input.amount, script=tx_input.script_pub_key)]) signed_tx = tx.sign(lookup) signed_hextx = signed_tx.as_hex() logging.info('Finished signing transaction') return signed_hextx
def send(self, ddestination_address, dcolourid=None): self.colordata.update() coins_to = [] total_spent = 0 for daa in [ddestination_address]: address, amount = daa[0], daa[1] amount = btc_to_satoshi(amount) total_spent += amount coins_to.append((amount, address)) selected_utxos, total_value = self.selectUTXOs(self.getAllUTXOs(), dcolourid, total_spent) change = (total_value - total_spent) - 10000 if change >= 1: coins_to.append((change, self.addresses[0].pubkey)) coins_from = [utxo.get_pycoin_coin_source() for utxo in selected_utxos] secret_exponents = [encoding.wif_to_secret_exponent(address.privkey) for address in self.addresses] unsigned_tx = UnsignedTx.standard_tx(coins_from, coins_to) solver = SecretExponentSolver(secret_exponents) new_tx = unsigned_tx.sign(solver) s = io.BytesIO() new_tx.stream(s) tx_bytes = s.getvalue() tx_hex = binascii.hexlify(tx_bytes).decode("utf8") recommended_tx_fee = tx_fee.recommended_fee_for_tx(new_tx) print tx_hex URL = "http://blockchain.info/pushtx" urllib2.urlopen(URL, data=tx_hex)
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 bitcoin(public, private, address, amount): coins_from = [] coins_sources = blockchain_info.coin_sources_for_address(public) coins_from.extend(coins_sources) value = sum(cs[-1].coin_value for cs in coins_sources) secret_exponents = [encoding.wif_to_secret_exponent(private)] amount = btc_to_satoshi(amount) coins_to = [] coins_to.append((amount, address)) actual_tx_fee = value - amount if actual_tx_fee < 0: print("not enough source coins (%s BTC) for destination (%s BTC). Short %s BTC" % (satoshi_to_btc(total_value), satoshi_to_btc(total_spent), satoshi_to_btc(-actual_tx_fee))) return None; if actual_tx_fee > 0: coins_to.append((actual_tx_fee, public)) unsigned_tx = UnsignedTx.standard_tx(coins_from, coins_to) solver = SecretExponentSolver(secret_exponents) new_tx = unsigned_tx.sign(solver) s = io.BytesIO() new_tx.stream(s) tx_bytes = s.getvalue() tx_hex = binascii.hexlify(tx_bytes).decode("utf8") return tx_bytes
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 calculate(self): all_tasks = pstasks.mac_tasks(self._config).allprocs() bit_tasks = [] try: if self._config.PID: # find tasks given PIDs pidlist = [int(p) for p in self._config.PID.split(',')] bit_tasks = [t for t in all_tasks if t.p_pid in pidlist] else: # find multibit process name_re = re.compile("JavaApplicationS", re.I) bit_tasks = [ t for t in all_tasks if name_re.search(str(t.p_comm)) ] except: pass if len(bit_tasks) == 0: yield (None, None) # scan for bitcoin addresses with yara, 34 chars, https://en.bitcoin.it/wiki/Address # Most Bitcoin addresses are 34 characters. They consist of random digits and uppercase # and lowercase letters, with the exception that the uppercase letter "O", uppercase # letter "I", lowercase letter "l", and the number "0" are never used to prevent visual ambiguity. bit_addrs = [] addr_rule = yara.compile(sources={ 'n': 'rule r1 {strings: $a = /[1-9a-zA-z]{34}(?!OIl)/ condition: $a}' }) for task in bit_tasks: scanner = mac_yarascan.MapYaraScanner(task=task, rules=addr_rule) for hit, address in scanner.scan(): content = scanner.address_space.zread(address, 34) if pyenc.is_valid_bitcoin_address( content) and content not in bit_addrs: bit_addrs.append(content) # scan for bitcoin keys with yara, 52 char compressed base58, starts with L or K, https://en.bitcoin.it/wiki/Private_key addr_key = {} key_rule = yara.compile(sources={ 'n': 'rule r1 {strings: $a = /(L|K)[0-9A-Za-z]{51}/ condition: $a}' }) for task in bit_tasks: scanner = mac_yarascan.MapYaraScanner(task=task, rules=key_rule) for hit, address in scanner.scan(): content = scanner.address_space.zread(address, 52) if pyenc.is_valid_wif(content): secret_exp = pyenc.wif_to_secret_exponent(content) key = pykey.Key(secret_exponent=secret_exp, is_compressed=True) if key.address() not in addr_key.keys(): addr_key[key.address()] = content yield (content, key.address()) # addresses with no known keys for bit_addr in bit_addrs: if bit_addr not in addr_key.keys(): yield ("UNKNOWN", bit_addr)
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 bitcoin(public, private, address, amount): coins_from = [] coins_sources = blockchain_info.coin_sources_for_address(public) coins_from.extend(coins_sources) value = sum(cs[-1].coin_value for cs in coins_sources) secret_exponents = [encoding.wif_to_secret_exponent(private)] amount = btc_to_satoshi(amount) coins_to = [] coins_to.append((amount, address)) actual_tx_fee = value - amount if actual_tx_fee < 0: print( "not enough source coins (%s BTC) for destination (%s BTC). Short %s BTC" % (satoshi_to_btc(total_value), satoshi_to_btc(total_spent), satoshi_to_btc(-actual_tx_fee))) return None if actual_tx_fee > 0: coins_to.append((actual_tx_fee, public)) unsigned_tx = UnsignedTx.standard_tx(coins_from, coins_to) solver = SecretExponentSolver(secret_exponents) new_tx = unsigned_tx.sign(solver) s = io.BytesIO() new_tx.stream(s) tx_bytes = s.getvalue() tx_hex = binascii.hexlify(tx_bytes).decode("utf8") return tx_bytes
def decrypt_message(public_key, encrypted_message): """Decrypts the message given a public key and an encrypted message. User needs to control the private key via bitcoind. """ wif = get_private_key_from_address(public_key) secret_exponent = wif_to_secret_exponent(wif) private_key = PrivKey(secret_exponent) return private_key.decrypt(b64decode(encrypted_message))
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 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 parse_as_private_key(s): v = parse_as_number(s) if v and v < secp256k1._r: return v try: v = encoding.wif_to_secret_exponent(s) return v except encoding.EncodingError: pass
def sign_transaction(self, wif, transaction_to_sign): secret_exponent = wif_to_secret_exponent(wif, self.allowable_wif_prefixes) lookup = build_hash160_lookup([secret_exponent]) signed_transaction = transaction_to_sign.sign(lookup) # Because signing failures silently continue, first check that the inputs are signed for input in signed_transaction.txs_in: if len(input.script) == 0: logging.error('Unable to sign transaction. hextx=%s', signed_transaction.as_hex()) raise UnableToSignTxError('Unable to sign transaction') return signed_transaction
def publish_data(data): secret_exponent = wif_to_secret_exponent(PAYMENT_PRIVATE_KEY) _from = PAYMENT_ADDRESS unsigned_tx = construct_data_tx(data, _from) if type(unsigned_tx) == str: # error return (None, unsigned_tx) signed_tx = unsigned_tx.sign(SecretExponentSolver([secret_exponent])) tx_hex = tx2hex(signed_tx) return pushtxn(tx_hex)
def private_key_iterator(pk): try: wallet = Wallet.from_wallet_key(pk) return (w.secret_exponent for w in wallet.children(max_level=50, start_index=0)) except (encoding.EncodingError, TypeError): try: exp = encoding.wif_to_secret_exponent(pk) return [exp] except encoding.EncodingError: sys.stderr.write('bad value: "%s"\n' % pk) sys.exit(1)
def get(self, v): if v in self.secret_exponent_db_cache: return self.secret_exponent_db_cache[v] for wif in self.wif_iterable: secret_exponent = wif_to_secret_exponent(wif, self.wif_prefix) d = build_hash160_lookup([secret_exponent]) self.secret_exponent_db_cache.update(d) if v in self.secret_exponent_db_cache: return self.secret_exponent_db_cache[v] self.wif_iterable = [] return None
def pycoin_construct_tx(input_utxos, outputs): from pycoin import encoding from pycoin.tx import UnsignedTx, SecretExponentSolver import io inputs = [utxo.get_pycoin_coin_source() for utxo in input_utxos] secret_exponents = [encoding.wif_to_secret_exponent(utxo.address.meat.privkey) for utxo in input_utxos] unsigned_tx = UnsignedTx.standard_tx(inputs, outputs) solver = SecretExponentSolver(secret_exponents) new_tx = unsigned_tx.sign(solver) s = io.BytesIO() new_tx.stream(s) return s.getvalue()
def calculate(self): all_tasks = pstasks.mac_tasks(self._config).allprocs() bit_tasks = [] try: if self._config.PID: # find tasks given PIDs pidlist = [int(p) for p in self._config.PID.split(',')] bit_tasks = [t for t in all_tasks if t.p_pid in pidlist] else: # find multibit process name_re = re.compile("JavaApplicationS", re.I) bit_tasks = [t for t in all_tasks if name_re.search(str(t.p_comm))] except: pass if len(bit_tasks) == 0: yield (None, None) # scan for bitcoin addresses with yara, 34 chars, https://en.bitcoin.it/wiki/Address # Most Bitcoin addresses are 34 characters. They consist of random digits and uppercase # and lowercase letters, with the exception that the uppercase letter "O", uppercase # letter "I", lowercase letter "l", and the number "0" are never used to prevent visual ambiguity. bit_addrs = [] addr_rule = yara.compile(sources = {'n' : 'rule r1 {strings: $a = /[1-9a-zA-z]{34}(?!OIl)/ condition: $a}'}) for task in bit_tasks: scanner = mac_yarascan.MapYaraScanner(task = task, rules = addr_rule) for hit, address in scanner.scan(): content = scanner.address_space.zread(address, 34) if pyenc.is_valid_bitcoin_address(content) and content not in bit_addrs: bit_addrs.append(content) # scan for bitcoin keys with yara, 52 char compressed base58, starts with L or K, https://en.bitcoin.it/wiki/Private_key addr_key = {} key_rule = yara.compile(sources = {'n' : 'rule r1 {strings: $a = /(L|K)[0-9A-Za-z]{51}/ condition: $a}'}) for task in bit_tasks: scanner = mac_yarascan.MapYaraScanner(task = task, rules = key_rule) for hit, address in scanner.scan(): content = scanner.address_space.zread(address, 52) if pyenc.is_valid_wif(content): secret_exp = pyenc.wif_to_secret_exponent(content) key = pykey.Key(secret_exponent = secret_exp,is_compressed=True) if key.address() not in addr_key.keys(): addr_key[key.address()] = content yield(content, key.address()) # addresses with no known keys for bit_addr in bit_addrs: if bit_addr not in addr_key.keys(): yield ("UNKNOWN", bit_addr)
def sign_tx(hex_tx, tx_input): """ Sign the transaction with private key :param hex_tx: :param tx_input: :return: """ logging.info('Signing tx with private key') transaction = Tx.from_hex(hex_tx) wif = wif_to_secret_exponent(helpers.import_key(), ALLOWABLE_WIF_PREFIXES) lookup = build_hash160_lookup([wif]) transaction.set_unspents([TxOut(coin_value=tx_input.coin_value, script=tx_input.script)]) signed_tx = transaction.sign(lookup) logging.info('Finished signing transaction') return signed_tx
def decrypt_message(message, my_private_key): my_private_integer = encoding.wif_to_secret_exponent(my_private_key) their_point = (message['point_x'], message['point_y']) key = create_common_key(their_point, my_private_integer) text = decrypt(key, message['ciphertext'], message['iv']) time_string = text[len(text) - 16:len(text)] try: time_reported = int(time_string) except: return '', False if time.time() - time_reported < time_threshold: return text[0:len(text) - 16], True else: print "message too late" return '', False
def decrypt_message(message, my_private_key): my_private_integer = encoding.wif_to_secret_exponent(my_private_key) their_point = (message['point_x'], message['point_y']) key = create_common_key(their_point, my_private_integer) text = decrypt(key, message['ciphertext'], message['iv']) time_string = text[len(text)-16:len(text)] try: time_reported = int(time_string) except: return '', False if time.time() - time_reported < time_threshold: return text[0:len(text)-16], True else: print "message too late" return '', False
def main(): parser = argparse.ArgumentParser(description="Create a Bitcoin transaction.") parser.add_argument('-s', "--source-address", help='source Bitcoin address', required=True, nargs="+", metavar='source_address') parser.add_argument('-d', "--destination-address", help='destination Bitcoin address/amount', required=True, metavar='dest_address/amount_in_btc', nargs="+") parser.add_argument('-f', "--wif-file", help='WIF items for source Bitcoin addresses', required=True, metavar="path-to-WIF-values", type=argparse.FileType('r')) args = parser.parse_args() total_value = 0 coins_from = [] for bca in args.source_address: coins_sources = blockchain_info.coin_sources_for_address(bca) coins_from.extend(coins_sources) total_value += sum(cs[-1].coin_value for cs in coins_sources) secret_exponents = [] for l in args.wif_file: print l secret_exponents.append(encoding.wif_to_secret_exponent(l[:-1])) coins_to = [] total_spent = 0 for daa in args.destination_address: address, amount = daa.split("/") amount = btc_to_satoshi(amount) total_spent += amount coins_to.append((amount, address)) actual_tx_fee = total_value - total_spent if actual_tx_fee < 0: print("not enough source coins (%s BTC) for destination (%s BTC). Short %s BTC" % (satoshi_to_btc(total_value), satoshi_to_btc(total_spent), satoshi_to_btc(-actual_tx_fee))) sys.exit(1) print("transaction fee: %s BTC" % satoshi_to_btc(actual_tx_fee)) unsigned_tx = UnsignedTx.standard_tx(coins_from, coins_to) solver = SecretExponentSolver(secret_exponents) new_tx = unsigned_tx.sign(solver) s = io.BytesIO() new_tx.stream(s) tx_bytes = s.getvalue() tx_hex = binascii.hexlify(tx_bytes).decode("utf8") recommended_tx_fee = tx_fee.recommended_fee_for_tx(new_tx) if actual_tx_fee > recommended_tx_fee: print("warning: transaction fee of exceeds expected value of %s BTC" % satoshi_to_btc(recommended_tx_fee)) elif actual_tx_fee < recommended_tx_fee: print("warning: transaction fee lower than (casually calculated) expected value of %s BTC, transaction might not propogate" % satoshi_to_btc(recommended_tx_fee)) print("copy the following hex to http://blockchain.info/pushtx to put the transaction on the network:\n") print(tx_hex)
def publish_data(data): data = POE_MARKER_BYTES + data if len(data) > OP_RETURN_MAX_DATA: return None, 'data too long for OP_RETURN: %s' % (data.encode('hex')) secret_exponent = wif_to_secret_exponent(PAYMENT_PRIVATE_KEY) _from = PAYMENT_ADDRESS unsigned_tx = construct_data_tx(data, _from) if type(unsigned_tx) == str: # error return (None, unsigned_tx) signed_tx = unsigned_tx.sign(SecretExponentSolver([secret_exponent])) raw_tx = tx2hex(signed_tx) txid, message = pushtxn(raw_tx) return txid, message
def write_message_for_address(text, their_address, my_private_key): try: my_private_integer = encoding.wif_to_secret_exponent(my_private_key) except: print 'invalid private key' my_private_integer = 'invalid' if not my_private_integer == 'invalid': their_pubkey = key_scraping.get_pubkey_on_address(their_address) if their_pubkey[1]==True: their_pubkey = their_pubkey[0] message = assemble_message(text, their_pubkey, my_private_integer) return message else: print "Cannot find their public key from Blockchain record" return '' else: return ''
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 write_message_for_address(text, their_address, my_private_key): try: my_private_integer = encoding.wif_to_secret_exponent(my_private_key) except: print 'invalid private key' my_private_integer = 'invalid' if not my_private_integer == 'invalid': their_pubkey = key_scraping.get_pubkey_on_address(their_address) if their_pubkey[1] == True: their_pubkey = their_pubkey[0] message = assemble_message(text, their_pubkey, my_private_integer) return message else: print "Cannot find their public key from Blockchain record" return '' else: return ''
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 createTransaction (self, outs, fee): # Create the signed transaction spendables = self._spendables (int (fee)) #print (spendables) if len (spendables) == 0: logger.error ('No spendables available') return None t = create_tx(spendables, [self.address], fee=int (fee)) for o in outs: t.txs_out.append (TxOut (0.0, tools.compile (o))) secret_exponent = wif_to_secret_exponent(self.wif, allowable_wif_prefixes=[wif_prefix_for_netcode (self.chain)]) d = {} d.update (build_hash160_lookup([secret_exponent])) t.sign (d) txhash = (t.as_hex ()) return txhash
def sign_tx(self, hex_tx, tx_input, netcode): """ Sign the transaction with private key :param hex_tx: :param tx_input: :param netcode: :return: """ logging.info('Signing tx with private key') self.secret_manager.start() wif = self.secret_manager.get_wif() transaction = Tx.from_hex(hex_tx) allowable_wif_prefixes = wif_prefix_for_netcode(netcode) se = wif_to_secret_exponent(wif, allowable_wif_prefixes) lookup = build_hash160_lookup([se]) transaction.set_unspents([TxOut(coin_value=tx_input.coin_value, script=tx_input.script)]) signed_tx = transaction.sign(lookup) self.secret_manager.stop() logging.info('Finished signing transaction') return signed_tx
def publish_data(data, unused_utxo): data = POE_MARKER_BYTES + data if len(data) > OP_RETURN_MAX_DATA: msg = 'data too long for OP_RETURN: %s' % (data.encode('hex')) ErrorNotification.new(msg) return None, msg _from = unused_utxo.address _private_key = PAYMENT_OBJ[_from][0] secret_exponent = wif_to_secret_exponent(_private_key) #mainnet unsigned_tx = construct_data_tx(data, _from, unused_utxo) if type(unsigned_tx) == str: # error msg = 'ERROR: type(unsigned_tx) == str' ErrorNotification.new(msg) return (None, unsigned_tx) solver = build_hash160_lookup([secret_exponent]) signed_tx = unsigned_tx.sign(solver) raw_tx = tx2hex(signed_tx) txid, message = pushtxn(raw_tx) return txid, message
def publish_data(data, unused_utxo): data = POE_MARKER_BYTES + data if len(data) > OP_RETURN_MAX_DATA: msg='data too long for OP_RETURN: %s' % (data.encode('hex')) ErrorNotification.new(msg) return None, msg _from = unused_utxo.address _private_key=PAYMENT_OBJ[_from][0] secret_exponent = wif_to_secret_exponent(_private_key) #mainnet unsigned_tx = construct_data_tx(data, _from, unused_utxo) if type(unsigned_tx) == str: # error msg='ERROR: type(unsigned_tx) == str' ErrorNotification.new(msg) return (None, unsigned_tx) solver = build_hash160_lookup([secret_exponent]) signed_tx = unsigned_tx.sign(solver) raw_tx = tx2hex(signed_tx) txid, message = pushtxn(raw_tx) return txid, message
def send(self, ddestination_address, dcolourid=None): self.colordata.update() coins_to = [] total_spent = 0 for daa in [ddestination_address]: address, amount = daa[0], daa[1] amount = btc_to_satoshi(amount) total_spent += amount coins_to.append((amount, address)) selected_utxos, total_value = self.selectUTXOs(self.getAllUTXOs(), dcolourid, total_spent) change = (total_value - total_spent) - 10000 if change >= 1: coins_to.append((change, self.addresses[0].pubkey)) coins_from = [utxo.get_pycoin_coin_source() for utxo in selected_utxos] secret_exponents = [ encoding.wif_to_secret_exponent(address.privkey) for address in self.addresses ] unsigned_tx = UnsignedTx.standard_tx(coins_from, coins_to) solver = SecretExponentSolver(secret_exponents) new_tx = unsigned_tx.sign(solver) s = io.BytesIO() new_tx.stream(s) tx_bytes = s.getvalue() tx_hex = binascii.hexlify(tx_bytes).decode("utf8") recommended_tx_fee = tx_fee.recommended_fee_for_tx(new_tx) print tx_hex URL = "http://blockchain.info/pushtx" urllib2.urlopen(URL, data=tx_hex)
def simple_sign (self, skeys): solver = OfflineAwareSolver([wif_to_secret_exponent(x) for x in skeys]) for idx, tx in enumerate(self.unsigned_txs_out): if tx.script == '': tx.script = solver.script_hash160[idx] return self.sign(solver, TxClass=ProxyTx)
def secret_exponents(testnet, wifs): valid_prefixes = [b'\xef' if testnet else b'\x80'] return list(map(lambda x: wif_to_secret_exponent(x, valid_prefixes), wifs))
def sign_transaction(self, transaction_to_sign): secret_exponent = wif_to_secret_exponent(self.wif, self.allowable_wif_prefixes) lookup = build_hash160_lookup([secret_exponent]) signed_transaction = transaction_to_sign.sign(lookup) return signed_transaction
fee = 10000 #satoshis. #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
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)