class Bitcoind(): def __init__(self, rpcconfig = "bitcoinrpc:rpcpassword", testnet = False): self.rpcuser, self.rpcpassword = self.readconfig(rpcconfig) self.testnet = testnet self.port = "8332" if not TESTNET else "18332" self.conn = ServiceProxy("http://" + self.rpcuser + ":" + self.rpcpassword + "@127.0.0.1:" + self.port) def geinfo(self): return self.conn.getinfo() def getrawtransaciton(self, txid): return self.conn.getrawtransaction(txid) def readconfig(self, config): if ":" in config and not "." in config: usrpas = config.split(":") return (usrpas[0], usrpas[1]) else: cf = open(config, "r") cfs = cf.readlines() usr, pas = "******", "rpcpassword" for i in cfs: j = i.split("=") if j[0] == "rpcuser": usr = j[1] elif j[0] == "rpcpassword": pas = j[0] return (usr, pas)
class ItemClient(): def __init__(self, wallet, password, second_password): self.second_password = second_password self.btc = ServiceProxy( 'https://%s:%[email protected]:443' % (wallet, password)) def GetNewAddress(self): self.btc.walletpassphrase(self.second_password, 50) return self.btc.getnewaddress() def SignMessage(self, address, message): self.btc.walletpassphrase(self.second_password, 50) sig = self.btc.signmessage(address, message) return sig def GenerateProofSig(self, item, target): """ Prove that this server owns the output of last_tx_id. """ tx = self.btc.gettransaction(item.last_tx_id) last_address = None for det in tx['details']: if det['category'] == 'receive': last_address = det['address'] if not last_address: return None self.btc.walletpassphrase(self.second_password, 50) proof_sig = self.btc.signmessage(last_address, target) return proof_sig
def handle_transactions(): for currency in currencies: logging.info('Processing {} deposits'.format(currency)) oldtransactions = CompletedOrder.query.filter().all() oldids = [x.transaction_id for x in oldtransactions] rpc = ServiceProxy(currencies[currency]['daemon']) transactions = [ tx for tx in rpc.listtransactions() if tx['category'] == 'receive'] newtransactions = [] for tx in transactions: if tx['txid'] not in oldids: newtransactions.append(tx) for tx in newtransactions: addr = Address.query.filter( Address.address == str( tx['address'])).first() if addr: logging.info( "New Deposit! TXID: {} Amount: {} UserID: {}".format( tx['txid'], tx['amount'], addr.user)) adjustbalance( currency, addr.user, int( float( tx['amount']) * currencies[currency]['multiplier'])) co = CompletedOrder( currency + "_" + currency, "DEPOSIT", float( tx['amount']), 0, addr.user, is_deposit=True, transaction_id=tx['txid']) db_session.add(co) logging.info('Processing {} withdrawals'.format(currency)) withdrawals = CompletedOrder.query.filter( CompletedOrder.is_withdrawal).filter( CompletedOrder.withdrawal_complete == False).all() for withdrawal in withdrawals: # TODO: some proper error checking etc logging.info( "New Withdrawal! Amount: {}".format( withdrawal.amount)) sendaddr = withdrawal.withdrawal_address try: rpc.sendtoaddress(sendaddr, withdrawal.amount) except Exception as e: logging.warning( "Error in executing withdrawal! ID: {} JSONRPC Error: {}".format( withdrawal.id, repr( e.error))) withdrawal.withdrawal_complete = True db_session.add(withdrawal) db_session.commit()
def _sendhome(data): from jsonrpc import ServiceProxy homeurl = "http://www.mindmade.org/~andi/research/python/server.py" proxy = ServiceProxy(homeurl) result = proxy.log(data) log("result %s" % result)
def GET(self): if session['active_page'] != "home": if session['active_page'] == "devtome": raise web.seeother('/devtome') rpc_daemon = ServiceProxy("http://"+rpc['user']+":"+rpc['pass']+"@blisterpool.com:52332") block = rpc_daemon.getinfo()['blocks'] blocksleft = 4000 - int(block)%4000 round = (int(block) + blocksleft)/4000 minleft = blocksleft * 10 h, m = divmod(minleft, 60) d, h = divmod(h, 24) timeleft = "%d days, %d hours and %d minutes" % (d, h, m) secondstogo = blocksleft * 600 eta = calendar.timegm(time.gmtime()) + secondstogo eta = time.strftime("%a, %d %b %Y %H:%M +0000", time.gmtime(eta)) if blocksleft > 2700: # the current payout block is still active activeround = round activeroundstart = ((round - 1) * 4000) - 2700 else: activeround = round + 1 activeroundstart = (round * 4000) - 2700 activeroundend = activeroundstart + 4000 breakdown, name, myshares, tally = receiver.GetShareEstimate(activeround, session.name, session.round) if activeround == round: breakdown2 = breakdown else: breakdown2 = receiver.GetBreakdown(round) breakdown3 = receiver.GetBreakdown(round-1) if breakdown != None: shares = breakdown['TotalShares'] else: shares = 1 activepayout = 180000000/shares activeblocksleft = activeroundend - int(block) activeminleft = activeblocksleft * 10 h, m = divmod(activeminleft, 60) d, h = divmod(h, 24) activetimeleft = "%d days, %d hours and %d minutes" % (d, h, m) activesecondstogo = activeblocksleft * 600 activeendtime = calendar.timegm(time.gmtime()) + activesecondstogo activeendtime = time.strftime("%a, %d %b %Y %H:%M +0000", time.gmtime(activeendtime)) devpershare = receiver.GetSharesByRound(round) prev = {} prev['round'] = round - 1 prev['devpershare'] = receiver.GetSharesByRound(round - 1) return render.index(name, myshares, tally, session.round, block, round, blocksleft, timeleft, eta, activeround, activepayout, activeroundstart, activeroundend, activeendtime, activetimeleft, devpershare, breakdown, breakdown2, breakdown3, prev)
def setUpClass(cls): service = ServiceProxy('http://localhost:9999/op') items = [dict(path='net.dot1q.dev10', model='asset.netable', value=dict(fqdn='dev10.dot1q.net', ip4='192.168.123.10', serialno='DRS010'))] cls.items = items service.upsert(items)
def connect(self): try: FVHTTPHandler.fv = self.getFV self.fv = ServiceProxy(self.cntstr, JSONParamEncoder) except: print "Connection to FlowVisor using %s failed" % self.cntstr sys.exit()
def __init__ (self): if DEBUG: print "Init tunproxy..." self._controller = CONTROLLER # available PLE nodes self._ple_list = [] # number of PLE connections self._ple_conns = 0 # dict for RTT measurments of PLE nodes self._delays = {} # PLE nodes' config params (which we are to connect) self._ple_config = [] self._my_fqdn = None self._host_shortname = None self._qemu = False self._parse_args() # init JSONRPC proxy while 1: try: self._jsonrpc_proxy = ServiceProxy(self._controller) break except (JSONRPCException, IOError): print "Waiting for initializing JSONRPC Proxy..." self._ple_list = [] time.sleep(2) continue if DEBUG: print "Done."
def __init__(self, key_name, btc_proxy = 'http://*****:*****@localhost:19001', lineage_filename = 'lineage.pickle'): if pp_keys.ExportPubKey(key_name) == '': raise Exception('Unknown key name ' + key_name) self.key_name = key_name self.btc = ServiceProxy(btc_proxy) self.btc.getinfo() # Will raise an exception if we aren't connected # Load user accounts try: self.user_account = cPickle.load(file(USER_ACCOUNT_FILENAME)) except: logging.info('Starting with empty user accounts') self.user_account= {} # Load lineage try: self.lineage = cPickle.load(file(lineage_filename)) except: logging.info('Starting with empty lineage') self.lineage = pp_lineage.Lineage() logging.info('Loading block chain from' + BLOCK_DIRECTORY) self.lineage.UpdateDir(BLOCK_DIRECTORY) # Save the updated lineage (only at __init__). logging.info('Saving updated lineage...') cPickle.dump(self.lineage, file(lineage_filename, 'w'), -1)
def checkForAlreadyRunning(self): try: # If create doesn't throw an error, there's another Armory open already! sock = socket.create_connection(('127.0.0.1',ARMORY_RPC_PORT), 0.1); # If this is the first instance of armoryd.py, connection will fail, # we hit the except clause, and continue happily starting the server. # If armoryd is already running, the rest of this try-clause will exec. LOGINFO('Another instance of armoryd.py is already runnning!') with open(ARMORYD_CONF_FILE, 'r') as f: usr,pwd = f.readline().strip().split(':') if CLI_ARGS: proxyobj = ServiceProxy("http://%s:%[email protected]:%d" % (usr,pwd,ARMORY_RPC_PORT)) try: #if not proxyobj.__hasattr__(CLI_ARGS[0]): #raise UnrecognizedCommand, 'No json command %s'%CLI_ARGS[0] extraArgs = [] for arg in ([] if len(CLI_ARGS)==1 else CLI_ARGS[1:]): if arg[0] == '{': extraArgs.append(json.loads(arg)) else: extraArgs.append(arg) result = proxyobj.__getattr__(CLI_ARGS[0])(*extraArgs) print json.dumps(result, indent=4, \ sort_keys=True, \ cls=UniversalEncoder) except Exception as e: errtype = str(type(e)) errtype = errtype.replace("<class '",'') errtype = errtype.replace("<type '",'') errtype = errtype.replace("'>",'') errordict = { 'error': { 'errortype': errtype, 'jsoncommand': CLI_ARGS[0], 'jsoncommandargs': ([] if len(CLI_ARGS)==1 else CLI_ARGS[1:]), 'extrainfo': str(e) if len(e.args)<2 else e.args}} print json.dumps( errordict, indent=4, sort_keys=True, cls=UniversalEncoder) sock.close() os._exit(0) except socket.error: LOGINFO('No other armoryd.py instance is running. We\'re the first.') pass
def __init__( self, ip_addr="127.0.0.1", port="8332", user="******", password="******", app="payme" ): bturl = "http://%s:%s@%s:%s" % ( user, password, ip_addr, port ) self.proxy = ServiceProxy(bturl) self.app = app
def run(self): access = ServiceProxy('http://' + self.rpcuser + ':' + self.rpcpass + '@' + self.rpchost + ':' + self.rpcport) while True: for server in self.bitHopper.pool.servers: info = self.bitHopper.pool.get_entry(server) if info['wallet'] != "": wallet = info['wallet'] try: getbalance = float(access.getreceivedbyaddress(wallet)) self.log_msg(server + ' ' + str(getbalance) + ' ' + wallet) self.bitHopper.update_payout(server, float(getbalance)) except Exception, e: self.log_dbg("Error getting getreceivedbyaddress") self.log_dbg(e) eventlet.sleep(self.interval)
def createProxy(self, forceNew=False): if self.proxy==None or forceNew: LOGDEBUG('Creating proxy') usr,pas,hst,prt = [self.bitconf[k] for k in ['rpcuser','rpcpassword',\ 'host', 'rpcport']] pstr = 'http://%s:%s@%s:%d' % (usr,pas,hst,prt) LOGINFO('Creating proxy in SDM: host=%s, port=%s', hst,prt) self.proxy = ServiceProxy(pstr)
def __init__(self, block, nonce, urlindex): Thread.__init__(self) self.block = block self.nonce = nonce self.urlindex = urlindex # Make a new proxy for sending, to avoid threading clashes self.proxy = ServiceProxy(options.url[self.urlindex])
def connect_JSON(config): """Connect to a digibyte JSON-RPC server""" testnet = config.get("testnet", "0") testnet = int(testnet) > 0 # 0/1 in config file, convert to True/False if not "rpcport" in config: config["rpcport"] = 18332 if testnet else 8332 connect = "http://%s:%[email protected]:%s" % (config["rpcuser"], config["rpcpassword"], config["rpcport"]) try: result = ServiceProxy(connect) # ServiceProxy is lazy-connect, so send an RPC command mostly to catch connection errors, # but also make sure the digibyted we're talking to is/isn't testnet: if result.getmininginfo()["testnet"] != testnet: sys.stderr.write("RPC server at " + connect + " testnet setting mismatch\n") sys.exit(1) return result except: sys.stderr.write("Error connecting to RPC server at " + connect + "\n") sys.exit(1)
def connect_JSON(config): """Connect to a bitcoin JSON-RPC server""" testnet = config.get('testnet', '0') testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False if not 'rpcport' in config: config['rpcport'] = 15492 if testnet else 5492 connect = "http://%s:%[email protected]:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport']) try: result = ServiceProxy(connect) # ServiceProxy is lazy-connect, so send an RPC command mostly to catch connection errors, # but also make sure the bitcoind we're talking to is/isn't testnet: if result.getmininginfo()['testnet'] != testnet: sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n") sys.exit(1) return result except: sys.stderr.write("Error connecting to RPC server at "+connect+"\n") sys.exit(1)
def __init__(self): self.remote_url = "http://%s:%s/api/%s/index.o" % ( meta['SERVER'], meta['PORT'], meta['API']) self.server = ServiceProxy(self.remote_url) QObject.__init__(self) GetterSetter.__init__(self)
def __init__(self, currency = "BTC", account = None ): self.__host = Settings[currency]["host"] self.__port = Settings[currency]["port"] self.__account = account self.__rpc_user = Settings[currency]["rpc_user"] self.__rpc_pwd = Settings[currency]["rpc_pwd"] self.__user = Settings[currency]["user"] self.__access = ServiceProxy("http://%s:%s@%s:%s" % (self.__rpc_user, self.__rpc_pwd, self.__host, self.__port) )
def __init__(self, args): self.bitcoind_api = ServiceProxy(args.bitcoind_connection_string) self.bet_address = args.betaddress self.startamount = args.startamount self.lastamount = args.startamount self.limit = args.limitamount self.betmul = args.betmul self.num_rounds = args.rounds self.current_round = 1 self.sessionID = None super(SimpleMartingaleBot, self).__init__(args)
def setUp(self): service = ServiceProxy('http://localhost:9999/op') items = [dict(path='net.dot1q.dev21', model='asset.netable', value=dict(fqdn='dev21.dot1q.net', ip4='192.168.123.21', serialno='DRS021')), dict(path='net.dot1q.dev22', model='asset.netable', value=dict(fqdn='dev22.dot1q.net', ip4='192.168.123.22', serialno='DRS022')), dict(path='net.dot1q.dev23', model='asset.netable', value=dict(fqdn='dev23.dot1q.net', ip4='192.168.123.23', serialno='DRS023'))] service.upsert(items)
class CryptoAccount: def __init__(self, currency = "BTC", account = None ): self.__host = Settings[currency]["host"] self.__port = Settings[currency]["port"] self.__account = account self.__rpc_user = Settings[currency]["rpc_user"] self.__rpc_pwd = Settings[currency]["rpc_pwd"] self.__user = Settings[currency]["user"] self.__access = ServiceProxy("http://%s:%s@%s:%s" % (self.__rpc_user, self.__rpc_pwd, self.__host, self.__port) ) def getbalance(self): return self.__access.getbalance() def getnewaddress(self): return self.__access.getnewaddress(self.__user) def listunspent(self): return self.__access.listunspent() def listtransactions(self): if self.__account is None : return [] return self.__access.listtransactions(self.__account,10000,0) def sendto(self, to_addr, amnt, minconf = 3, comment = None ): if comment is not None : return self.__access.sendfrom(self.__user, to_addr, amnt, minconf, comment) else: return self.__access.sendfrom(self.__user, to_addr, amnt, minconf)
def UpdateFiles(): rpc = json.load(open("rpc.access")) rpc_daemon = ServiceProxy("http://"+rpc['user']+":"+rpc['pass']+"@blisterpool.com:52332") block = rpc_daemon.getinfo()['blocks'] blocksleft = 4000 - int(block)%4000 current_round = (int(block) + blocksleft)/4000 #print "current_round = %d" % current_round if blocksleft <= 2700: # the current payout block is still active current_round += 1 #print "current_round = %d" % current_round for round in range(current_round-1, current_round+1): try: # Now we know the round, we know which file to get path = 'http://d.evco.in/charity/receiver_'+str(round)+'.csv' #print "Attempting %s" % path f = urllib2.urlopen(path) data = f.read() with open("/home/amit/devcoin_countdown/www/static/receiver_"+str(round)+".csv", 'wb') as code: code.write(data) except: pass try: path = 'http://d.evco.in/charity/account_'+str(round)+'.csv' #print "Attempting %s" % path f = urllib2.urlopen(path) data = f.read() with open("/home/amit/devcoin_countdown/www/static/account_"+str(round)+".csv", 'wb') as code: code.write(data) except: pass try: path = 'http://d.evco.in/charity/devtome_'+str(round)+'.csv' #print "Attempting %s" % path f = urllib2.urlopen(path) data = f.read() with open("/home/amit/devcoin_countdown/www/static/devtome_"+str(round)+".csv", 'wb') as code: code.write(data) except: pass
class StockDataIcarra(StockData): def __init__(self): StockData.__init__(self) self.s = ServiceProxy("http://www.icarra.com/cgi-bin/webApi.py") def suggest(self, ticker): try: request = {"ticker": str(ticker)} return self.s.suggest(request) except Exception, e: print traceback.format_exc() appGlobal.setFailConnected(True) return False
def __init__(self, work_queue): super(BitcoinThread, self).__init__() self.queue = work_queue self.username = "" self.password = "" self.address = "" self.secure = False self.get_rpc_info() url = "http%s://%s:%s@%s" % \ ('s' if self.secure else '', self.username, self.password, self.address) self.rpc = ServiceProxy(url)
def runView(viewId, viewUrl, dbid, docid): logging.info('sending document to view: '+str(docid)) dataUrl=dataBase+dbid+'/'+docid data=callNode(viewUrl, dataUrl) if data!=None: logging.info('got view result: '+str(data)) key=data['key'] value=data['value'] db=Database.all().filter("dbid =", dbid).get() if db==None: logging.error("No such database "+str(dbid)) return view=Database.all().ancestor(db).filter("dbid =", viewId).get() if view==None: logging.error("No such database "+str(viewId)) return s=ServiceProxy(dataBase+'db') s.modify([dbid, viewId], [ ['add', [key, value]] ])
def __init__(self): self.s = ServiceProxy("http://www.icarra2.com/cgi-bin/webApi.py") self.db = Db(os.path.join(prefs.Prefs.prefsRootPath(), "stocks.db")) # TODO: make unique index on ticker self.db.checkTable("stockData", [ {"name": "ticker", "type": "text"}, {"name": "date", "type": "datetime"}, {"name": "open", "type": "float default 0.0"}, {"name": "high", "type": "float default 0.0"}, {"name": "low", "type": "float default 0.0"}, {"name": "close", "type": "float default 0.0"}, {"name": "volume", "type": "float default 0"}], index = [ {"name": "tickerDate", "cols": ["ticker", "date"]}]) self.db.checkTable("stockDividends", [ {"name": "ticker", "type": "text"}, {"name": "date", "type": "datetime"}, {"name": "value", "type": "float"}], index = [ {"name": "tickerDate", "cols": ["ticker", "date"]}]) self.db.checkTable("stockSplits", [ {"name": "ticker", "type": "text"}, {"name": "date", "type": "datetime"}, {"name": "value", "type": "float"}], index = [ {"name": "tickerDate", "cols": ["ticker", "date"]}]) self.db.checkTable("stockInfo", [ {"name": "ticker", "type": "text"}, {"name": "lastDownload", "type": "datetime"}, {"name": "icarraTicker", "type": "text"}, {"name": "name", "type": "text"}], unique = [ {"name": "ticker", "cols": ["ticker"]}]) self.db.checkTable("stockNews", [ {"name": "ticker", "type": "text"}, {"name": "date", "type": "datetime"}, {"name": "title", "type": "text"}, {"name": "summary", "type": "text"}, {"name": "rating", "type": "int"}, {"name": "url", "type": "text"}, {"name": "downloaded", "type": "bool default 0"}, {"name": "content", "type": "text"}], index = [ {"name": "tickerDate", "cols": ["ticker", "date"]}]) self.stocks = {}
def run(self): while True: task = self.queue.get() try: if task[0] == 'beat': ret = { 'connections': self.rpc.getconnectioncount(), 'balance': self.rpc.getbalance(), 'ubalance': self.rpc.getbalance('*', 0) } elif task[0] == 'get addresses': # listaddressgroupings can be used to find account balances used = self.rpc.listaddressgroupings() used = dict((x[0], x[1]) for sub in used for x in sub) # but if it hasn't been used, it won't be in the list # so merge it with a complete address listing every = self.rpc.listreceivedbyaddress(0, True) ret = [[x['address'], used[x['address']] if x['address'] in used else 0, x['account']] for x in every] elif task[0] == 'reconnect': self.get_rpc_info() url = "http://%s:%s@%s" % \ (self.username, self.password, self.address) self.rpc = ServiceProxy(url) elif task[0] == 'create address': ret = self.rpc.getnewaddress('default') elif task[0] == 'send to address': ret = self.rpc.sendtoaddress(*task[2:]) else: print 'Unknown command.' ret = False except JSONRPCException as ex: print repr(ex.error) except Exception as ex: if task[0] == 'beat': ret = False else: print "Exception: ", print ex finally: task[1](ret) self.queue.task_done()
class Submitter(Thread): def __init__(self, block, nonce, urlindex): Thread.__init__(self) self.block = block self.nonce = nonce self.urlindex = urlindex # Make a new proxy for sending, to avoid threading clashes self.proxy = ServiceProxy(options.url[self.urlindex]) def run(self): # This thread will be created upon every submit, as they may # come in sooner than the submits finish. print("Block found on " + ctime()) if stride > 0: n = self.nonce.encode('hex') print(n + " % " + str(stride) + " = " + str(int(n, 16) % stride)) elif options.debug: print(self.nonce.encode('hex')) hrnonce = self.nonce[::-1].encode('hex') data = self.block[:152] + hrnonce + self.block[160:] try: #result = proxies[self.urlindex].getwork(data) result = self.proxy.getwork(data) print("Upstream result: " + str(result)) except: print("RPC send error") # a sensible boolean for stats result = False if not result: penalties[self.urlindex].put(0) results_queue.put(result)
def main(): bitcoind = ServiceProxy("http://*****:*****@127.0.0.1:8332") while True: txs = get_transaction_log() merged_txs = merge_tx(txs) txs_with_change = add_tx_change(bitcoind,merged_txs) txs_left_to_process = txs_with_change while len(txs_left_to_process)>0: print len(txs_left_to_process) agregated_txs , tx_size, txs_left_to_process = aggregate_txs_for_max_tx(bitcoind,txs_left_to_process) txs_after_fee = remove_needed_change(tx_size,agregated_txs) txdata = create_tx(bitcoind,txs_after_fee) privatekeys = get_privatekeys(txs_after_fee) signed_rawtx = bitcoind.signrawtransaction(txdata, [], privatekeys) print signed_rawtx["complete"] print bitcoind.decoderawtransaction(signed_rawtx["hex"]) bitcoind.sendrawtransaction(signed_rawtx["hex"]) time.sleep(60*60*168)
def __init__(self, platform, context, host, user, password, port=8332, frames=60, rate=1, askrate=5, worksize=-1, vectors=False): Thread.__init__(self) (defines, self.rateDivisor) = if_else(vectors, ('-DVECTORS', 500), ('', 1000)) self.context = context self.rate = float(rate) self.askrate = int(askrate) self.worksize = int(worksize) self.frames = frames if (self.context.devices[0].extensions.find('cl_amd_media_ops') != -1): defines += ' -DBITALIGN' kernelFile = open('BitcoinMiner.cl', 'r') self.miner = cl.Program(self.context, kernelFile.read()).build(defines) kernelFile.close() if (self.worksize == -1): self.worksize = self.miner.search.get_work_group_info(cl.kernel_work_group_info.WORK_GROUP_SIZE, self.context.devices[0]) self.workQueue = Queue() self.resultQueue = Queue() self.bitcoin = ServiceProxy('http://%s:%s@%s:%s' % (user, password, host, port))
class Bt(object): """ BitCoin JSON-RPC interface class for payme """ def __init__(self, ip_addr="127.0.0.1", port="8332", user="******", password="******", app="payme"): bturl = "http://%s:%s@%s:%s" % (user, password, ip_addr, port) self.proxy = ServiceProxy(bturl) self.app = app def getaddress(self, user): """ Return a unique, persistent BT address for this user. Create a new address, if necessary """ # addresses are tagged in the bitcoin wallet via this naming convention account = self.app + "-" + user address_list = self.proxy.getaddressesbyaccount(account) if (len(address_list) > 0): return (address_list[0]) return self.proxy.getnewaddress(account) def getreceived(self, address): """ Return the amount received by this address """ return "%f" % self.proxy.getreceivedbyaddress(address, 0) def get_user_list(self): """ Return a list of dictionaries containing user ('user'), total received ('amount'), and current balance ('balance') """ user_list = self.proxy.listreceivedbyaccount(0, True) # limit the list to those fitting the naming convention user_list = [x for x in user_list if x['account'].find(self.app) == 0] # massage the list to format, add user name, and add balance spliceamt = len(self.app) + 1 for entry in user_list: entry['user'] = entry['account'][spliceamt:] entry['amountstr'] = "%f" % entry['amount'] entry['balance'] = self.proxy.getbalance(entry['account']) entry['balancestr'] = "%f" % entry['balance'] return (user_list) def harvest(self, address): """ transfer all non-zero user balances to 'address' """ user_list = self.get_user_list() for user in user_list: balance = user['balance'] account = user['account'] if balance > 0: print "Transferring %f from %s to %s" % (balance, account, address) self.proxy.sendfrom(account, address, balance)
print('This script generates a transaction to cleanup your wallet.') print( ' It looks for the single addresses which have the most small confirmed payments made to them and merges' ) print( ' all those payments, along with those for any addresses which are all tiny payments, to a single txout.' ) print( ' It must connect to bitcoin to inspect your wallet and to get fresh addresses to pay your coin to.' ) print( ' This script doesn\'t sign or send the transaction, it only generates the raw txn for you.' ) else: try: b = ServiceProxy(sys.argv[1]) b.getinfo() except: print("Couldn't connect to bitcoin") exit(1) min_fee = Decimal(sys.argv[2]) #Add up the number of small txouts and amounts assigned to each address. coins = b.listunspent(1, 99999999) scripts = {} for coin in coins: script = coin['scriptPubKey'] if script not in scripts: scripts[script] = (0, Decimal(0), 0) if (coin['amount'] < Decimal(25) and coin['amount'] >= Decimal(0.01) and coin['confirmations'] > 100):
from jsonrpc import ServiceProxy access = ServiceProxy("http://127.0.0.1:9335") pwd = raw_input("Enter old wallet passphrase: ") pwd2 = raw_input("Enter new wallet passphrase: ") access.walletpassphrasechange(pwd, pwd2)
# -*- coding: utf-8 -*- import json import urllib2 from decimal import Decimal from django.conf import settings from django.core.cache import cache from django.db import models from django.utils.translation import ugettext as _ from jsonrpc import ServiceProxy BITCOIND = ServiceProxy(settings.BITCOIND_CONNECTION_STRING) """ access.getbalance() access.getinfo() settxfee(0.00001) a.listaccounts() a.listtransactions(acc) """ # Start with hard-coded forex rates. Will be recalculated on creation of new wallet # If API for new rates fails, system will fall back to these rates CURRENCY_RATES = { 'USD': 1, 'EUR': 0.88, 'GBP': 0.79, 'AUD': 1.47, 'CAD': 1.32, 'JPY': 109.76 }
from jsonrpc import ServiceProxy import sys import string # ===== BEGIN USER SETTINGS ===== # if you do not set these you will be prompted for a password for every command rpcuser = "" rpcpass = "" # ====== END USER SETTINGS ====== if rpcpass == "": access = ServiceProxy("http://127.0.0.1:2332") else: access = ServiceProxy("http://" + rpcuser + ":" + rpcpass + "@127.0.0.1:2332") cmd = sys.argv[1].lower() if cmd == "backupwallet": try: path = raw_input("Enter destination path/filename: ") print access.backupwallet(path) except: print "\n---An error occurred---\n" elif cmd == "getaccount": try: addr = raw_input("Enter a Honkcoin address: ") print access.getaccount(addr) except: print "\n---An error occurred---\n"
from jsonrpc import ServiceProxy access = ServiceProxy("http://127.0.0.1:10109") pwd = raw_input("Enter wallet passphrase: ") access.walletpassphrase(pwd, 60)
#!/usr/bin/python # -*- coding: utf-8 -*- from devinclude import * from core.models import * import datetime from jsonrpc import ServiceProxy from django.db.models import Sum from django.core.mail import send_mail BITCOIND = ServiceProxy(settings.BITCOIND_CONNECTION_STRING) BITCOIND.settxfee(0) now = datetime.datetime.now() expired_tips = Tip.objects.filter(etime__lt=now, activated=False, wallet__activated=True, expired=False).order_by('wallet') # Step 1: move all the stuff to the special expired account expired = [] for tip in expired_tips: account = tip.wallet.get_account() BITCOIND.move(account, account + "_exp", tip.balance_btc) #print "BITCOINDD move(%s) %s, %s, %s"%(BITCOIND.getbalance(account),,account, account+"_exp", tip.balance_btc) if account not in expired: expired.append(account) tip.expired = True tip.save() # Step 2: get all the money from epxpired accounts and return to the wallet owner
from jsonrpc import ServiceProxy access = ServiceProxy( "http://*****:*****@50.66.72.155:9332") print access.getmininginfo()
def __init__(self, url): self.internal_proxy_obj = ServiceProxy(url)
from merkletools import * import cPickle as pickle from secp256k1 import PrivateKey, PublicKey import random, string import time import thread import requests import json EPOCH_TIME=1 gen_tx = "fc64c5ad44c7fd43891392699a5dfd9d499207ee6f073a85e67093897ed79456" rpc_user = "******" rpc_pwd = "gatto" rpc = ServiceProxy("http://%s:%[email protected]:18332/" % (rpc_user, rpc_pwd)) print rpc.getblockcount() rpc.generate(100) print rpc.getblockcount() my_tx = "fcd690be5e2b659fddf8770e67107087bcf5a620818d949f24b9cf3a30f631f9" unspent_txs = rpc.listunspent() #print rpc.listunspent() for utx in unspent_txs: if(utx['txid'] in my_tx): print utx sel_tx = utx
for d in data: dt = r2ordinal(d[0]) dates.append(dt) values.append(d[1]) fig = figure() ax = fig.add_subplot(111) ax.plot_date(dates, values, '-') ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(monthsFmt) ax.xaxis.set_minor_locator(mondays) ax.autoscale_view() ax.grid(True) fig.autofmt_xdate() show() if __name__ == '__main__': from jsonrpc import ServiceProxy s = ServiceProxy('http://localhost:8080/') N = len(sys.argv) window = 20 if N > 1: symbol = str(sys.argv[1]).upper() if N > 2: window = int(sys.argv[2]) else: symbol = 'GOOG' r = s.mean(symbol, window = window) plot(r)
from jsonrpc import ServiceProxy access = ServiceProxy("http://*****:*****@127.0.0.1:22823") access.getinfo() # что-то не работает. не может найти ServiceProxy в jsonrpc # разобраться позже
#!/usr/bin/python from jsonrpc import ServiceProxy PROXY = ServiceProxy("http://*****:*****@127.0.0.1:8332") BTINFO = PROXY.getinfo() print "BitCoin stats" for key in BTINFO.keys(): print " %s; %s" % (key, BTINFO[key]) print "See https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_Calls_list" print "for the full list of functions available"