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 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 decoderawtransaction(rawtx): bitcoin = ServiceProxy(BITCOINRPC) try: data=bitcoin.decoderawtransaction(rawtx) except JSONRPCException, e: return (False, "Error: %s" % e.error['message'])
class wallet: url = None name = '' algorithm = '' K = 100 access = None reward_history_limit = 10 height = 0 reward_history = list() difficulty = dict() def __init__(self, conf): self.name = conf['name'] self.url = conf['url'] if 'algorithm' in conf: self.algorithm = conf['algorithm'] if 'K' in conf: self.K = conf['K'] self.access = ServiceProxy(self.url, timeout=5) self.reward_history = list() self.difficulty = dict() def is_synced(self): try: info = self.access.getwork() return True except: return False def getDifficulty(self, algo=''): try: if algo == '': return self.difficulty[self.algorithm] else: return self.difficulty[algo] except: return 1e10 def getReward(self): try: average_reward = sum([r[1] for r in self.reward_history]) / len( self.reward_history) return average_reward except: return 0 def getHeight(self): return self.height def update(self, method='quick'): #Update info try: info = self.access.getinfo() #Load height height = info['blocks'] prev_height = self.height self.height = height #Load difficulty if isinstance(self.algorithm, basestring): #single algo wallet if 'difficulty' in info and isinstance( info['difficulty'], (int, long, float, complex)): self.difficulty[self.algorithm] = info['difficulty'] else: #work around for orbitcoin diff = self.access.getdifficulty() self.difficulty[self.algorithm] = diff['proof-of-work'] else: for algo in self.algorithm: try: key = algo #handle aliases key = alias(key, 'myr-gr', 'groestle', 'j', self.name) key = alias(key, 'myr-gr', 'groestl') key = alias(key, 'whirl', 'whirlpool') key = alias(key, 'penta', 'pentablake') key = alias(key, 'lyra2v2', 'lyra2re') key = alias(key, 'blake2s', 'blake') key = 'difficulty_%s' % key self.difficulty[algo] = info[key] except: print('Wallet %s: cannot find difficulty' % (self.name)) except: print('Wallet %s: network error' % (self.name)) return if method != 'quick': #Load blocks and compute block reward history i = max( [0, height - self.K + 1, prev_height + 1] ) #starts reading from 0, or current block, or K blocks before current while i <= height: try: hash = self.access.getblockhash(i) block = self.access.getblock(hash) if 'flags' in block and block['flags'] == 'proof-of-stake': #work around for hybrid POS/POW coins such as xlr pass else: for txid in block['tx']: try: txhash = self.access.getrawtransaction(txid) tx = self.access.decoderawtransaction(txhash) coinbase_tx_cnt = sum([ 1 for vin in tx['vin'] if 'coinbase' in vin ]) if coinbase_tx_cnt > 0: #Read reward as sum of all coinbase transactions #Does not really work for coins with dev fees reward = sum( [vout['value'] for vout in tx['vout']]) if self.name == 'chc': reward = reward / 8.0 * 4.4 elif self.name == 'flax': reward = reward / 0.71 * 0.48 elif self.name == 'sib': reward = reward / 2.0 elif self.name == 'bsd': reward = reward / 5.0 #25->5 elif self.name == 'xlr': reward = reward / 2.0 * 1.0 #2->1.0 self.reward_history.append((i, reward)) if len(self.reward_history ) > self.reward_history_limit: self.reward_history.pop(0) except: #If such transaction was not in the wallet, it would be impossible to read the transaction #print('Wallet %s: error reading tx %s'%(self.name,txid)); pass except: #print('Wallet %s: failed to read block hash %d/%d'%(self.name,i,height)); return i = i + 1 return
class CryptoAccount: def __init__(self, currency="BTC", account=None): self.__currency = currency self.__host = Settings[currency]["host"] self.__port = Settings[currency]["port"] self.__rpc_user = Settings[currency]["rpc_user"] self.__rpc_pwd = Settings[currency]["rpc_pwd"] self.__account = account self.__access = ServiceProxy("http://%s:%s@%s:%s" % (self.__rpc_user, self.__rpc_pwd, self.__host, self.__port)) def walletpassphrase(self, time=20): return self.__access.walletpassphrase(Settings[self.__currency]["pwd2"],time) def keypoolrefill(self, size=None): if size is None: return self.__access.keypoolrefill() else: return self.__access.keypoolrefill(size) def getrawmempool(self): return self.__access.getrawmempool() def getrawtransaction(self, txid): return self.__access.getrawtransaction(txid) def decoderawtransaction(self, hex_data): return self.__access.decoderawtransaction(hex_data) def listaddressgroupings(self): return self.__access.listaddressgroupings() def validateaddress(self, address): return self.__access.validateaddress(address) def settxfee(self, amnt): return self.__access.settxfee(amnt) def listsinceblock(self, hashblcok): return self.__access.listsinceblock(hashblcok) def getblockcount(self): return self.__access.getblockcount() def getblockhash(self, hs): return self.__access.getblockhash(hs) def getblock(self, hs): return self.__access.getblock(hs) def walletlock(self): return self.__access.walletlock() def dumpwallet(self, filename): return self.__access.dumpwallet(filename) def backupwallet(self, filename): return self.__access.backupwallet(filename) def dumpprivkey(self, Addr): return self.__access.dumpprivkey(Addr) def getbalance(self): return self.__access.getbalance() def getnewaddress(self): return self.__access.getnewaddress(self.__account) def listunspent(self): return self.__access.listunspent() def sendmany(self, to_addr): return self.__access.sendmany(self.__account, to_addr) def listtransactions(self): if self.__account is None : return [] return self.__access.listtransactions(self.__account,10000,0) def sendtoaddress(self, addr, amnt): return self.__access.sendtoaddress(addr, amnt) def sendto(self, to_addr, amnt, minconf = 3, comment = None ): if comment is not None : return self.__access.sendfrom(self.__account, to_addr, amnt, minconf, comment) else: return self.__access.sendfrom(self.__account, to_addr, amnt, minconf)
def decoderawtransaction(rawtx): bitcoin = ServiceProxy(BITCOINRPC) try: data = bitcoin.decoderawtransaction(rawtx) except JSONRPCException, e: return (False, "Error: %s" % e.error['message'])
def main(): global debug, version, conf_file server = "localhost" verbose = False replace = False parser = OptionParser(usage="%prog [-cdr] first [last]\n\nFor help try : %prog --help", formatter=IndentedHelpFormatter(), epilog="(Copyleft) 2016 - AWI : http://pool-prime.net/", description="Arguments:\t\t\t\t\t\t\t\t\t\t\tfirst: start to insert blocks from this block (default: 0)\t\t\t\tlast: stop to insert at this block (default is -1, means last received from primecoind)", version="%prog " + "%s" % version) parser.add_option("-c", "--conf", action="store", type="string", dest="conf", default=conf_file, help="configuration file (default: %default)") parser.add_option("-r", "--replace", action="store_true", dest="replace", default=replace, help="replace existing records (default: %default)") parser.add_option("-d", "--debug", action="store_true", dest="debug", default=debug, help="verbose logging (default: %default)") (options, args) = parser.parse_args() debug = options.debug replace = options.replace conf_file = options.conf conf_file = os.path.expanduser(conf_file) if debug: print("options=%s, args=%s" % (options, args )) if len(args): if len(args) == 1: first = int(args[0]) last = -1 else: if len(args) == 2: first = int(args[0]) last = int(args[1]) else: parser.error("no more than 2 arguments...") else: last = -1 first = -1 content = "Can not read %s (perhaps need to be in bitcoin group ?)" % conf_file try: conf = open(conf_file, 'r') content = conf.read() conf.close() except: pass user = password = "" port = 9912 for line in content.split(): if "rpcuser" in line: (tmp, user) = line.split('=',1) if "rpcpassword" in line: (tmp, password) = line.split('=',1) if "rpcport" in line: (tmp, ports) = line.split('=',1) port = int(ports) if debug: print("port=%d, user=%s, password=%s" % (port, user, password)) if jrpc: primecoind = ServiceProxy("http://%s:%[email protected]:%d" % (user, password,port)) else: primecoind = bitcoin.rpc.RawProxy("http://%s:%[email protected]:%d" % (user, password,port)) # Yes, it means that you need to use same user:password for primecoind and couchdb admin... # if not, fix value here # user = "******" # password = "******" couchdb = Server(url='http://%s:%s@localhost:5984/' % (user, password)) cdb = cdb_connect(couchdb, "xpm") if first < 0: #headers = {"Content-type": "application/json"} #r = requests.get("http://localhost:5984/xpm/_design/block/_view/last?limit=1&descending=true", headers=headers) #rec = r.json() #first = int(rec["rows"][0]["key"]) + 1 row = cdb.view("_design/block/_view/by_height", limit=1, descending=True) if row: first = int(list(row)[0].key) + 1 else: first = 0 if last < 0: last = int(primecoind.getblockcount()) + 1 if debug: print("Let's go for blocks from %d to %d :" % (first, last)) if primecoind and cdb: for current in range(first, last): blk_hash = primecoind.getblockhash(current) block = primecoind.getblock(blk_hash) dte = datetime.utcfromtimestamp(block['time']) when = [dte.year, dte.month, dte.day, dte.hour, dte.minute, dte.second] block["_id"] = blk_hash block["date"] = when block["type"] = "block" if debug: print("xpm:primecoind:%s" % (block)) for txid in block['tx']: # Only block 0 should have no trans if current: rawtrans = primecoind.getrawtransaction(txid) trans = primecoind.decoderawtransaction(rawtrans) trans["raw"] = rawtrans if debug: print("%s:%s" % (current,txid)) trans["_id"] = txid trans["height"] = current trans["date"] = when trans["type"] = "trans" if replace: record = cdb.get(txid) if record: if debug: print("%s:%s trans already exist..." % (record.id, record.rev)) cdb.delete(record) cdb.save(trans) if replace: record = cdb.get(blk_hash) if record: if debug: print("%s:%s block already exist..." % (record.id, record.rev)) cdb.delete(record) cdb.save(block) print("%d:%d-%d-%d:%d:%d:%s(%d)" % (current, dte.year,dte.month,dte.day, dte.hour, dte.minute,blk_hash,len(block['tx']))) return(0) else: return(-1)
import json from jsonrpc import ServiceProxy, JSONRPCException access = ServiceProxy( "http://*****:*****@127.0.0.1:19345" ) print '------------- get raw transaction ---------' trans = access.getrawtransaction( '0a2dfcdf8e0b75c522394f34eb6a62a8242b28e4bc763016fa13470b9cadb124', 0) print trans print 'decoded: %s' % (access.decoderawtransaction(trans))
class rpcdump: def __init__(self,url): self.s = ServiceProxy("http://%s" % url) self.set2Begin() def set2Begin(self): self.current=self.getHash(0) return self.current def setCurrent(self,h): self.current=self.getHash(h) return self.current def getCurrent(self): return self.current def next(self): self.current=self.nextBlock(self.current) return self.current def previous(self): self.current=self.previousBlock(self.current) return self.current def set2End(self): self.current=self.getHash(self.getTop()) return self.current def getTop(self): info = self.s.getinfo() return info['blocks']-1 def getHash(self,height): return self.s.getblockhash(height) def nextBlock(self,h): block = self.getBlock(h) if 'nextblockhash' in block: return block['nextblockhash'] else: return None def previousBlock(self,h): block = self.getBlock(h) if 'previousblockhash' in block: return block['previousblockhash'] else: return None def getBlock(self,h): block = self.s.getblock(h) dump = {} for key in ['previousblockhash','nextblockhash','tx','time','height']: if key in block: dump[key]=block[key] dump['type']='block' dump['_id']=block['hash'] return dump def getTx(self,txid): try: txraw = self.s.getrawtransaction(txid) tx = self.s.decoderawtransaction(txraw) dump = {} dump['type']='tx' dump['_id']=tx['txid'] dump['vin']=[] for x in tx['vin']: y={} for key in ['coinbase','txid','vout']: if key in x: y[key]=x[key] dump['vin'].append(y) dump['vout']=tx['vout'] for x in dump['vout']: if 'scriptPubKey' in x: for key in ['asm','hex','reqSigs']: if key in x['scriptPubKey']: del x['scriptPubKey'][key] return dump except: pass return None