def post(self): db_updated = yield tornado.gen.Task(is_db_updated) bitcoin_updated = yield tornado.gen.Task(is_bitcoin_updated) version_updated = yield tornado.gen.Task(is_version_updated) block_count_db, block_count_bitcoin = yield tornado.gen.Task(get_status) info = None error = None bets = util.get_bets(db, order_by='tx_index', validity='valid') bets = bet_tuples(bets[:100]) my_bets = [] supply = util.devise(db, util.cha_supply(db), 'CHA', 'output') max_profit = float(supply)*config.MAX_PROFIT if self.get_argument("form")=="roll" and self.get_argument("source") and self.get_argument("bet") and self.get_argument("payout") and self.get_argument("chance"): source = self.get_argument("source") bet_amount = util.devise(db, self.get_argument("bet"), 'CHA', 'input') chance = util.devise(db, self.get_argument("chance"), 'value', 'input') payout = util.devise(db, self.get_argument("payout"), 'value', 'input') try: tx_hex = bet.create(db, source, bet_amount, chance, payout, unsigned=False) bitcoin.transmit(tx_hex, ask=False) info = "Thanks for betting!" except: error = sys.exc_info()[1] elif self.get_argument("form")=="my_bets" and self.get_argument("address"): try: my_bets = util.get_bets(db, source = self.get_argument("address"), order_by='tx_index', validity='valid') my_bets = bet_tuples(my_bets) except: my_bets = [] self.render("casino.html", db_updated = db_updated, bitcoin_updated = bitcoin_updated, version_updated = version_updated, bets = bets, my_bets = my_bets, supply = supply, house_edge = config.HOUSE_EDGE, max_profit = max_profit, info = info, error = error, block_count_db = block_count_db, block_count_bitcoin = block_count_bitcoin)
def post(self): db_updated = yield tornado.gen.Task(is_db_updated) bitcoin_updated = yield tornado.gen.Task(is_bitcoin_updated) version_updated = yield tornado.gen.Task(is_version_updated) block_count_db, block_count_bitcoin = yield tornado.gen.Task( get_status) info = None error = None bets = util.get_bets(db, order_by='tx_index', validity='valid') bets = bet_tuples(bets[:100]) my_bets = [] supply = util.devise(db, util.cha_supply(db), 'CHA', 'output') max_profit = float(supply) * config.MAX_PROFIT if self.get_argument("form") == "roll" and self.get_argument( "source") and self.get_argument("bet") and self.get_argument( "payout") and self.get_argument("chance"): source = self.get_argument("source") bet_amount = util.devise(db, self.get_argument("bet"), 'CHA', 'input') chance = util.devise(db, self.get_argument("chance"), 'value', 'input') payout = util.devise(db, self.get_argument("payout"), 'value', 'input') try: tx_hex = bet.create(db, source, bet_amount, chance, payout, unsigned=False) bitcoin.transmit(tx_hex, ask=False) info = "Thanks for betting!" except: error = sys.exc_info()[1] elif self.get_argument("form") == "my_bets" and self.get_argument( "address"): try: my_bets = util.get_bets(db, source=self.get_argument("address"), order_by='tx_index', validity='valid') my_bets = bet_tuples(my_bets) except: my_bets = [] self.render("casino.html", db_updated=db_updated, bitcoin_updated=bitcoin_updated, version_updated=version_updated, bets=bets, my_bets=my_bets, supply=supply, house_edge=config.HOUSE_EDGE, max_profit=max_profit, info=info, error=error, block_count_db=block_count_db, block_count_bitcoin=block_count_bitcoin)
def bet_tuples(bets): bets_new = [] if bets != None: for bet in bets: bets_new.append( (bet['source'], util.devise(db, bet['bet'], 'CHA', 'output'), bet['chance'], bet['payout'], util.devise(db, bet['profit'], 'CHA', 'output'))) return bets_new
def order_match_tuples(order_matches): order_matches_new = [] if order_matches!=None: for order_match in order_matches: if order_match['forward_asset']=='BTC': btc = util.devise(db, order_match['forward_amount'], 'BTC', 'output') cha = util.devise(db, order_match['backward_amount'], 'CHA', 'output') else: btc = util.devise(db, order_match['backward_amount'], 'BTC', 'output') cha = util.devise(db, order_match['forward_amount'], 'CHA', 'output') order_matches_new.append((btc,cha,order_match['id'])) return order_matches_new
def address (address): address = util.get_address(db, address=address) # Balances. balances = address['balances'] table = PrettyTable(['Asset', 'Amount']) table.add_row(['BTC', '???']) # BTC for balance in balances: asset = balance['asset'] amount = util.devise(db, balance['amount'], balance['asset'], 'output') table.add_row([asset, amount]) print('Balances') print(str(table)) print('\n') # Burns. burns = address['burns'] table = PrettyTable(['Block Index', 'Burned', 'Earned', 'Tx Hash']) for burn in burns: burned = util.devise(db, burn['burned'], 'BTC', 'output') earned = util.devise(db, burn['earned'], 'BTC', 'output') table.add_row([burn['block_index'], burned + ' BTC', earned + ' XCP', util.short(burn['tx_hash'])]) print('Burns') print(str(table)) print('\n') # Sends. sends = address['sends'] table = PrettyTable(['Amount', 'Asset', 'Source', 'Destination', 'Tx Hash']) for send in sends: amount = util.devise(db, send['amount'], send['asset'], 'output') asset = send['asset'] table.add_row([amount, asset, send['source'], send['destination'], util.short(send['tx_hash'])]) print('Sends') print(str(table)) print('\n') """ # Orders. orders = address['orders'] json_print(orders) table = PrettyTable(['Amount', 'Asset', 'Source', 'Destination', 'Tx Hash']) for order in orders: amount = util.devise(db, order['amount'], order['asset'], 'output') asset = order['asset'] table.add_row([amount, asset, order['source'], order['destination'], util.short(order['tx_hash'])]) print('orders') print(str(table)) print('\n') """ """
def balance_tuples(balances): balances_new = [] if balances != None: cha_supply = util.cha_supply(db) for balance in balances: burns = util.get_burns(db, source=balance['address'], validity='valid') burned = sum([burn['burned'] for burn in burns]) balances_new.append( (balance['address'], util.devise(db, balance['amount'], 'CHA', 'output'), util.devise(db, burned, 'BTC', 'output'), balance['amount'] / cha_supply * 100)) return balances_new
def order_match_tuples(order_matches): order_matches_new = [] if order_matches != None: for order_match in order_matches: if order_match['forward_asset'] == 'BTC': btc = util.devise(db, order_match['forward_amount'], 'BTC', 'output') cha = util.devise(db, order_match['backward_amount'], 'CHA', 'output') else: btc = util.devise(db, order_match['backward_amount'], 'BTC', 'output') cha = util.devise(db, order_match['forward_amount'], 'CHA', 'output') order_matches_new.append((btc, cha, order_match['id'])) return order_matches_new
def format_order (order): give_remaining = util.devise(db, D(order['give_remaining']), order['give_asset'], 'output') get_remaining = util.devise(db, round(D(order['give_remaining']) * D(order['price'])), order['get_asset'], 'output') give_asset = order['give_asset'] get_asset = order['get_asset'] price = util.devise(db, D(get_remaining) / D(give_remaining), 'price', 'output') price_assets = get_asset + '/' + give_asset if order['fee_required']: fee = str(order['fee_required'] / config.UNIT) else: fee = str(order['fee_provided'] / config.UNIT) return [give_remaining, give_asset, get_remaining, get_asset, price, price_assets, fee, util.get_time_left(order), util.short(order['tx_hash'])]
def get(self): db_updated = yield tornado.gen.Task(is_db_updated) bitcoin_updated = yield tornado.gen.Task(is_bitcoin_updated) version_updated = yield tornado.gen.Task(is_version_updated) block_count_db, block_count_bitcoin = yield tornado.gen.Task( get_status) info = None error = None bets = util.get_bets(db, order_by='tx_index', validity='valid') bets = bet_tuples(bets[:100]) my_bets = [] supply = util.devise(db, util.cha_supply(db), 'CHA', 'output') max_profit = float(supply) * config.MAX_PROFIT self.render("casino.html", db_updated=db_updated, bitcoin_updated=bitcoin_updated, version_updated=version_updated, bets=bets, my_bets=my_bets, supply=supply, house_edge=config.HOUSE_EDGE, max_profit=max_profit, info=info, error=error, block_count_db=block_count_db, block_count_bitcoin=block_count_bitcoin)
def compose (db, source, fraction, asset): call_price, callback_total, outputs, problems = validate(db, source, fraction, asset, util.last_block(db)['block_time'], util.last_block(db)['block_index'], parse=False) if problems: raise exceptions.ComposeError(problems) logging.info('Total quantity to be called back: {} {}'.format(util.devise(db, callback_total, asset, 'output'), asset)) asset_id = util.get_asset_id(asset, util.last_block(db)['block_index']) data = struct.pack(config.TXTYPE_FORMAT, ID) data += struct.pack(FORMAT, fraction, asset_id) return (source, [], data)
def compose (db, source, fraction, asset): call_price, callback_total, outputs, problems = validate(db, source, fraction, asset, util.last_block(db)['block_time'], util.last_block(db)['block_index'], parse=False) if problems: raise exceptions.ComposeError(problems) logging.info('Total quantity to be called back: {} {}'.format(util.devise(db, callback_total, asset, 'output'), asset)) asset_id = util.get_asset_id(db, asset, util.last_block(db)['block_index']) data = struct.pack(config.TXTYPE_FORMAT, ID) data += struct.pack(FORMAT, fraction, asset_id) return (source, [], data)
def format_bet (bet): odds = D(bet['counterwager_quantity']) / D(bet['wager_quantity']) if not bet['target_value']: target_value = None else: target_value = bet['target_value'] if not bet['leverage']: leverage = None else: leverage = util.devise(db, D(bet['leverage']) / 5040, 'leverage', 'output') return [util.BET_TYPE_NAME[bet['bet_type']], bet['feed_address'], util.isodt(bet['deadline']), target_value, leverage, str(bet['wager_remaining'] / config.UNIT) + ' XCP', util.devise(db, odds, 'odds', 'output'), bet['expire_index'] - util.last_block(db)['block_index'], bet['tx_hash']]
def balance_tuples(balances): balances_new = [] if balances!=None: cha_supply = util.cha_supply(db) for balance in balances: burns = util.get_burns(db, source = balance['address'], validity='valid') burned = sum([burn['burned'] for burn in burns]) balances_new.append((balance['address'],util.devise(db, balance['amount'], 'CHA', 'output'),util.devise(db, burned, 'BTC', 'output'), balance['amount']/cha_supply*100)) return balances_new
def order_tuples(orders): orders_new = [] if orders != None: for order in orders: if order['get_asset'] == 'CHA': cha_side = 'get_amount' btc_side = 'give_amount' buysell = 'buy' else: cha_side = 'give_amount' btc_side = 'get_amount' buysell = 'sell' orders_new.append( (util.devise(db, order[cha_side], 'CHA', 'output'), float(util.devise(db, order[btc_side], 'BTC', 'output')) / float(util.devise(db, order[cha_side], 'CHA', 'output')), util.devise(db, order[btc_side], 'BTC', 'output'), buysell, order['tx_hash'])) return orders_new
def format_order (order): price = D(order['get_amount']) / D(order['give_amount']) give_remaining = util.devise(D(order['give_remaining']), order['give_id'], 'output') get_remaining = util.devise(give_remaining * price, order['get_id'], 'ouput') give_name = util.get_asset_name(order['give_id']) get_name = util.get_asset_name(order['get_id']) give = str(give_remaining) + ' ' + give_name get = str(round(get_remaining, 8)) + ' ' + get_name price_string = str(price.quantize(config.FOUR).normalize()) price_string += ' ' + get_name + '/' + give_name if order['fee_required']: fee = str(order['fee_required'] / config.UNIT) + ' BTC (required)' else: fee = str(order['fee_provided'] / config.UNIT) + ' BTC (provided)' return [give, get, price_string, fee, util.get_time_left(order), util.short(order['tx_hash'])]
def balances (address): address_data = util.get_address(db, address=address) balances = address_data['balances'] table = PrettyTable(['Asset', 'Amount']) table.add_row(['BTC', bitcoin.get_btc_balance(address)]) # BTC for balance in balances: asset = balance['asset'] amount = util.devise(db, balance['amount'], balance['asset'], 'output') table.add_row([asset, amount]) print('Balances') print(table.get_string())
def format_bet (bet): odds = D(bet['counterwager_amount']) / D(bet['wager_amount']) wager_remaining = D(bet['wager_remaining']) counterwager_remaining = round(wager_remaining * odds) if not bet['target_value']: target_value = None else: target_value = bet['target_value'] if not bet['leverage']: leverage = None else: leverage = util.devise(db, D(bet['leverage']) / 5040, 'leverage', 'output') return [util.BET_TYPE_NAME[bet['bet_type']], bet['feed_address'], util.isodt(bet['deadline']), target_value, leverage, str(wager_remaining / config.UNIT) + ' XCP', str(counterwager_remaining / config.UNIT) + ' XCP', util.devise(db, odds, 'odds', 'output'), util.get_time_left(bet), util.short(bet['tx_hash'])]
def get(self): db_updated = yield tornado.gen.Task(is_db_updated) bitcoin_updated = yield tornado.gen.Task(is_bitcoin_updated) version_updated = yield tornado.gen.Task(is_version_updated) block_count_db, block_count_bitcoin = yield tornado.gen.Task(get_status) info = None error = None bets = util.get_bets(db, order_by='tx_index', validity='valid') bets = bet_tuples(bets[:100]) my_bets = [] supply = util.devise(db, util.cha_supply(db), 'CHA', 'output') max_profit = float(supply)*config.MAX_PROFIT self.render("casino.html", db_updated = db_updated, bitcoin_updated = bitcoin_updated, version_updated = version_updated, bets = bets, my_bets = my_bets, supply = supply, house_edge = config.HOUSE_EDGE, max_profit = max_profit, info = info, error = error, block_count_db = block_count_db, block_count_bitcoin = block_count_bitcoin)
def balances (address): if not bitcoin.base58_decode(address, config.ADDRESSVERSION): raise exceptions.InvalidAddressError('Not a valid Bitcoin address:', address) address_data = util.get_address(db, address=address) balances = address_data['balances'] table = PrettyTable(['Asset', 'Amount']) table.add_row(['BTC', bitcoin.get_btc_balance(address, normalize=True)]) # BTC for balance in balances: asset = balance['asset'] quantity = util.devise(db, balance['quantity'], balance['asset'], 'output') table.add_row([asset, quantity]) print('Balances') print(table.get_string())
def balances (address): if not bitcoin.base58_decode(address, config.ADDRESSVERSION): raise exceptions.AddressError('Not a valid Bitcoin address:', address) address_data = get_address(db, address=address) balances = address_data['balances'] table = PrettyTable(['Asset', 'Amount']) table.add_row(['BTC', bitcoin.get_btc_balance(address, normalize=True)]) # BTC for balance in balances: asset = balance['asset'] quantity = util.devise(db, balance['quantity'], balance['asset'], 'output') table.add_row([asset, quantity]) print('Balances') print(table.get_string())
def order_tuples(orders): orders_new = [] if orders!=None: for order in orders: if order['get_asset']=='CHA': cha_side = 'get_amount' btc_side = 'give_amount' buysell = 'buy' else: cha_side = 'give_amount' btc_side = 'get_amount' buysell = 'sell' orders_new.append((util.devise(db, order[cha_side], 'CHA', 'output'),float(util.devise(db, order[btc_side], 'BTC', 'output'))/float(util.devise(db, order[cha_side], 'CHA', 'output')), util.devise(db, order[btc_side], 'BTC', 'output'), buysell, order['tx_hash'])) return orders_new
def compose (db, source, quantity_per_unit, asset, dividend_asset): dividend_total, outputs, problems, fee = validate(db, source, quantity_per_unit, asset, dividend_asset, util.last_block(db)['block_index']) if problems: raise exceptions.ComposeError(problems) logging.info('Total quantity to be distributed in dividends: {} {}'.format(util.devise(db, dividend_total, dividend_asset, 'output'), dividend_asset)) if dividend_asset == config.BTC: return (source, [(output['address'], output['dividend_quantity']) for output in outputs], None) asset_id = util.get_asset_id(asset, util.last_block(db)['block_index']) dividend_asset_id = util.get_asset_id(dividend_asset, util.last_block(db)['block_index']) data = struct.pack(config.TXTYPE_FORMAT, ID) data += struct.pack(FORMAT_2, quantity_per_unit, asset_id, dividend_asset_id) return (source, [], data)
def compose (db, source, quantity_per_unit, asset, dividend_asset): dividend_total, outputs, problems, fee = validate(db, source, quantity_per_unit, asset, dividend_asset, util.last_block(db)['block_index']) if problems: raise exceptions.ComposeError(problems) logging.info('Total quantity to be distributed in dividends: {} {}'.format(util.devise(db, dividend_total, dividend_asset, 'output'), dividend_asset)) if dividend_asset == config.BTC: return (source, [(output['address'], output['dividend_quantity']) for output in outputs], None) asset_id = util.get_asset_id(db, asset, util.last_block(db)['block_index']) dividend_asset_id = util.get_asset_id(db, dividend_asset, util.last_block(db)['block_index']) data = struct.pack(config.TXTYPE_FORMAT, ID) data += struct.pack(FORMAT_2, quantity_per_unit, asset_id, dividend_asset_id) return (source, [], data)
def format_order (order): give_quantity = util.devise(db, D(order['give_quantity']), order['give_asset'], 'output') get_quantity = util.devise(db, D(order['get_quantity']), order['get_asset'], 'output') give_remaining = util.devise(db, D(order['give_remaining']), order['give_asset'], 'output') get_remaining = util.devise(db, D(order['get_remaining']), order['get_asset'], 'output') give_asset = order['give_asset'] get_asset = order['get_asset'] if get_asset < give_asset: price = util.devise(db, D(order['get_quantity']) / D(order['give_quantity']), 'price', 'output') price_assets = get_asset + '/' + give_asset + ' ask' else: price = util.devise(db, D(order['give_quantity']) / D(order['get_quantity']), 'price', 'output') price_assets = give_asset + '/' + get_asset + ' bid' return [D(give_remaining), give_asset, price, price_assets, str(order['fee_required'] / config.UNIT), str(order['fee_provided'] / config.UNIT), order['expire_index'] - util.last_block(db)['block_index'], order['tx_hash']]
def balances (address): def get_btc_balance(address): r = requests.get("https://blockchain.info/q/addressbalance/" + address) # ^any other services that provide this?? (blockexplorer.com doesn't...) try: assert r.status_code == 200 return int(r.text) / float(config.UNIT) except: return "???" address_data = util.get_address(db, address=address) # Balances. balances = address_data['balances'] table = PrettyTable(['Asset', 'Amount']) table.add_row(['BTC', get_btc_balance(address)]) # BTC for balance in balances: asset = balance['asset'] amount = util.devise(db, balance['amount'], balance['asset'], 'output') table.add_row([asset, amount]) print('Balances') print(table.get_string())
def balances(address): def get_btc_balance(address): r = requests.get("https://blockchain.info/q/addressbalance/" + address) # ^any other services that provide this?? (blockexplorer.com doesn't...) try: assert r.status_code == 200 return int(r.text) / float(config.UNIT) except: return "???" address_data = util.get_address(db, address=address) # Balances. balances = address_data['balances'] table = PrettyTable(['Asset', 'Amount']) table.add_row(['BTC', get_btc_balance(address)]) # BTC for balance in balances: asset = balance['asset'] amount = util.devise(db, balance['amount'], balance['asset'], 'output') table.add_row([asset, amount]) print('Balances') print(table.get_string())
def wallet(): #total_table = PrettyTable(['Asset', 'Balance']) wallet = {'addresses': {}} totals = {} for group in bitcoin.rpc('listaddressgroupings', []): for bunch in group: address, btc_balance = bunch[:2] get_address = util.get_address(db, address=address) balances = get_address['balances'] #table = PrettyTable(['Asset', 'Balance']) assets = {} empty = True if btc_balance: #table.add_row(['BTC', btc_balance]) # BTC assets['BTC'] = btc_balance if 'BTC' in totals.keys(): totals['BTC'] += btc_balance else: totals['BTC'] = btc_balance empty = False for balance in balances: asset = balance['asset'] balance = D(util.devise(db, balance['amount'], balance['asset'], 'output')) if balance: if asset in totals.keys(): totals[asset] += balance else: totals[asset] = balance #table.add_row([asset, balance]) assets[asset] = balance empty = False if not empty: wallet['addresses'][address] = assets wallet['totals'] = totals #print(wallet) response.content_type = 'application/json' return json.dumps(wallet, cls=DecimalEncoder)
# Check versions. # Check that bitcoind is running, communicable, and caught up with the blockchain. # Check that the database has caught up with bitcoind. if not args.force: util.versions_check(db) bitcoin.bitcoind_check(db) if args.action not in ('server', 'reparse', 'rollback'): util.database_check(db, bitcoin.get_block_count()) # TODO # Do something. # MESSAGE CREATION if args.action == 'send': quantity = util.devise(db, args.quantity, args.asset, 'input') cli('create_send', [args.source, args.destination, args.asset, quantity], args.unsigned) elif args.action == 'order': fee_required, fee_fraction_provided = D(args.fee_fraction_required), D(args.fee_fraction_provided) give_quantity, get_quantity = D(args.give_quantity), D(args.get_quantity) # Fee argument is either fee_required or fee_provided, as necessary. if args.give_asset == 'BTC': fee_required = 0 fee_fraction_provided = util.devise(db, fee_fraction_provided, 'fraction', 'input') fee_provided = round(D(fee_fraction_provided) * D(give_quantity) * D(config.UNIT)) if fee_provided < config.MIN_FEE: raise exceptions.InputError('Fee provided less than minimum necessary for acceptance in a block.')
# TODO # Check versions. util.versions_check(db) # Check that bitcoind is running, communicable, and caught up with the blockchain. # Check that the database has caught up with bitcoind. if not args.force: bitcoin.bitcoind_check(db) if args.action not in ('server', 'reparse', 'rollback', 'potentials'): util.database_check(db, bitcoin.rpc('getblockcount', [])) # TODO # Do something. # MESSAGE CREATION if args.action == 'send': quantity = util.devise(db, args.quantity, args.asset, 'input') cli('create_send', [args.source, args.destination, args.asset, quantity], args.unsigned) elif args.action == 'order': fee_required, fee_fraction_provided = D(args.fee_fraction_required), D( args.fee_fraction_provided) give_quantity, get_quantity = D(args.give_quantity), D( args.get_quantity) # Fee argument is either fee_required or fee_provided, as necessary. if args.give_asset == 'BTC': fee_required = 0 fee_fraction_provided = util.devise(db, fee_fraction_provided, 'fraction', 'input')
config.PREFIX = b'XX' # 2 bytes (possibly accidentally created) else: config.PREFIX = b'CNTRPRTY' # 8 bytes if args.action == None: args.action = 'server' # Check that bitcoind is running, communicable, and caught up with the blockchain. # Check that the database has caught up with bitcoind. if not args.force: util.bitcoind_check(db) if args.action not in ('server', 'purge'): util.database_check(db) # Do something. if args.action == 'send': quantity = util.devise(db, args.quantity, args.asset, 'input') unsigned_tx_hex = send.create(db, args.source, args.destination, quantity, args.asset) json_print(bitcoin.transmit(unsigned_tx_hex, unsigned=args.unsigned)) elif args.action == 'order': # Fee argument is either fee_required or fee_provided, as necessary. if args.give_asset == 'BTC': if args.fee_required != 0: raise exceptions.FeeError('When selling BTC, do not specify a fee required.') fee_required = args.fee_required fee_provided = util.devise(db, args.fee_provided, 'BTC', 'input') elif args.get_asset == 'BTC': fee_required = util.devise(db, args.fee_required, 'BTC', 'input') if args.fee_provided != config.MIN_FEE / config.UNIT: raise exceptions.FeeError('When buying BTC, do not specify a fee provided.')
requests_log.setLevel(logging.DEBUG if args.verbose else logging.WARNING) requests_log.propagate = False urllib3_log = logging.getLogger('urllib3') urllib3_log.setLevel(logging.DEBUG if args.verbose else logging.WARNING) urllib3_log.propagate = False if args.action == None: args.action = 'server' # TODO: Keep around only as long as reparse and rollback don’t use API. if not config.FORCE and args.action in ('reparse', 'rollback'): util.version_check(db) bitcoin.bitcoind_check(db) # MESSAGE CREATION if args.action == 'send': if args.fee: args.fee = util.devise(db, args.fee, 'BTC', 'input') quantity = util.devise(db, args.quantity, args.asset, 'input') cli('create_send', {'source': args.source, 'destination': args.destination, 'asset': args.asset, 'quantity': quantity, 'fee': args.fee, 'allow_unconfirmed_inputs': args.unconfirmed}, args.unsigned) elif args.action == 'order': if args.fee: args.fee = util.devise(db, args.fee, 'BTC', 'input') fee_required, fee_fraction_provided = D(args.fee_fraction_required), D(args.fee_fraction_provided) give_quantity, get_quantity = D(args.give_quantity), D(args.get_quantity) # Fee argument is either fee_required or fee_provided, as necessary. if args.give_asset == 'BTC': fee_required = 0 fee_fraction_provided = util.devise(db, fee_fraction_provided, 'fraction', 'input') fee_provided = round(D(fee_fraction_provided) * D(give_quantity) * D(config.UNIT))
if args.action == None: args.action = 'server' # Check versions. util.versions_check(db) # Check that bitcoind is running, communicable, and caught up with the blockchain. # Check that the database has caught up with bitcoind. if not args.force: util.bitcoind_check(db) if args.action not in ('server', 'reparse', 'rollback'): util.database_check(db) # Do something. if args.action == 'send': quantity = util.devise(db, args.quantity, args.asset, 'input') unsigned_tx_hex = send.create(db, args.source, args.destination, quantity, args.asset, unsigned=args.unsigned) print(unsigned_tx_hex) if args.unsigned else json_print(bitcoin.transmit(unsigned_tx_hex)) elif args.action == 'order': fee_required, fee_provided = D(args.fee_required), D(args.fee_provided) give_quantity, get_quantity = D(args.give_quantity), D(args.get_quantity) # Fee argument is either fee_required or fee_provided, as necessary. if args.give_asset == 'BTC': fee_required = 0 fee_provided = util.devise(db, fee_provided, 'fraction', 'input') fee_provided = round(D(fee_provided) * D(give_quantity) * D(config.UNIT)) if fee_provided < config.MIN_FEE: raise exceptions.InputError('Fee provided less than minimum necessary for acceptance in a block.')
def bet_tuples(bets): bets_new = [] if bets!=None: for bet in bets: bets_new.append((bet['source'],util.devise(db, bet['bet'], 'CHA', 'output'),bet['chance'],bet['payout'],util.devise(db, bet['profit'], 'CHA', 'output'))) return bets_new
def post(self): db_updated = yield tornado.gen.Task(is_db_updated) bitcoin_updated = yield tornado.gen.Task(is_bitcoin_updated) version_updated = yield tornado.gen.Task(is_version_updated) block_count_db, block_count_bitcoin = yield tornado.gen.Task(get_status) info = None error = None orders_sell = util.get_orders(db, validity='valid', show_empty=False, show_expired=False, filters=[{'field': 'give_asset', 'op': '==', 'value': 'CHA'},{'field': 'get_asset', 'op': '==', 'value': 'BTC'}]) orders_buy = util.get_orders(db, validity='valid', show_empty=False, show_expired=False, filters=[{'field': 'get_asset', 'op': '==', 'value': 'CHA'},{'field': 'give_asset', 'op': '==', 'value': 'BTC'}]) orders_sell = sorted(order_tuples(orders_sell), key=lambda tup: tup[1], reverse=True) orders_buy = sorted(order_tuples(orders_buy), key=lambda tup: tup[1], reverse=True) my_orders = None my_order_matches = None balance = None if self.get_argument("form")=="balance": address = self.get_argument("address") try: wallet = util.get_address(db, address = address) except: wallet = None balance = None if wallet != None: for balance in wallet['balances']: if balance['asset']=='CHA': balance = util.devise(db, balance['amount'], 'CHA', 'output') elif self.get_argument("form")=="my_orders": address = self.get_argument("address") try: my_orders = util.get_orders(db, validity='valid', show_empty=False, show_expired=False, source=address) my_orders = order_tuples(my_orders) my_order_matches = util.get_order_matches(db, validity='pending', is_mine=True, address=address) my_order_matches = order_match_tuples(my_order_matches) except: my_orders = None my_order_matches = None elif self.get_argument("form")=="btcpay": order_match_id = self.get_argument("order_match_id") try: tx_hex = btcpay.create(db, order_match_id, unsigned=False) bitcoin.transmit(tx_hex, ask=False) info = "BTC payment successful" except: error = sys.exc_info()[1] elif self.get_argument("form")=="cancel": tx_hash = self.get_argument("tx_hash") try: tx_hex = cancel.create(db, tx_hash, unsigned=False) bitcoin.transmit(tx_hex, ask=False) info = "Cancel successful" except: error = sys.exc_info()[1] elif self.get_argument("form")=="send": source = self.get_argument("source") destination = self.get_argument("destination") quantity = util.devise(db, self.get_argument("quantity"), 'CHA', 'input') try: tx_hex = send.create(db, source, destination, quantity, 'CHA', unsigned=False) bitcoin.transmit(tx_hex, ask=False) info = "Send successful" except: error = sys.exc_info()[1] elif self.get_argument("form")=="burn": source = self.get_argument("source") quantity = util.devise(db, self.get_argument("quantity"), 'CHA', 'input') try: tx_hex = burn.create(db, source, quantity, unsigned=False) bitcoin.transmit(tx_hex, ask=False) info = "Burn successful" except: error = sys.exc_info()[1] elif self.get_argument("form")=="buy": source = self.get_argument("source") quantity = util.devise(db, self.get_argument("quantity"), 'CHA', 'input') price = util.devise(db, self.get_argument("price"), 'value', 'input') pricetimesquantity = float(self.get_argument("quantity"))*float(self.get_argument("price")) pricetimesquantity = int(pricetimesquantity*config.UNIT) expiration = 6 * 24 #24 hour order try: tx_hex = order.create(db, source, 'BTC', pricetimesquantity, 'CHA', quantity, expiration, 0, config.MIN_FEE, unsigned=False) bitcoin.transmit(tx_hex, ask=False) info = "Buy order successful" except: error = sys.exc_info()[1] elif self.get_argument("form")=="sell": source = self.get_argument("source") quantity = util.devise(db, self.get_argument("quantity"), 'CHA', 'input') price = util.devise(db, self.get_argument("price"), 'value', 'input') pricetimesquantity = float(self.get_argument("quantity"))*float(self.get_argument("price")) pricetimesquantity = int(pricetimesquantity*config.UNIT) expiration = 6 * 24 #24 hour order try: tx_hex = order.create(db, source, 'CHA', quantity, 'BTC', pricetimesquantity, expiration, 0, config.MIN_FEE, unsigned=False) bitcoin.transmit(tx_hex, ask=False) info = "Sell order successful" except: error = sys.exc_info()[1] self.render("wallet.html", db_updated = db_updated, bitcoin_updated = bitcoin_updated, version_updated = version_updated, orders_buy = orders_buy, orders_sell = orders_sell, info = info, error = error, block_count_db = block_count_db, block_count_bitcoin = block_count_bitcoin, balance = balance, my_orders = my_orders, my_order_matches = my_order_matches)
def post(self): db_updated = yield tornado.gen.Task(is_db_updated) bitcoin_updated = yield tornado.gen.Task(is_bitcoin_updated) version_updated = yield tornado.gen.Task(is_version_updated) block_count_db, block_count_bitcoin = yield tornado.gen.Task( get_status) info = None error = None orders_sell = util.get_orders(db, validity='valid', show_empty=False, show_expired=False, filters=[{ 'field': 'give_asset', 'op': '==', 'value': 'CHA' }, { 'field': 'get_asset', 'op': '==', 'value': 'BTC' }]) orders_buy = util.get_orders(db, validity='valid', show_empty=False, show_expired=False, filters=[{ 'field': 'get_asset', 'op': '==', 'value': 'CHA' }, { 'field': 'give_asset', 'op': '==', 'value': 'BTC' }]) orders_sell = sorted(order_tuples(orders_sell), key=lambda tup: tup[1], reverse=True) orders_buy = sorted(order_tuples(orders_buy), key=lambda tup: tup[1], reverse=True) my_orders = None my_order_matches = None balance = None if self.get_argument("form") == "balance": address = self.get_argument("address") try: wallet = util.get_address(db, address=address) except: wallet = None balance = None if wallet != None: for balance in wallet['balances']: if balance['asset'] == 'CHA': balance = util.devise(db, balance['amount'], 'CHA', 'output') elif self.get_argument("form") == "my_orders": address = self.get_argument("address") try: my_orders = util.get_orders(db, validity='valid', show_empty=False, show_expired=False, source=address) my_orders = order_tuples(my_orders) my_order_matches = util.get_order_matches(db, validity='pending', is_mine=True, address=address) my_order_matches = order_match_tuples(my_order_matches) except: my_orders = None my_order_matches = None elif self.get_argument("form") == "btcpay": order_match_id = self.get_argument("order_match_id") try: tx_hex = btcpay.create(db, order_match_id, unsigned=False) bitcoin.transmit(tx_hex, ask=False) info = "BTC payment successful" except: error = sys.exc_info()[1] elif self.get_argument("form") == "cancel": tx_hash = self.get_argument("tx_hash") try: tx_hex = cancel.create(db, tx_hash, unsigned=False) bitcoin.transmit(tx_hex, ask=False) info = "Cancel successful" except: error = sys.exc_info()[1] elif self.get_argument("form") == "send": source = self.get_argument("source") destination = self.get_argument("destination") quantity = util.devise(db, self.get_argument("quantity"), 'CHA', 'input') try: tx_hex = send.create(db, source, destination, quantity, 'CHA', unsigned=False) bitcoin.transmit(tx_hex, ask=False) info = "Send successful" except: error = sys.exc_info()[1] elif self.get_argument("form") == "burn": source = self.get_argument("source") quantity = util.devise(db, self.get_argument("quantity"), 'CHA', 'input') try: tx_hex = burn.create(db, source, quantity, unsigned=False) bitcoin.transmit(tx_hex, ask=False) info = "Burn successful" except: error = sys.exc_info()[1] elif self.get_argument("form") == "buy": source = self.get_argument("source") quantity = util.devise(db, self.get_argument("quantity"), 'CHA', 'input') price = util.devise(db, self.get_argument("price"), 'value', 'input') pricetimesquantity = float(self.get_argument("quantity")) * float( self.get_argument("price")) pricetimesquantity = int(pricetimesquantity * config.UNIT) expiration = 6 * 24 #24 hour order try: tx_hex = order.create(db, source, 'BTC', pricetimesquantity, 'CHA', quantity, expiration, 0, config.MIN_FEE, unsigned=False) bitcoin.transmit(tx_hex, ask=False) info = "Buy order successful" except: error = sys.exc_info()[1] elif self.get_argument("form") == "sell": source = self.get_argument("source") quantity = util.devise(db, self.get_argument("quantity"), 'CHA', 'input') price = util.devise(db, self.get_argument("price"), 'value', 'input') pricetimesquantity = float(self.get_argument("quantity")) * float( self.get_argument("price")) pricetimesquantity = int(pricetimesquantity * config.UNIT) expiration = 6 * 24 #24 hour order try: tx_hex = order.create(db, source, 'CHA', quantity, 'BTC', pricetimesquantity, expiration, 0, config.MIN_FEE, unsigned=False) bitcoin.transmit(tx_hex, ask=False) info = "Sell order successful" except: error = sys.exc_info()[1] self.render("wallet.html", db_updated=db_updated, bitcoin_updated=bitcoin_updated, version_updated=version_updated, orders_buy=orders_buy, orders_sell=orders_sell, info=info, error=error, block_count_db=block_count_db, block_count_bitcoin=block_count_bitcoin, balance=balance, my_orders=my_orders, my_order_matches=my_order_matches)
def get(self): supply = util.devise(db, util.cha_supply(db), 'CHA', 'output') self.render("index.html", supply = supply)
def counterparty_action(): unsigned = True if request.forms.get('unsigned')!=None and request.forms.get('unsigned')=="1" else False print("unsigned:"+str(unsigned)) try: action = request.forms.get('action') if action=='send': source = request.forms.get('source') destination = request.forms.get('destination') asset = request.forms.get('asset') quantity = util.devise(db, request.forms.get('quantity'), asset, 'input') unsigned_tx_hex = send.create(db, source, destination, quantity, asset, unsigned=unsigned) result = {'success':True, 'message':str(unsigned_tx_hex)} elif action=='order': source = request.forms.get('source') give_asset = request.forms.get('give_asset') get_asset = request.forms.get('get_asset') give_quantity = util.devise(db, request.forms.get('give_quantity'), give_asset, 'input') get_quantity = util.devise(db, request.forms.get('get_quantity'), get_asset, 'input') expiration = int(request.forms.get('expiration')) fee_required = 0 fee_provided = config.MIN_FEE if give_asset == 'BTC': fee_required = 0 fee_provided = util.devise(db, request.forms.get('fee_provided'), 'BTC', 'input') elif get_asset == 'BTC': fee_required = util.devise(db, request.forms.get('fee_required'), 'BTC', 'input') fee_provided = config.MIN_FEE unsigned_tx_hex = order.create(db, source, give_asset, give_quantity, get_asset, get_quantity, expiration, fee_required, fee_provided, unsigned=unsigned) result = {'success':True, 'message':str(unsigned_tx_hex)} elif action=='btcpay': order_match_id = request.forms.get('order_match_id') unsigned_tx_hex = btcpay.create(db, order_match_id, unsigned=unsigned) result = {'success':True, 'message':str(unsigned_tx_hex)} elif action=='cancel': offer_hash = request.forms.get('offer_hash') unsigned_tx_hex = cancel.create(db, offer_hash, unsigned=unsigned) result = {'success':True, 'message':str(unsigned_tx_hex)} elif action=='issuance': source = request.forms.get('source') destination = request.forms.get('destination') asset_name = request.forms.get('asset_name') divisible = True if request.forms.get('divisible')=="1" else False quantity = util.devise(db, request.forms.get('quantity'), None, 'input', divisible=divisible) callable_ = True if request.forms.get('callable')=="1" else False call_date = request.forms.get('call_date') call_price = request.forms.get('call_price') description = request.forms.get('description') if callable_: call_date = round(datetime.timestamp(dateutil.parser.parse(call_date))) call_price = float(call_price) else: call_date, call_price = 0, 0 issuance.create(db, source, destination, asset_name, quantity, divisible, callable_, call_date, call_price, description, unsigned=unsigned) result = {'success':True, 'message':str(unsigned_tx_hex)} elif action=='dividend': source = request.forms.get('source') asset = request.forms.get('asset') quantity_per_share = util.devise(db, request.forms.get('quantity_per_share'), 'XCP', 'input') unsigned_tx_hex = dividend.create(db, source, quantity_per_share, asset, unsigned=unsigned) result = {'success':True, 'message':str(unsigned_tx_hex)} elif action=='callback': source = request.forms.get('source') asset = request.forms.get('asset') fraction_per_share = float(request.forms.get('fraction_per_share')) unsigned_tx_hex = callback.create(db, source, fraction_per_share, asset, unsigned=unsigned) result = {'success':True, 'message':str(unsigned_tx_hex)} elif action=='broadcast': source = request.forms.get('source') text = request.forms.get('text') value = util.devise(db, request.forms.get('value'), 'value', 'input') fee_multiplier = request.forms.get('fee_multiplier') unsigned_tx_hex = broadcast.create(db, source, int(time.time()), value, fee_multiplier, text, unsigned=unsigned) result = {'success':True, 'message':str(unsigned_tx_hex)} elif action=='bet': source = request.forms.get('source') feed_address = request.forms.get('feed_address') bet_type = int(request.forms.get('bet_type')) deadline = calendar.timegm(dateutil.parser.parse(request.forms.get('deadline')).utctimetuple()) wager = util.devise(db, request.forms.get('wager'), 'XCP', 'input') counterwager = util.devise(db, request.forms.get('counterwager'), 'XCP', 'input') target_value = util.devise(db, request.forms.get('target_value'), 'value', 'input') leverage = util.devise(db, request.forms.get('leverage'), 'leverage', 'input') expiration = request.forms.get('expiration') unsigned_tx_hex = bet.create(db, source, feed_address, bet_type, deadline, wager, counterwager, target_value, leverage, expiration, unsigned=unsigned) result = {'success':True, 'message':str(unsigned_tx_hex)} else: result = {'success':False, 'message':'Unknown action.'} if result['success']==True and unsigned==False: tx_hash = bitcoin.transmit(unsigned_tx_hex, ask=False); result['message'] = "Transaction transmited: "+tx_hash except Exception as e: result = {'success':False, 'message':str(e)} response.content_type = 'application/json' return json.dumps(result, cls=DecimalEncoder)
if args.action == None: args.action = 'server' # Check versions. util.versions_check(db) # Check that bitcoind is running, communicable, and caught up with the blockchain. # Check that the database has caught up with bitcoind. if not args.force: util.bitcoind_check(db) if args.action not in ('server', 'reparse', 'rollback'): util.database_check(db) # Do something. if args.action == 'send': quantity = util.devise(db, args.quantity, args.asset, 'input') unsigned_tx_hex = send.create(db, args.source, args.destination, quantity, args.asset, unsigned=args.unsigned) print(unsigned_tx_hex) if args.unsigned else json_print( bitcoin.transmit(unsigned_tx_hex)) elif args.action == 'order': fee_required, fee_provided = D(args.fee_required), D(args.fee_provided) give_quantity, get_quantity = D(args.give_quantity), D( args.get_quantity) # Fee argument is either fee_required or fee_provided, as necessary.
def get(self): supply = util.devise(db, util.cha_supply(db), 'CHA', 'output') self.render("index.html", supply=supply)
logging.basicConfig(filename=config.LOG, level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%m-%d-%YT%I:%M:%S%z') requests_log = logging.getLogger("requests") requests_log.setLevel(logging.WARNING) # Do something. if args.version: print('This is Version 0.01 of counterparty.') elif args.action == 'send': bitcoin.bitcoind_check() asset_id = util.get_asset_id(args.asset) quantity = util.devise(args.quantity, asset_id, 'input') unsigned_tx_hex = send.create(args.source, args.destination, round(quantity), asset_id) json_print(bitcoin.transmit(unsigned_tx_hex)) elif args.action == 'order': bitcoin.bitcoind_check() give_id = util.get_asset_id(args.give_asset) get_id = util.get_asset_id(args.get_asset) # Fee argument is either fee_required or fee_provided, as necessary. fee = round(D(args.fee) * config.UNIT) if not give_id: fee_provided = fee