def parse_context(args, parser): network = network_for_netcode(args.network) tx_class = network.tx # we create the tx_db lazily tx_db = None if args.db: try: txs = [tx_class.from_hex(tx_hex) for tx_hex in args.db] except Exception: parser.error("can't parse ") the_ram_tx_db = dict((tx.hash(), tx) for tx in txs) if tx_db is None: tx_db = create_tx_db(network) tx_db.lookup_methods.append(the_ram_tx_db.get) # defaults txs = [] spendables = [] payables = [] key_iters = [] # there are a few warnings we might optionally print out, but only if # they are relevant. We don't want to print them out multiple times, so we # collect them here and print them at the end if they ever kick in. warning_spendables = None for arg in args.argument: tx, tx_db = parse_tx(tx_class, arg, parser, tx_db, network) if tx: txs.append(tx) continue if key_found(arg, payables, key_iters, network): continue if parse_parts(tx_class, arg, spendables, payables, network): continue payable = script_for_address_or_opcodes(network, arg) if payable is not None: payables.append((payable, 0)) continue parser.error("can't parse %s" % arg) parse_private_key_file(args, key_iters) if args.fetch_spendables: warning_spendables = message_about_spendables_for_address_env(args.network) for address in args.fetch_spendables: spendables.extend(spendables_for_address(address, args.network)) return (network, txs, spendables, payables, key_iters, tx_db, warning_spendables)
def parse_context(args, parser): # we create the tx_db lazily tx_db = None if args.db: the_ram_tx_db = dict((tx.hash(), tx) for tx in args.db) if tx_db is None: tx_db = create_tx_db(args.network) tx_db.lookup_methods.append(the_ram_tx_db.get) # defaults txs = [] spendables = [] payables = [] key_iters = [] # there are a few warnings we might optionally print out, but only if # they are relevant. We don't want to print them out multiple times, so we # collect them here and print them at the end if they ever kick in. warning_spendables = None for arg in args.argument: if is_address_valid( arg, allowable_netcodes=[args.network], allowable_types=["address", "pay_to_script", "segwit"]): payables.append((arg, 0)) continue if key_found(arg, payables, key_iters): continue tx, tx_db = parse_tx(arg, parser, tx_db, args.network) if tx: txs.append(tx) continue if parse_parts(arg, spendables, payables, args.network): continue parser.error("can't parse %s" % arg) parse_private_key_file(args, key_iters) if args.fetch_spendables: warning_spendables = message_about_spendables_for_address_env( args.network) for address in args.fetch_spendables: spendables.extend(spendables_for_address(address, args.network)) return (txs, spendables, payables, key_iters, tx_db, warning_spendables)
def fetch_unspent(args): netcode = get_current_netcode() m = message_about_spendables_for_address_env(netcode) if m: print("warning: %s" % m) for address in args.bitcoin_address: spendables = spendables_for_address(address, netcode, format="text") for spendable in spendables: print(spendable)
def get_unspent_outputs(address, netcode=CONFIG_NETCODE): """ Get unspent outputs at the address :param address: :param netcode: :return: """ spendables = spendables_for_address(bitcoin_address=address, netcode=netcode) if spendables: return sorted(spendables, key=lambda x: hash(x.coin_value)) return None
def get_unspent_outputs(self, address): """ Get unspent outputs at the address :param address: :return: """ spendables = spendables_for_address(bitcoin_address=address, netcode=self.netcode) if spendables: return sorted(spendables, key=lambda x: hash(x.coin_value)) return None
def getcoinBalance(address): spendables = spendables_for_address( address, 'BTC', format="dict") ##for spendable send to address provided by print(spendables) placeholder = 0 for myitem in spendables: if myitem['does_seem_spent'] == 0: placeholder = placeholder + myitem['coin_value'] placeholder = placeholder / 100000 return placeholder
def parse_context(args, parser): # we create the tx_db lazily tx_db = None if args.db: the_ram_tx_db = dict((tx.hash(), tx) for tx in args.db) if tx_db is None: tx_db = create_tx_db(args.network) tx_db.lookup_methods.append(the_ram_tx_db.get) # defaults txs = [] spendables = [] payables = [] key_iters = [] # there are a few warnings we might optionally print out, but only if # they are relevant. We don't want to print them out multiple times, so we # collect them here and print them at the end if they ever kick in. warning_spendables = None for arg in args.argument: if is_address_valid(arg, allowable_netcodes=[args.network], allowable_types=[ "address", "pay_to_script", "segwit"]): payables.append((arg, 0)) continue if key_found(arg, payables, key_iters): continue tx, tx_db = parse_tx(arg, parser, tx_db, args.network) if tx: txs.append(tx) continue if parse_parts(arg, spendables, payables, args.network): continue parser.error("can't parse %s" % arg) parse_private_key_file(args, key_iters) if args.fetch_spendables: warning_spendables = message_about_spendables_for_address_env(args.network) for address in args.fetch_spendables: spendables.extend(spendables_for_address(address, args.network)) return (txs, spendables, payables, key_iters, tx_db, warning_spendables)
def main(): parser = argparse.ArgumentParser( description="Create a hex dump of unspent TxOut items for Bitcoin addresses.") parser.add_argument("bitcoin_address", help='a bitcoin address', nargs="+") args = parser.parse_args() m = message_about_spendables_for_address_env() if m: print("warning: %s" % m) for address in args.bitcoin_address: spendables = spendables_for_address(address, format="text") for spendable in spendables: print(spendable)
def main(): parser = argparse.ArgumentParser( description= "Create a hex dump of unspent TxOut items for Bitcoin addresses.") parser.add_argument("bitcoin_address", help='a bitcoin address', nargs="+") args = parser.parse_args() m = message_about_spendables_for_address_env() if m: print("warning: %s" % m) for address in args.bitcoin_address: spendables = spendables_for_address(address, format="text") for spendable in spendables: print(spendable)
def processSendBitcoin(fromPrivateKey, toPublicKey, amountOfBitcoin): bcip = BlockchainInfoProvider("BTC") amountOfSatoshi = int(amountOfBitcoin * 100000000) spendables = spendables_for_address(wif2address(fromPrivateKey), "BTC") try: tx = create_signed_tx(spendables, [(toPublicKey, amountOfSatoshi), wif2address(fromPrivateKey)], [fromPrivateKey], tx_fee.TX_FEE_PER_THOUSAND_BYTES) except Exception as e: print "could not build transaction." print e return False try: bcip.broadcast_tx(tx) print "tx broadcasted: ", tx.id() return tx.id() except: print "tx failed to be broadcasted" return False
def createTx(self): # address = self.fromaddress.text() # destination = self.sendto.text() address = "mti8znMQPkP9LnPcce7i3LQRuSGZ38PVPV" destination = "ms4cSWpPGb6tBzbBXNuBwsarg1SNYvkjxg" #あらかじめ送信元アドレスに対応する秘密鍵を入力しておく wif = "cNJm4inEA9xreDHntBB9gAFj8V6aSn9sqdVgDdJJGrN9Ys8b8vzD" sndtx = BlockchainInfoProvider('blockr.io') print("before") assert is_valid_wif(wif) print("after") spendables = spendables_for_address(address, "BTC") tx = create_signed_tx(spendables, payables=[destination], wifs=[wif]) sndtx.broadcast_tx(tx) self.transaction.setText(tx.as_hex())
def parse_context(args, parser): # defaults txs = [] spendables = [] payables = [] key_iters = [] TX_ID_RE = re.compile(r"^[0-9a-fA-F]{64}$") # there are a few warnings we might optionally print out, but only if # they are relevant. We don't want to print them out multiple times, so we # collect them here and print them at the end if they ever kick in. warning_tx_cache = None warning_tx_for_tx_hash = None warning_spendables = None if args.private_key_file: wif_re = re.compile(r"[1-9a-km-zA-LMNP-Z]{51,111}") # address_re = re.compile(r"[1-9a-kmnp-zA-KMNP-Z]{27-31}") for f in args.private_key_file: if f.name.endswith(".gpg"): gpg_args = ["gpg", "-d"] if args.gpg_argument: gpg_args.extend(args.gpg_argument.split()) gpg_args.append(f.name) popen = subprocess.Popen(gpg_args, stdout=subprocess.PIPE) f = popen.stdout for line in f.readlines(): # decode if isinstance(line, bytes): line = line.decode("utf8") # look for WIFs possible_keys = wif_re.findall(line) def make_key(x): try: return Key.from_text(x) except Exception: return None keys = [make_key(x) for x in possible_keys] for key in keys: if key: key_iters.append((k.wif() for k in key.subkeys(""))) # if len(keys) == 1 and key.hierarchical_wallet() is None: # # we have exactly 1 WIF. Let's look for an address # potential_addresses = address_re.findall(line) # update p2sh_lookup p2sh_lookup = {} if args.pay_to_script: for p2s in args.pay_to_script: try: script = h2b(p2s) p2sh_lookup[hash160(script)] = script except Exception: print("warning: error parsing pay-to-script value %s" % p2s) if args.pay_to_script_file: hex_re = re.compile(r"[0-9a-fA-F]+") for f in args.pay_to_script_file: count = 0 for l in f: try: m = hex_re.search(l) if m: p2s = m.group(0) script = h2b(p2s) p2sh_lookup[hash160(script)] = script count += 1 except Exception: print("warning: error parsing pay-to-script file %s" % f.name) if count == 0: print("warning: no scripts found in %s" % f.name) # we create the tx_db lazily tx_db = None for arg in args.argument: # hex transaction id if TX_ID_RE.match(arg): if tx_db is None: warning_tx_cache = message_about_tx_cache_env() warning_tx_for_tx_hash = message_about_tx_for_tx_hash_env( args.network) tx_db = get_tx_db(args.network) tx = tx_db.get(h2b_rev(arg)) if not tx: for m in [ warning_tx_cache, warning_tx_for_tx_hash, warning_spendables ]: if m: print("warning: %s" % m, file=sys.stderr) parser.error("can't find Tx with id %s" % arg) txs.append(tx) continue # hex transaction data try: tx = Tx.from_hex(arg) txs.append(tx) continue except Exception: pass is_valid = is_address_valid(arg, allowable_netcodes=[args.network]) if is_valid: payables.append((arg, 0)) continue try: key = Key.from_text(arg) # TODO: check network if key.wif() is None: payables.append((key.address(), 0)) continue # TODO: support paths to subkeys key_iters.append((k.wif() for k in key.subkeys(""))) continue except Exception: pass if os.path.exists(arg): try: with open(arg, "rb") as f: if f.name.endswith("hex"): f = io.BytesIO(codecs.getreader("hex_codec")(f).read()) tx = Tx.parse(f) txs.append(tx) try: tx.parse_unspents(f) except Exception as ex: pass continue except Exception: pass parts = arg.split("/") if len(parts) == 4: # spendable try: spendables.append(Spendable.from_text(arg)) continue except Exception: pass if len(parts) == 2 and is_address_valid( parts[0], allowable_netcodes=[args.network]): try: payables.append(parts) continue except ValueError: pass parser.error("can't parse %s" % arg) if args.fetch_spendables: warning_spendables = message_about_spendables_for_address_env( args.network) for address in args.fetch_spendables: spendables.extend(spendables_for_address(address)) for tx in txs: if tx.missing_unspents() and args.augment: if tx_db is None: warning_tx_cache = message_about_tx_cache_env() warning_tx_for_tx_hash = message_about_tx_for_tx_hash_env( args.network) tx_db = get_tx_db(args.network) tx.unspents_from_db(tx_db, ignore_missing=True) return (txs, spendables, payables, key_iters, p2sh_lookup, tx_db, warning_tx_cache, warning_tx_for_tx_hash, warning_spendables)
def process(request): if request.method == 'POST': # auto deposit function if request.POST.get('VERY_LONG_RANDOM_STRING'): account_record = AccountModel.objects.create( return_address=chikun_address) account_record.save() deposit_address = master_public_key.subkey( account_record.id).address() return HttpResponse(deposit_address) response = system('ping -c 1 -w 3 %s > /dev/null 2>&1' % hostname) if request.POST.get('v_key') == v_key and response == 0: # check balance stats for all balance 0's zero_list = AccountModel.objects.filter(balance=0) if zero_list.exists(): for i in zero_list: address = master_public_key.subkey(i.id).address() try: balance = Decimal( urlopen( 'https://%s/q/addressbalance/%s?confirmations=%s&api_code=%s' % (hostname, address, confirmations, api_code)).read()) / 100000000 # REMOTE except Exception as e: lf = open('logFile', 'a') print('try one: ', end='') print(e, file=lf) lf.close() return HttpResponse(status=204) if balance >= Decimal('0.001'): i.balance = balance i.checked += 1 i.save() # match valid accounts and make payments nonzero_list = AccountModel.objects.filter( balance__gt=0).order_by('?') if len(nonzero_list) > 1: v = True limit = len(nonzero_list) / 2 if not len( nonzero_list) % 2 else (len(nonzero_list) - 1) / 2 nonzero_list = nonzero_list[:limit * 2] else: v = False if v: slice_one = nonzero_list[:limit] slice_two = nonzero_list[limit:] c = 0 while c < limit: if not slice_one[c].balance == slice_two[c].balance: (winner, loser) = ( slice_one[c], slice_two[c] ) if slice_one[c].balance > slice_two[c].balance else ( slice_two[c], slice_one[c]) winner_key = Key.from_text( request.POST['private_key']).subkey(winner.id) loser_key = Key.from_text( request.POST['private_key']).subkey(loser.id) try: spendables = spendables_for_address( '%s&api_code=%s' % (winner_key.address(), api_code)) + spendables_for_address( '%s&api_code=%s' % (loser_key.address(), api_code)) signed_tx = create_signed_tx( spendables, [(chikun_address, int((loser.balance * vig) * 100000000)), winner.return_address], wifs=[winner_key.wif(), loser_key.wif()], fee="standard") pushtx(signed_tx.as_hex()) ResultModel.objects.create( winning_address=winner_key.address(), winning_deposit=str(winner.balance), losing_address=loser_key.address(), losing_deposit=str(loser.balance), txid=signed_tx.id()).save() for i in (winner, loser): ArchiveModel.objects.create( **AccountModel.objects.filter( id=i.id).values()[0]).save() AccountModel.objects.filter(id=i.id).delete() except Exception as e: lf = open('logFile', 'a') print('try two: ', end='') print(e, file=lf) lf.close() for i in (winner, loser): BrokenModel.objects.create( **AccountModel.objects.filter( id=i.id).values()[0]).save() AccountModel.objects.filter(id=i.id).delete() c += 1 # remove invalid accounts invalid_accounts = AccountModel.objects.filter( checked__gt=24).filter(balance=0) # four hours if invalid_accounts.exists(): for i in invalid_accounts: InvalidModel.objects.create(**AccountModel.objects.filter( id=i.id).values()[0]).save() AccountModel.objects.filter(id=i.id).delete() return HttpResponse(status=204) return HttpResponse( '<h1>Not Found</h1><p>The requested URL /with was not found on this server.</p>', status=404)
def main(): parser = argparse.ArgumentParser( description="Manipulate bitcoin (or alt coin) transactions.", epilog=EPILOG) parser.add_argument('-t', "--transaction-version", type=int, help='Transaction version, either 1 (default) or 3 (not yet supported).') parser.add_argument('-l', "--lock-time", type=parse_locktime, help='Lock time; either a block' 'index, or a date/time (example: "2014-01-01T15:00:00"') parser.add_argument('-n', "--network", default="BTC", help='Define network code (M=Bitcoin mainnet, T=Bitcoin testnet).') parser.add_argument('-a', "--augment", action='store_true', help='augment tx by adding any missing spendable metadata by fetching' ' inputs from cache and/or web services') parser.add_argument("-i", "--fetch-spendables", metavar="address", action="append", help='Add all unspent spendables for the given bitcoin address. This information' ' is fetched from web services.') parser.add_argument('-f', "--private-key-file", metavar="path-to-private-keys", action="append", help='file containing WIF or BIP0032 private keys. If file name ends with .gpg, ' '"gpg -d" will be invoked automatically. File is read one line at a time, and if ' 'the file contains only one WIF per line, it will also be scanned for a bitcoin ' 'address, and any addresses found will be assumed to be public keys for the given' ' private key.', type=argparse.FileType('r')) parser.add_argument('-g', "--gpg-argument", help='argument to pass to gpg (besides -d).', default='') parser.add_argument("--remove-tx-in", metavar="tx_in_index_to_delete", action="append", type=int, help='remove a tx_in') parser.add_argument("--remove-tx-out", metavar="tx_out_index_to_delete", action="append", type=int, help='remove a tx_out') parser.add_argument('-F', "--fee", help='fee, in satoshis, to pay on transaction, or ' '"standard" to auto-calculate. This is only useful if the "split pool" ' 'is used; otherwise, the fee is automatically set to the unclaimed funds.', default="standard", metavar="transaction-fee", type=parse_fee) parser.add_argument('-C', "--cache", help='force the resultant transaction into the transaction cache.' ' Mostly for testing.', action='store_true'), parser.add_argument('-u', "--show-unspents", action='store_true', help='show TxOut items for this transaction in Spendable form.') parser.add_argument('-b', "--bitcoind-url", help='URL to bitcoind instance to validate against (http://user:pass@host:port).') parser.add_argument('-o', "--output-file", metavar="path-to-output-file", type=argparse.FileType('wb'), help='file to write transaction to. This supresses most other output.') parser.add_argument("argument", nargs="+", help='generic argument: can be a hex transaction id ' '(exactly 64 characters) to be fetched from cache or a web service;' ' a transaction as a hex string; a path name to a transaction to be loaded;' ' a spendable 4-tuple of the form tx_id/tx_out_idx/script_hex/satoshi_count ' 'to be added to TxIn list; an address/satoshi_count to be added to the TxOut ' 'list; an address to be added to the TxOut list and placed in the "split' ' pool".') args = parser.parse_args() # defaults txs = [] spendables = [] payables = [] key_iters = [] TX_ID_RE = re.compile(r"^[0-9a-fA-F]{64}$") # there are a few warnings we might optionally print out, but only if # they are relevant. We don't want to print them out multiple times, so we # collect them here and print them at the end if they ever kick in. warning_tx_cache = None warning_get_tx = None warning_spendables = None if args.private_key_file: wif_re = re.compile(r"[1-9a-km-zA-LMNP-Z]{51,111}") # address_re = re.compile(r"[1-9a-kmnp-zA-KMNP-Z]{27-31}") for f in args.private_key_file: if f.name.endswith(".gpg"): gpg_args = ["gpg", "-d"] if args.gpg_argument: gpg_args.extend(args.gpg_argument.split()) gpg_args.append(f.name) popen = subprocess.Popen(gpg_args, stdout=subprocess.PIPE) f = popen.stdout for line in f.readlines(): # decode if isinstance(line, bytes): line = line.decode("utf8") # look for WIFs possible_keys = wif_re.findall(line) def make_key(x): try: return Key.from_text(x) except Exception: return None keys = [make_key(x) for x in possible_keys] for key in keys: if key: key_iters.append((k.wif() for k in key.subkeys(""))) # if len(keys) == 1 and key.hierarchical_wallet() is None: # # we have exactly 1 WIF. Let's look for an address # potential_addresses = address_re.findall(line) # we create the tx_db lazily tx_db = None for arg in args.argument: # hex transaction id if TX_ID_RE.match(arg): if tx_db is None: warning_tx_cache = message_about_tx_cache_env() warning_get_tx = message_about_get_tx_env() tx_db = get_tx_db() tx = tx_db.get(h2b_rev(arg)) if not tx: for m in [warning_tx_cache, warning_get_tx, warning_spendables]: if m: print("warning: %s" % m, file=sys.stderr) parser.error("can't find Tx with id %s" % arg) txs.append(tx) continue # hex transaction data try: tx = Tx.tx_from_hex(arg) txs.append(tx) continue except Exception: pass try: key = Key.from_text(arg) # TODO: check network if key.wif() is None: payables.append((key.address(), 0)) continue # TODO: support paths to subkeys key_iters.append((k.wif() for k in key.subkeys(""))) continue except Exception: pass if os.path.exists(arg): try: with open(arg, "rb") as f: if f.name.endswith("hex"): f = io.BytesIO(codecs.getreader("hex_codec")(f).read()) tx = Tx.parse(f) txs.append(tx) try: tx.parse_unspents(f) except Exception as ex: pass continue except Exception: pass parts = arg.split("/") if len(parts) == 4: # spendable try: spendables.append(Spendable.from_text(arg)) continue except Exception: pass # TODO: fix allowable_prefixes allowable_prefixes = b'\0' if len(parts) == 2 and encoding.is_valid_bitcoin_address( parts[0], allowable_prefixes=allowable_prefixes): try: payables.append(parts) continue except ValueError: pass parser.error("can't parse %s" % arg) if args.fetch_spendables: warning_spendables = message_about_spendables_for_address_env() for address in args.fetch_spendables: spendables.extend(spendables_for_address(address)) for tx in txs: if tx.missing_unspents() and args.augment: if tx_db is None: warning_tx_cache = message_about_tx_cache_env() warning_get_tx = message_about_get_tx_env() tx_db = get_tx_db() tx.unspents_from_db(tx_db, ignore_missing=True) txs_in = [] txs_out = [] unspents = [] # we use a clever trick here to keep each tx_in corresponding with its tx_out for tx in txs: smaller = min(len(tx.txs_in), len(tx.txs_out)) txs_in.extend(tx.txs_in[:smaller]) txs_out.extend(tx.txs_out[:smaller]) unspents.extend(tx.unspents[:smaller]) for tx in txs: smaller = min(len(tx.txs_in), len(tx.txs_out)) txs_in.extend(tx.txs_in[smaller:]) txs_out.extend(tx.txs_out[smaller:]) unspents.extend(tx.unspents[smaller:]) for spendable in spendables: txs_in.append(spendable.tx_in()) unspents.append(spendable) for address, coin_value in payables: script = standard_tx_out_script(address) txs_out.append(TxOut(coin_value, script)) lock_time = args.lock_time version = args.transaction_version # if no lock_time is explicitly set, inherit from the first tx or use default if lock_time is None: if txs: lock_time = txs[0].lock_time else: lock_time = DEFAULT_LOCK_TIME # if no version is explicitly set, inherit from the first tx or use default if version is None: if txs: version = txs[0].version else: version = DEFAULT_VERSION if args.remove_tx_in: s = set(args.remove_tx_in) txs_in = [tx_in for idx, tx_in in enumerate(txs_in) if idx not in s] if args.remove_tx_out: s = set(args.remove_tx_out) txs_out = [tx_out for idx, tx_out in enumerate(txs_out) if idx not in s] tx = Tx(txs_in=txs_in, txs_out=txs_out, lock_time=lock_time, version=version, unspents=unspents) fee = args.fee try: distribute_from_split_pool(tx, fee) except ValueError as ex: print("warning: %s" % ex.args[0], file=sys.stderr) unsigned_before = tx.bad_signature_count() if unsigned_before > 0 and key_iters: def wif_iter(iters): while len(iters) > 0: for idx, iter in enumerate(iters): try: wif = next(iter) yield wif except StopIteration: iters = iters[:idx] + iters[idx+1:] break print("signing...", file=sys.stderr) sign_tx(tx, wif_iter(key_iters)) unsigned_after = tx.bad_signature_count() if unsigned_after > 0 and key_iters: print("warning: %d TxIn items still unsigned" % unsigned_after, file=sys.stderr) if len(tx.txs_in) == 0: print("warning: transaction has no inputs", file=sys.stderr) if len(tx.txs_out) == 0: print("warning: transaction has no outputs", file=sys.stderr) include_unspents = (unsigned_after > 0) tx_as_hex = tx.as_hex(include_unspents=include_unspents) if args.output_file: f = args.output_file if f.name.endswith(".hex"): f.write(tx_as_hex.encode("utf8")) else: tx.stream(f) if include_unspents: tx.stream_unspents(f) f.close() elif args.show_unspents: for spendable in tx.tx_outs_as_spendable(): print(spendable.as_text()) else: if not tx.missing_unspents(): check_fees(tx) dump_tx(tx, args.network) if include_unspents: print("including unspents in hex dump since transaction not fully signed") print(tx_as_hex) if args.cache: if tx_db is None: warning_tx_cache = message_about_tx_cache_env() warning_get_tx = message_about_get_tx_env() tx_db = get_tx_db() tx_db.put(tx) if args.bitcoind_url: if tx_db is None: warning_tx_cache = message_about_tx_cache_env() warning_get_tx = message_about_get_tx_env() tx_db = get_tx_db() validate_bitcoind(tx, tx_db, args.bitcoind_url) if tx.missing_unspents(): print("\n** can't validate transaction as source transactions missing", file=sys.stderr) else: try: if tx_db is None: warning_tx_cache = message_about_tx_cache_env() warning_get_tx = message_about_get_tx_env() tx_db = get_tx_db() tx.validate_unspents(tx_db) print('all incoming transaction values validated') except BadSpendableError as ex: print("\n**** ERROR: FEES INCORRECTLY STATED: %s" % ex.args[0], file=sys.stderr) except Exception as ex: print("\n*** can't validate source transactions as untampered: %s" % ex.args[0], file=sys.stderr) # print warnings for m in [warning_tx_cache, warning_get_tx, warning_spendables]: if m: print("warning: %s" % m, file=sys.stderr)
#spendable_for_address requires netcode. #https://github.com/richardkiss/pycoin/issues/193 def get_net_code(which): while 1: print("enter the %s => " % which, end='') netcode = input() if netcode: print(netcode) return netcode print("invalid netcode, please try again") src_address = get_address("source") netcode = get_net_code("netcode") spendables = spendables_for_address(src_address, netcode) print(spendables) while 1: print("enter the WIF for %s=> " % src_address, end='') wif = input() is_valid = is_wif_valid(wif) if is_valid: break print("invalid wif, please try again") key = Key.from_text(wif) if src_address not in (key.address(use_uncompressed=False), key.address(use_uncompressed=True)): print("** WIF doesn't correspond to %s" % src_address) print("The secret exponent is %d" % key.secret_exponent())
def parse_context(args, parser): # defaults txs = [] spendables = [] payables = [] key_iters = [] TX_ID_RE = re.compile(r"^[0-9a-fA-F]{64}$") # there are a few warnings we might optionally print out, but only if # they are relevant. We don't want to print them out multiple times, so we # collect them here and print them at the end if they ever kick in. warning_tx_cache = None warning_tx_for_tx_hash = None warning_spendables = None if args.private_key_file: wif_re = re.compile(r"[1-9a-km-zA-LMNP-Z]{51,111}") # address_re = re.compile(r"[1-9a-kmnp-zA-KMNP-Z]{27-31}") for f in args.private_key_file: if f.name.endswith(".gpg"): gpg_args = ["gpg", "-d"] if args.gpg_argument: gpg_args.extend(args.gpg_argument.split()) gpg_args.append(f.name) popen = subprocess.Popen(gpg_args, stdout=subprocess.PIPE) f = popen.stdout for line in f.readlines(): # decode if isinstance(line, bytes): line = line.decode("utf8") # look for WIFs possible_keys = wif_re.findall(line) def make_key(x): try: return Key.from_text(x) except Exception: return None keys = [make_key(x) for x in possible_keys] for key in keys: if key: key_iters.append((k.wif() for k in key.subkeys(""))) # if len(keys) == 1 and key.hierarchical_wallet() is None: # # we have exactly 1 WIF. Let's look for an address # potential_addresses = address_re.findall(line) # update p2sh_lookup p2sh_lookup = {} if args.pay_to_script: for p2s in args.pay_to_script: try: script = h2b(p2s) p2sh_lookup[hash160(script)] = script except Exception: print("warning: error parsing pay-to-script value %s" % p2s) if args.pay_to_script_file: hex_re = re.compile(r"[0-9a-fA-F]+") for f in args.pay_to_script_file: count = 0 for l in f: try: m = hex_re.search(l) if m: p2s = m.group(0) script = h2b(p2s) p2sh_lookup[hash160(script)] = script count += 1 except Exception: print("warning: error parsing pay-to-script file %s" % f.name) if count == 0: print("warning: no scripts found in %s" % f.name) # we create the tx_db lazily tx_db = None for arg in args.argument: # hex transaction id if TX_ID_RE.match(arg): if tx_db is None: warning_tx_cache = message_about_tx_cache_env() warning_tx_for_tx_hash = message_about_tx_for_tx_hash_env(args.network) tx_db = get_tx_db(args.network) tx = tx_db.get(h2b_rev(arg)) if not tx: for m in [warning_tx_cache, warning_tx_for_tx_hash, warning_spendables]: if m: print("warning: %s" % m, file=sys.stderr) parser.error("can't find Tx with id %s" % arg) txs.append(tx) continue # hex transaction data try: tx = Tx.from_hex(arg) txs.append(tx) continue except Exception: pass is_valid = is_address_valid(arg, allowable_netcodes=[args.network]) if is_valid: payables.append((arg, 0)) continue try: key = Key.from_text(arg) # TODO: check network if key.wif() is None: payables.append((key.address(), 0)) continue # TODO: support paths to subkeys key_iters.append((k.wif() for k in key.subkeys(""))) continue except Exception: pass if os.path.exists(arg): try: with open(arg, "rb") as f: if f.name.endswith("hex"): f = io.BytesIO(codecs.getreader("hex_codec")(f).read()) tx = Tx.parse(f) txs.append(tx) try: tx.parse_unspents(f) except Exception as ex: pass continue except Exception: pass parts = arg.split("/") if len(parts) == 4: # spendable try: spendables.append(Spendable.from_text(arg)) continue except Exception: pass if len(parts) == 2 and is_address_valid(parts[0], allowable_netcodes=[args.network]): try: payables.append(parts) continue except ValueError: pass parser.error("can't parse %s" % arg) if args.fetch_spendables: warning_spendables = message_about_spendables_for_address_env(args.network) for address in args.fetch_spendables: spendables.extend(spendables_for_address(address)) for tx in txs: if tx.missing_unspents() and args.augment: if tx_db is None: warning_tx_cache = message_about_tx_cache_env() warning_tx_for_tx_hash = message_about_tx_for_tx_hash_env(args.network) tx_db = get_tx_db(args.network) tx.unspents_from_db(tx_db, ignore_missing=True) return (txs, spendables, payables, key_iters, p2sh_lookup, tx_db, warning_tx_cache, warning_tx_for_tx_hash, warning_spendables)
from pycoin.services import spendables_for_address from pycoin.tx.tx_utils import create_signed_tx def get_address(which): while 1: print("enter the %s address=> " % which, end='') address = input() is_valid = is_address_valid(address) if is_valid: return address print("invalid address, please try again") src_address = get_address("source") spendables = spendables_for_address(src_address) print(spendables) while 1: print("enter the WIF for %s=> " % src_address, end='') wif = input() is_valid = is_wif_valid(wif) if is_valid: break print("invalid wif, please try again") key = Key.from_text(wif) if src_address not in (key.address(use_uncompressed=False), key.address(use_uncompressed=True)): print("** WIF doesn't correspond to %s" % src_address) print("The secret exponent is %d" % key.secret_exponent())
def parse_context(args, parser): network = network_for_netcode(args.network) tx_class = network.tx # defaults spendables = [] payables = [] # we create the tx_db lazily tx_db = None if args.db: try: txs = [tx_class.from_hex(tx_hex) for tx_hex in args.db or []] except Exception: parser.error("can't parse ") the_ram_tx_db = dict((tx.hash(), tx) for tx in txs) if tx_db is None: tx_db = create_tx_db(network) tx_db.lookup_methods.append(the_ram_tx_db.get) txs = [] if args.coinbase: coinbase_tx = build_coinbase_tx(network, args.coinbase) txs.append(coinbase_tx) keychain = network.keychain(sqlite3.connect(args.keychain)) # there are a few warnings we might optionally print out, but only if # they are relevant. We don't want to print them out multiple times, so we # collect them here and print them at the end if they ever kick in. warning_spendables = None for arg in args.argument: tx, tx_db = parse_tx(tx_class, arg, parser, tx_db, network) if tx: txs.append(tx) continue if key_found(arg, keychain, args.key_paths, network): continue if parse_parts(tx_class, arg, spendables, payables, network): continue payable = script_for_address_or_opcodes(network, arg) if payable is not None: payables.append((payable, 0)) continue parser.error("can't parse %s" % arg) parse_private_key_file(args, keychain, network) if args.fetch_spendables: warning_spendables = message_about_spendables_for_address_env(args.network) for address in args.fetch_spendables: spendables.extend(spendables_for_address(address, args.network)) return (network, txs, spendables, payables, keychain, tx_db, warning_spendables)
def process(request): if request.method == 'POST': # auto deposit function if request.POST.get('VERY_LONG_RANDOM_STRING'): account_record = AccountModel.objects.create(return_address=chikun_address) account_record.save() deposit_address = master_public_key.subkey(account_record.id).address() return HttpResponse(deposit_address) response = system('ping -c 1 -w 3 %s > /dev/null 2>&1' % hostname) if request.POST.get('v_key') == v_key and response == 0: # check balance stats for all balance 0's zero_list = AccountModel.objects.filter(balance=0) if zero_list.exists(): for i in zero_list: address = master_public_key.subkey(i.id).address() try: balance = Decimal(urlopen('https://%s/q/addressbalance/%s?confirmations=%s&api_code=%s' % (hostname, address, confirmations, api_code)).read()) / 100000000 # REMOTE except Exception as e: lf = open('logFile', 'a') print('try one: ', end='') print(e, file=lf) lf.close() return HttpResponse(status=204) if balance >= Decimal('0.001'): i.balance = balance i.checked += 1 i.save() # match valid accounts and make payments nonzero_list = AccountModel.objects.filter(balance__gt=0).order_by('?') if len(nonzero_list) > 1: v = True limit = len(nonzero_list) / 2 if not len(nonzero_list) % 2 else (len(nonzero_list) - 1) / 2 nonzero_list = nonzero_list[:limit * 2] else: v = False if v: slice_one = nonzero_list[:limit] slice_two = nonzero_list[limit:] c = 0 while c < limit: if not slice_one[c].balance == slice_two[c].balance: (winner, loser) = (slice_one[c], slice_two[c]) if slice_one[c].balance > slice_two[c].balance else (slice_two[c], slice_one[c]) winner_key = Key.from_text(request.POST['private_key']).subkey(winner.id) loser_key = Key.from_text(request.POST['private_key']).subkey(loser.id) try: spendables = spendables_for_address('%s&api_code=%s' % (winner_key.address(), api_code)) + spendables_for_address('%s&api_code=%s' % (loser_key.address(), api_code)) signed_tx = create_signed_tx(spendables, [(chikun_address, int((loser.balance * vig) * 100000000)), winner.return_address], wifs=[winner_key.wif(), loser_key.wif()], fee="standard") pushtx(signed_tx.as_hex()) ResultModel.objects.create(winning_address=winner_key.address(), winning_deposit=str(winner.balance), losing_address=loser_key.address(), losing_deposit=str(loser.balance), txid=signed_tx.id()).save() for i in (winner, loser): ArchiveModel.objects.create(**AccountModel.objects.filter(id=i.id).values()[0]).save() AccountModel.objects.filter(id=i.id).delete() except Exception as e: lf = open('logFile', 'a') print('try two: ', end='') print(e, file=lf) lf.close() for i in (winner, loser): BrokenModel.objects.create(**AccountModel.objects.filter(id=i.id).values()[0]).save() AccountModel.objects.filter(id=i.id).delete() c += 1 # remove invalid accounts invalid_accounts = AccountModel.objects.filter(checked__gt=24).filter(balance=0) # four hours if invalid_accounts.exists(): for i in invalid_accounts: InvalidModel.objects.create(**AccountModel.objects.filter(id=i.id).values()[0]).save() AccountModel.objects.filter(id=i.id).delete() return HttpResponse(status=204) return HttpResponse('<h1>Not Found</h1><p>The requested URL /with was not found on this server.</p>', status=404)
parser.add_argument('--send-all-to', help='where to send all the money at this address', default='1MaxKayeQg4YhFkzFz4x6NDeeNv1bwKKVA', type=str) args = parser.parse_args() key_bytes = unhexlify(args.privkey_bytes.encode() ) if args.privkey_bytes != '' else os.urandom(32) private_key = Key(secret_exponent=int.from_bytes(key_bytes, 'big')) address = private_key.address() print('Your Bitcoin address is...', address) print('Your --privkey-bytes', hexlify(key_bytes).decode()) try: spendables = spendables_for_address(address, None) print('Spending', spendables) except HTTPError as e: print( 'Blockchain throws a 500 error if there are no spendables. Try sending some coins to', address, 'and try again. Remeber to copy privkey-bytes.') sys.exit() tx = create_tx(spendables, [args.send_all_to]) print('TX created:', repr(tx)) sign_tx(tx, [private_key.wif(False), private_key.wif(True)]) print('Final TX:', tx) # print('TX Send Attempt:', send_tx(tx)) '''
from pycoin.key.validate import is_address_valid, is_wif_valid from pycoin.services import spendables_for_address from pycoin.tx.tx_utils import create_signed_tx def get_address(which): while 1: print "enter the %s address=>"%which, address=input(); is_valid=is_address_valid(address) if is_valid: return address print 'invalid address, please try again' src_address=get_address("source") spendables=spendables_for_address(src_address) print spendables while 1: print "enter the WIF for %s" %src_address, wif=input() is_valid=is_wif_valid(wif) if is_valid: break print("invalid wif, please try again") key = key.from_text(wif) if src_address not in (key.address(use_uncompressed=False), key.address(use_uncompressed=True)): print("**WIF doesn't correspond to %s" %src_address) print("The secret exponent is %d"%key.secret_exponent())
print("") script_encoded = ScriptMultisig(n=2, sec_keys=[key.sec() for key in sub_bip32_nodes]).script() script = b2h(script_encoded) print("Script:") print(script) print("") address = address_for_pay_to_script(script_encoded) # 3Bi36w9RZHmibi1ip7ud9dvtpDt59ij7GC print("Address: %s" % address) print("") spendables = spendables_for_address(address) # UTXOs of address # The simplest transaction: all the UTXOs, less the fees, go to the address. tx = create_tx(spendables,["3977Lp7VNWY5L8hY5W2oaNjeR5r8FZ6ban"], fee="standard") # raw hex not-signed transaction tx.as_hex() # to sign the transaction I need the sub_private keys print("Transaction as Hex:") print(tx.as_hex(tx)) print("") # My Extended private subkeys subBip32PrivateNodes = [BIP32Node.subkey_for_path(Key.from_text(private_wallets[i]), chainPaths[i]) for i in range(len(private_wallets))] # subnodes