def home(DB, dic): if 'BrainWallet' in dic: dic['privkey'] = tools.det_hash(dic['BrainWallet']) elif 'privkey' not in dic: return "<p>You didn't type in your brain wallet.</p>" privkey = dic['privkey'] pubkey = tools.privtopub(dic['privkey']) address = tools.make_address([pubkey], 1) if 'do' in dic: if dic['do'] == 'spend': spend(float(dic['amount']), pubkey, privkey, dic['to'], DB) out = empty_page out = out.format('<p>your address: ' + str(address) + '</p>{}') out = out.format('<p>current block: ' + str(DB['length']) + '</p>{}') balance = blockchain.db_get(address, DB)['amount'] for tx in DB['txs']: if tx['type'] == 'spend' and tx['to'] == address: balance += tx['amount'] - custom.fee if tx['type'] == 'spend' and tx['pubkeys'][0] == pubkey: balance -= tx['amount'] out = out.format('<p>current balance is: ' + str(balance/100000.0) + '</p>{}') if balance > 0: out = out.format(easyForm('/home', 'spend money', ''' <input type="hidden" name="do" value="spend"> <input type="text" name="to" value="address to give to"> <input type="text" name="amount" value="amount to spend"> <input type="hidden" name="privkey" value="{}">'''.format(privkey))) txt=''' <input type="hidden" name="privkey" value="{}">''' s = easyForm('/home', 'Refresh', txt.format(privkey)) return out.format(s)
def home(DB, dic): if 'BrainWallet' in dic: dic['privkey']=tools.det_hash(dic['BrainWallet']) elif 'privkey' not in dic: return "<p>You didn't type in your brain wallet.</p>" privkey=dic['privkey'] pubkey=tools.privtopub(dic['privkey']) address=tools.make_address([pubkey], 1) if 'do' in dic.keys(): if dic['do']=='spend': spend(float(dic['amount']), pubkey, privkey, dic['to'], DB) out=empty_page out=out.format('<p>your address: ' +str(address)+'</p>{}') out=out.format('<p>current block: ' +str(DB['length'])+'</p>{}') balance=blockchain.db_get(address, DB)['amount'] for tx in DB['txs']: if tx['type'] == 'spend' and tx['to'] == address: balance += tx['amount'] - custom.fee if tx['type'] == 'spend' and tx['pubkeys'][0] == pubkey: balance -= tx['amount'] out=out.format('<p>current balance is: ' +str(balance/100000.0)+'</p>{}') if balance>0: out=out.format(easyForm('/home', 'spend money', ''' <input type="hidden" name="do" value="spend"> <input type="text" name="to" value="address to give to"> <input type="text" name="amount" value="amount to spend"> <input type="hidden" name="privkey" value="{}">'''.format(privkey))) txt=''' <input type="hidden" name="privkey" value="{}">''' s=easyForm('/home', 'Refresh', txt.format(privkey)) return out.format(s)
def main(c=0): if type(c)==int: p={'command':sys.argv[1:]} else: p={'command':c} if len(p['command'])==0: p['command'].append(' ') c=p['command'] if c[0]=='make_PM': tx=build_pm() return run_command({'command':['pushtx', tools.package(tx).encode('base64')]}) elif c[0]=='buy_shares': tx=build_buy_shares() return run_command({'command':['pushtx', tools.package(tx).encode('base64')]}) elif c[0]=='start': r=connect({'command':'blockcount'}) if is_off(r): p=raw_input('what is your password?\n') daemonize(lambda: threads.main(p)) else: print('blockchain is already running') elif c[0]=='new_address': if len(c)<2: print('what is your brain wallet? not enough inputs.') else: privkey=tools.det_hash(c[1]) pubkey=tools.privtopub(privkey) address=tools.make_address([pubkey], 1) return({'brain':str(c[1]), 'privkey':str(privkey), 'pubkey':str(pubkey), 'address':str(address)}) else: return run_command(p)
def easy_add_transaction(tx_orig, privkey='default'): tx = copy.deepcopy(tx_orig) if privkey in ['default', 'Default']: if tools.db_existence('privkey'): privkey = tools.db_get('privkey') else: return 'No private key is known, so the tx cannot be signed. ' pubkey = tools.privtopub(privkey) address = tools.make_address([pubkey], 1) if 'count' not in tx: try: tx['count'] = tools.count(address, {}) except: tx['count'] = 1 # add our pubkey if 'pubkeys' not in tx: tx['pubkeys'] = [pubkey] # this is IMPORTANT # when adding new transaction which is signed by us, # this procedure is applied. tx without signatures is signed with our privkey. if 'signatures' not in tx: tx['signatures'] = [tools.sign(tools.det_hash(tx), privkey)] return blockchain.add_tx(tx)
def sign(tx, privkey): pubkey = tools.privtopub(privkey) address = tools.make_address([pubkey], 1) if 'pubkeys' not in tx: tx['pubkeys'] = [pubkey] if 'signatures' not in tx: tx['signatures'] = [tools.sign(tools.det_hash(tx), privkey)] return tx
def sign(tx, privkey): pubkey=tools.privtopub(privkey) address=tools.make_address([pubkey], 1) if 'pubkeys' not in tx: tx['pubkeys']=[pubkey] if 'signatures' not in tx: tx['signatures']=[tools.sign(tools.det_hash(tx), privkey)] return tx
def easy_add_transaction(tx_orig, privkey, DB): tx=copy.deepcopy(tx_orig) pubkey=tools.privtopub(privkey) try: tx['count']=blockchain.count(pubkey, DB) except: tx['count']=1 tx['signature']=tools.sign(tools.det_hash(tx), privkey) blockchain.add_tx(tx, DB)
def sign(tx, privkey): pubkey = tools.privtopub(privkey) address = tools.make_address([pubkey], 1) tx = add_recent_hash(tx) if "pubkeys" not in tx: tx["pubkeys"] = [pubkey] if "signatures" not in tx: tx["signatures"] = [tools.sign(tools.det_hash(tx), privkey)] return tx
def easy_add_transaction(tx_orig, privkey, DB): tx = copy.deepcopy(tx_orig) pubkey = tools.privtopub(privkey) address = tools.make_address([pubkey], 1) try: tx['count'] = blockchain.count(address, DB) except: tx['count'] = 1 tx['signatures'] = [tools.sign(tools.det_hash(tx), privkey)] blockchain.add_tx(tx, DB)
def easy_add_transaction(tx_orig, privkey, DB): tx=copy.deepcopy(tx_orig) pubkey=tools.privtopub(privkey) address=tools.make_address([pubkey], 1) try: tx['count']=blockchain.count(address, DB) except: tx['count']=1 tx['signatures']=[tools.sign(tools.det_hash(tx), privkey)] blockchain.add_tx(tx, DB)
def easy_add_transaction(tx_orig, DB, privkey='default'): tx = copy.deepcopy(tx_orig) try: tx['count'] = tools.count(DB['address'], DB) except: tx['count'] = 1 if privkey=='default': if 'privkey' in DB: privkey=DB['privkey'] else: return('no private key is known, so the tx cannot be signed. Here is the tx: \n'+str(tools.package(tx_orig).encode('base64').replace('\n', ''))) if 'pubkeys' not in tx: tx['pubkeys']=[tools.privtopub(privkey)] tx['signatures'] = [tools.sign(tools.det_hash(tx), privkey)] tools.log('collect winnings 3') return(blockchain.add_tx(tx, DB))
def trade_shares(DB, args): #args = [ PM_id, buy ] privkey = tools.db_get('privkey') pubkey = tools.privtopub(privkey) address = tools.make_address([pubkey], 1) tx = { 'type': 'buy_shares', 'PM_id': args[0], 'buy': csv2vec(args[1]), 'pubkeys': [pubkey], 'count': tools.count(address, {}) } cost = txs_tools.cost_to_buy_shares(tx) tx['price_limit'] = int(cost * 1.01) + 1 tx = tools.unpackage(tools.package(tx)) tx = tools.POW(tx) tx['signatures'] = [tools.sign(tools.det_hash(tx), privkey)] return easy_add_transaction(tx, DB, privkey)
def common_buy_shares(tx, num_states, brainwallet): privkey = tools.det_hash(brainwallet) pubkey = tools.privtopub(privkey) address = tools.make_address([pubkey], 1) tx['pubkeys'] = [pubkey] tx['count'] = tools.count(address, {}) cost = txs_tools.cost_to_buy_shares(tx) tx['price_limit'] = int(cost * 1.01) + 1 print( 'now for a little proof of work. This may take several minutes. The purpose of this pow is to make it more difficult for a front runner to steal your trade.' ) tx = tools.unpackage(tools.package(tx)) tx = tools.POW(tx) tx['signatures'] = [tools.sign(tools.det_hash(tx), privkey)] print('tx for copy/pasting into pushtx: ' + tools.package(tx).encode('base64')) return tx
def easy_add_transaction(tx_orig, DB, privkey='default'): tx = copy.deepcopy(tx_orig) if privkey in ['default', 'Default']: if tools.db_existence('privkey'): privkey=tools.db_get('privkey') else: return('no private key is known, so the tx cannot be signed. Here is the tx: \n'+str(tools.package(tx_orig).encode('base64').replace('\n', ''))) pubkey=tools.privtopub(privkey) address=tools.make_address([pubkey], 1) if 'count' not in tx: try: tx['count'] = tools.count(address, {}) except: tx['count'] = 1 if 'pubkeys' not in tx: tx['pubkeys']=[pubkey] if 'signatures' not in tx: tx['signatures'] = [tools.sign(tools.det_hash(tx), privkey)] return(blockchain.add_tx(tx, DB))
def easy_add_transaction(tx_orig, DB, privkey='default'): tx = copy.deepcopy(tx_orig) if privkey in ['default', 'Default']: if tools.db_existence('privkey'): privkey = tools.db_get('privkey') else: return ('no private key is known, so the tx cannot be signed. Here is the tx: \n' + str( tools.package(tx_orig).encode('base64').replace('\n', ''))) pubkey = tools.privtopub(privkey) address = tools.make_address([pubkey], 1) if 'count' not in tx: try: tx['count'] = tools.count(address, {}) except: tx['count'] = 1 if 'pubkeys' not in tx: tx['pubkeys'] = [pubkey] if 'signatures' not in tx: tx['signatures'] = [tools.sign(tools.det_hash(tx), privkey)] return (blockchain.add_tx(tx, DB))
def build_buy_shares(): tx={'type':'buy_shares', 'PM_id':str(raw_input('What is the unique name for this prediction market?\n>'))} num_states=int(raw_input('how many states does this pm have?\n>')) tx['buy']=[] for i in range(num_states): tx['buy'].append(int(raw_input('how many shares do you want to buy of state '+str(i)+'? To sell states, use negative numbers.\n>'))) brainwallet=str(raw_input('What is your brainwallet\n>')) privkey=tools.det_hash(brainwallet) pubkey=tools.privtopub(privkey) address=tools.make_address([pubkey], 1) tx['pubkeys']=[pubkey] tx['count'] = tools.count(address, {}) cost=txs_tools.cost_to_buy_shares(tx) tx['price_limit']=int(cost*1.01) print('now for a little proof of work. This may take several minutes. The purpose of this pow is to make it more difficult for a front runner to steal your trade.') tx=tools.unpackage(tools.package(tx)) tx=tools.POW(tx) tx['signatures']=[tools.sign(tools.det_hash(tx), privkey)] print('tx for copy/pasting into pushtx: '+tools.package(tx).encode('base64')) return tx
def main(): info=sys.argv p={'command':sys.argv[1:]} if len(p['command'])==0: p['command'].append(' ') c=p['command'] if c[0]=='make_PM': tx=build_pm() run_command({'command':['pushtx', tools.package(tx).encode('base64')]}) elif c[0]=='buy_shares': tx=build_buy_shares() run_command({'command':['pushtx', tools.package(tx).encode('base64')]}) elif c[0]=='start': r=connect({'command':'blockcount'}) if is_truthcoin_off(r): p=raw_input('what is your password?\n') if sys.platform == 'win32': pypath = list(os.path.split(sys.executable)) pypath[-1] = 'pythonw.exe' os.system('start '+os.path.join(*pypath)+' threads.py '+p) sys.exit(0) else: daemonize(lambda: threads.main(p)) else: print('truthcoin is already running') elif c[0]=='new_address': if len(c)<2: print('what is your brain wallet? not enough inputs.') else: privkey=tools.det_hash(c[1]) pubkey=tools.privtopub(privkey) address=tools.make_address([pubkey], 1) print('brain: ' +str(c[1])) print('privkey: ' +str(privkey)) print('pubkey: ' +str(pubkey)) print('address: ' +str(address)) else: run_command(p)
def main(brainwallet, pubkey_flag=False): DB=custom.DB tools.log('custom.current_loc: ' +str(custom.current_loc)) print('starting truthcoin') if not pubkey_flag: privkey=tools.det_hash(brainwallet) pubkey=tools.privtopub(privkey) else: pubkey=brainwallet a=tools.empty_peer() a['port']=custom.port b=custom.peers my_ip=tools.getPublicIp() b[my_ip+':'+str(custom.port)]=a processes= [ {'target': blockchain.main, 'args': (DB,), 'name': 'blockchain'}, {'target': truthcoin_api.main, 'args': (DB, DB['heart_queue']), 'name': 'truthcoin_api'}, {'target': peers_check.main, 'args': (b, DB), 'name': 'peers_check'}, {'target': miner.main, 'args': (pubkey, DB), 'name': 'miner'}, {'target': networking.serve_forever, 'args': (peer_recieve_func, custom.port, DB['heart_queue'], True), 'name': 'peer_recieve'} ] cmds=[database.DatabaseProcess( DB['heart_queue'], custom.database_name, tools.log, custom.database_port)] try: cmds[0].start() except Exception as exc: tools.log(exc) tools.log('starting ' + cmds[0].name) time.sleep(4) tools.db_put('test', 'TEST') tools.db_get('test') tools.db_put('test', 'undefined') b=tools.db_existence(0) if not b: tools.db_put('ip', my_ip) tools.db_put('length', -1) tools.db_put('memoized_votes', {}) tools.db_put('txs', []) tools.db_put('peers', {}) tools.db_put('targets', {}) tools.db_put('times', {}) tools.db_put('mine', False) tools.db_put('diffLength', '0') tools.db_put('stop', False) tools.log('stop: ' +str(tools.db_get('stop'))) for process in processes: cmd=multiprocessing.Process(**process) cmd.start() cmds.append(cmd) tools.log('starting '+cmd.name) if not pubkey_flag: tools.db_put('privkey', privkey) else: tools.db_put('privkey', 'Default') tools.db_put('address', tools.make_address([pubkey], 1)) tools.log('stop: ' +str(tools.db_get('stop'))) while not tools.db_get('stop'): time.sleep(0.5) tools.log('about to stop threads') DB['heart_queue'].put('stop') for p in [[custom.port, '127.0.0.1'], [custom.api_port, '127.0.0.1']]: networking.connect('stop', p[0], p[1]) cmds.reverse() for cmd in cmds[:-1]: cmd.join() tools.log('stopped a thread: '+str(cmd)) time.sleep(2) networking.connect('stop', custom.database_port, '127.0.0.1') cmds[-1].join() tools.log('stopped a thread: '+str(cmds[-1])) tools.log('all threads stopped') sys.exit(0)
gui_port = 8700 version = "VERSION" block_reward = 10**5 premine = 5 * 10**6 fee = 10**3 # Lower limits on what the "time" tag in a block can say. mmm = 100 # Take the median of this many of the blocks. # How far back in history do we look when we use statistics to guess at # the current blocktime and difficulty. history_length = 400 # This constant is selected such that the 50 most recent blocks count for 1/2 the # total weight. inflection = 0.985 download_many = 500 # Max number of blocks to request from a peer at the same time. max_download = 50000 brainwallet = 'brain wallet' privkey = tools.det_hash(brainwallet) pubkey = tools.privtopub(privkey) master_pubkey = tools.privtopub(privkey) peers = [['localhost', 8901], ['localhost', 8902], ['localhost', 8903], ['localhost', 8904], ['localhost', 8905]] hashes_per_check = 10**5 def blocktime(length): if length * block_reward < premine: return 30 # seconds else: return 60
def main(wallet_name='', key=''): tools.log('custom.current_loc: ' + str(custom.current_loc)) print('Starting Coinami Client ...') b = tools.db_existence('length') # Initialize the db if not b: tools.db_put('length', -1) tools.db_put('memoized_votes', {}) tools.db_put('txs', []) tools.db_put('peers_ranked', []) tools.db_put('times', {}) tools.db_put('mine', False) tools.db_put('peers', []) tools.db_put('authorities', []) tools.db_put('miner_status', 'Uninitialized') tools.db_put('miner_id', -1) tools.db_put('default_wallet', False) tools.db_put('stop', False) tools.log('stop: ' + str(tools.db_get('stop'))) wallet = {} if key == '': wallet['valid'] = False wallet['message'] = 'Please define a passphrase to open the wallet' if wallet_name == '': wallet_name = tools.db_get('default_wallet') if not tools.db_get('default_wallet'): wallet['valid'] = False wallet['message'] = 'There is no defined default wallet. You need to specify one.' else: wallet = tools.read_wallet(wallet_name, key) elif wallet_name != '': wallet = tools.read_wallet(wallet_name, key) if not wallet['valid']: print wallet['message'] sys.exit(0) # Take the initial peer and authority list over here. Also a download link for executable. # Download can be started when miner is opened for the first time. # Peers and authorities must be set immediately. seed = str(wallet['seed']) try: info = json.loads(urllib2.urlopen(custom.info_address).read()) except: print 'Could not read info file' sys.exit(0) peers = [] for authority in info['authorities']: peers.append([authority['ip'], authority['port']]) authorities = [] for authority in info['authorities']: authorities.append(authority['pubkey']) tools.db_put('seed', seed) tools.db_put('info', info) tools.db_put('peers', peers) tools.db_put('authorities', authorities) tools.db_put('default_wallet', wallet_name) privkey = tools.det_hash(wallet['seed']) pubkey = tools.privtopub(privkey) tools.db_put('privkey', privkey) tools.db_put('pubkey', pubkey) processes = [ {'target': tools.heart_monitor, 'name': 'heart_monitor'}, {'target': blockchain.main, 'name': 'blockchain'}, {'target': api.main, 'name': 'api'}, {'target': peers_check.main, 'args': (tools.db_get('peers'),), 'name': 'peers_check'}, {'target': networking.serve_forever, 'args': (peer_recieve_func, custom.port, custom.queues['heart_queue'], True), 'name': 'peer_recieve'}, {'target': miner.main, 'args': (pubkey, ), 'name': 'miner'} ] running_processes = [] for process in processes[1:]: cmd = multiprocessing.Process(**process) cmd.start() running_processes.append(cmd) tools.log('starting ' + cmd.name) tools.db_put('address', tools.make_address([pubkey], 1)) tools.log('stop: ' + str(tools.db_get('stop'))) # until stop command puts into db, threads module will stay in this loop while not tools.db_get('stop'): time.sleep(0.5) # start the stopping custom.queues['heart_queue'].put('stop') for p in [[custom.port, '127.0.0.1'], [custom.api_port, '127.0.0.1']]: networking.connect('stop', p[0], p[1]) running_processes.reverse() # process = psutil.Process(os.getpid()) # for proc in process.get_children(recursive=True): # print proc.pid # proc.kill() time.sleep(2) for cmd in running_processes[:-1]: print 'im waiting for %s' % str(cmd) cmd.terminate() cmd.join() print('all processes stopped') sys.exit(0)
def main(wallet_name='', key=''): tools.log('custom.current_loc: ' + str(custom.current_loc)) print('Starting Coinami Client ...') b = tools.db_existence('length') # Initialize the db if not b: tools.db_put('length', -1) tools.db_put('memoized_votes', {}) tools.db_put('txs', []) tools.db_put('peers_ranked', []) tools.db_put('times', {}) tools.db_put('mine', False) tools.db_put('peers', []) tools.db_put('authorities', []) tools.db_put('miner_status', 'Uninitialized') tools.db_put('miner_id', -1) tools.db_put('default_wallet', False) tools.db_put('stop', False) tools.log('stop: ' + str(tools.db_get('stop'))) wallet = {} if key == '': wallet['valid'] = False wallet['message'] = 'Please define a passphrase to open the wallet' if wallet_name == '': wallet_name = tools.db_get('default_wallet') if not tools.db_get('default_wallet'): wallet['valid'] = False wallet[ 'message'] = 'There is no defined default wallet. You need to specify one.' else: wallet = tools.read_wallet(wallet_name, key) elif wallet_name != '': wallet = tools.read_wallet(wallet_name, key) if not wallet['valid']: print wallet['message'] sys.exit(0) # Take the initial peer and authority list over here. Also a download link for executable. # Download can be started when miner is opened for the first time. # Peers and authorities must be set immediately. seed = str(wallet['seed']) try: info = json.loads(urllib2.urlopen(custom.info_address).read()) except: print 'Could not read info file' sys.exit(0) peers = [] for authority in info['authorities']: peers.append([authority['ip'], authority['port']]) authorities = [] for authority in info['authorities']: authorities.append(authority['pubkey']) tools.db_put('seed', seed) tools.db_put('info', info) tools.db_put('peers', peers) tools.db_put('authorities', authorities) tools.db_put('default_wallet', wallet_name) privkey = tools.det_hash(wallet['seed']) pubkey = tools.privtopub(privkey) tools.db_put('privkey', privkey) tools.db_put('pubkey', pubkey) processes = [{ 'target': tools.heart_monitor, 'name': 'heart_monitor' }, { 'target': blockchain.main, 'name': 'blockchain' }, { 'target': api.main, 'name': 'api' }, { 'target': peers_check.main, 'args': (tools.db_get('peers'), ), 'name': 'peers_check' }, { 'target': networking.serve_forever, 'args': (peer_recieve_func, custom.port, custom.queues['heart_queue'], True), 'name': 'peer_recieve' }, { 'target': miner.main, 'args': (pubkey, ), 'name': 'miner' }] running_processes = [] for process in processes[1:]: cmd = multiprocessing.Process(**process) cmd.start() running_processes.append(cmd) tools.log('starting ' + cmd.name) tools.db_put('address', tools.make_address([pubkey], 1)) tools.log('stop: ' + str(tools.db_get('stop'))) # until stop command puts into db, threads module will stay in this loop while not tools.db_get('stop'): time.sleep(0.5) # start the stopping custom.queues['heart_queue'].put('stop') for p in [[custom.port, '127.0.0.1'], [custom.api_port, '127.0.0.1']]: networking.connect('stop', p[0], p[1]) running_processes.reverse() # process = psutil.Process(os.getpid()) # for proc in process.get_children(recursive=True): # print proc.pid # proc.kill() time.sleep(2) for cmd in running_processes[:-1]: print 'im waiting for %s' % str(cmd) cmd.terminate() cmd.join() print('all processes stopped') sys.exit(0)
def main(brainwallet, pubkey_flag=False): DB = custom.DB tools.log('custom.current_loc: ' + str(custom.current_loc)) print('starting full node') if not pubkey_flag: privkey = tools.det_hash(brainwallet) pubkey = tools.privtopub(privkey) else: pubkey = brainwallet a = tools.empty_peer() b = custom.peers #b[tools.getPublicIp()+':'+str(custom.port)]=a processes = [ { 'target': db.main, 'args': (DB['heart_queue'], custom.database_name, tools.log, custom.database_port), 'name': 'db' }, { 'target': auto_signer.mainloop, 'args': (), 'name': 'auto_signer' }, { 'target': reward_collector.doit, 'args': (), 'name': 'auto_signer' }, #{'target':tools.heart_monitor, # 'args':(DB['heart_queue'], ), # 'name':'heart_monitor'}, { 'target': blockchain.main, 'args': (DB, ), 'name': 'blockchain' }, { 'target': api.main, 'args': (DB, DB['heart_queue']), 'name': 'api' }, { 'target': peers_check.main, 'args': (b, DB), 'name': 'peers_check' }, { 'target': networking.serve_forever, 'args': (peer_recieve_func, custom.port, DB['heart_queue'], True), 'name': 'peer_recieve' } ] cmds = [] cmd = multiprocessing.Process(**processes[0]) cmd.start() cmds.append(cmd) tools.log('starting ' + cmd.name) time.sleep(4) b = tools.db_existence(0) #def empty_memoized(): return({'blockcount':-3000}) if not b: tools.local_put('length', -1) tools.local_put('height', -1) tools.local_put('memoized_votes', {}) tools.local_put('txs', []) tools.local_put('peers', {}) tools.local_put('targets', {}) tools.local_put('times', {}) tools.local_put('mine', False) tools.local_put('my_sign_txs', {}) #empty_memoized()) tools.local_put('secrets', {}) money = db.default_entry() money['amount'] += custom.all_money tools.db_put(custom.creator, money) tools.local_put('stop', False) tools.log('stop: ' + str(tools.local_get('stop'))) for process in processes[1:]: cmd = multiprocessing.Process(**process) cmd.start() cmds.append(cmd) tools.log('starting ' + cmd.name) if not pubkey_flag: tools.local_put('privkey', privkey) else: tools.local_put('privkey', 'Default') Address = tools.make_address([pubkey], 1) tools.local_put('address', Address) a = tools.db_proof(Address) tools.local_put('balance_proofs-1', a) tools.log('stop: ' + str(tools.local_get('stop'))) while not tools.local_get('stop'): time.sleep(0.5) tools.log('about to stop threads') DB['heart_queue'].put('stop') for p in [[custom.port, '127.0.0.1'], [custom.api_port, '127.0.0.1']]: networking.connect('stop', p[0], p[1]) cmds.reverse() for cmd in cmds[:-1]: cmd.join() tools.log('stopped a thread: ' + str(cmd)) time.sleep(2) networking.connect('stop', custom.database_port, '127.0.0.1') cmds[-1].join() tools.log('stopped a thread: ' + str(cmds[-1])) tools.log('all threads stopped') sys.exit(0)
def home(DB, dic): def display_msg(msg): try: return str(msg['msg']) + ' : ' + str(msg['reputation'] / 100000.0) except: return str(msg['msg']) + ' : ' + str(msg['amount'] / 100000.0) def display_posts(posts, parent, tabs): out = '{}' if tabs > 2: return out for pos in posts: id_ = transactions.postid(pos) if pos['parent'] == parent: bumper = '<div class="contentcontainer med left" style="margin-left: ' + str( 100 * tabs) + 'px;"><p>{}</p></div>' if pos in zeroth_confirmations: print('pos: ' + str(pos)) out = out.format(bumper.format(display_msg(pos)) + '{}') else: txt = bumper.format( easyForm( '/home', display_msg(pos), ''' <input type="hidden" name="location" value="{}"> <input type="hidden" name="parent" value="{}"> <input type="hidden" name="privkey" value="{}">'''.format( id_, id_, privkey))).format('') + '{}' out = out.format(txt) out = out.format(display_posts(posts, id_, tabs + 1)) return out def balance_(address, DB): balance = blockchain.db_get(address, DB)['amount'] for tx in DB['txs']: if tx['type'] == 'spend': if tx['to'] == address: balance += tx['amount'] if tx['pubkeys'][0] == pubkey: balance -= tx['amount'] + custom.fee if tx['type'] == 'post': if tx['pubkeys'][0] == pubkey: balance -= tx['amount'] + custom.fee return balance if 'BrainWallet' in dic: dic['privkey'] = tools.det_hash(dic['BrainWallet']) elif 'privkey' not in dic: return "<p>You didn't type in your brain wallet.</p>" privkey = dic['privkey'] pubkey = tools.privtopub(dic['privkey']) address = tools.make_address([pubkey], 1) balance = balance_(address, DB) doFunc = { 'spend': (lambda dic: spend(float(dic['amount']), pubkey, privkey, dic[ 'to'], DB)), 'post': (lambda dic: post(float(dic['amount']), pubkey, privkey, dic[ 'msg'], dic['parent'], DB)), 'vote': (lambda dic: vote(float(dic['amount']), pubkey, privkey, dic[ 'location'], DB)) } try: if 'do' in dic.keys(): doFunc[dic['do']](dic) except: pass out = empty_page out = out.format('<p>your address: ' + str(address) + '</p>{}') out = out.format('<p>current block: ' + str(DB['length']) + '</p>{}') out = out.format('<p>current balance is: ' + str(balance / 100000.0) + '</p>{}') if balance > 0: out = out.format( easyForm( '/home', 'spend money', ''' <input type="hidden" name="location" value="{}"> <input type="hidden" name="do" value="spend"> <input type="text" name="to" value="address to give to"> <input type="text" name="amount" value="amount to spend"> <input type="hidden" name="privkey" value="{}">'''.format( dic['location'], privkey))) out = out.format(newline) out = out.format( easyForm( '/home', 'create post', ''' <input type="hidden" name="location" value="{}"> <input type="hidden" name="do" value="post"> <input type="text" name="msg" value="message"> <input type="hidden" name="parent" value="{}"> <input type="text" name="amount" value="amount to spend"> <input type="hidden" name="privkey" value="{}">'''.format( dic['location'], dic['location'], privkey))) out = out.format(newline) posts = map(lambda x: blockchain.db_get(x, DB), DB['posts']) zeroth_confirmations = filter(lambda tx: tx['type'] == 'post', DB['txs']) posts += zeroth_confirmations msg = blockchain.db_get(dic['location'], DB) txt = ''' <input type="hidden" name="privkey" value="{}"> <input type="hidden" name="location" value="{}"> '''.format(privkey, '{}') out = out.format( easyForm('/home', 'Refresh: cd ./', txt.format(dic['location']))) out = out.format( easyForm('/home', 'Back: cd ../', txt.format(msg['parent']))) out = out.format(easyForm('/home', 'Root: cd /', txt.format('root'))) out = out.format('<h2>' + display_msg(msg) + '</h2>{}') if balance > 0: out = out.format( easyForm( '/home', 'upvote/downvote', txt.format(dic['location']) + ''' <input type="hidden" name="do" value="vote"> <input type="text" name="amount" value="amount +/-"> ''')) out = out.format(display_posts(posts, dic['location'], 0)) return out.format('')
def main(brainwallet, pubkey_flag=False): DB=custom.DB tools.log('custom.current_loc: ' +str(custom.current_loc)) print('starting full node') if not pubkey_flag: privkey=tools.det_hash(brainwallet) pubkey=tools.privtopub(privkey) else: pubkey=brainwallet a=tools.empty_peer() b=custom.peers #b[tools.getPublicIp()+':'+str(custom.port)]=a processes= [ {'target': db.main, 'args': (DB['heart_queue'], custom.database_name, tools.log, custom.database_port), 'name': 'db'}, {'target': auto_signer.mainloop, 'args': (), 'name': 'auto_signer'}, {'target': reward_collector.doit, 'args': (), 'name': 'auto_signer'}, #{'target':tools.heart_monitor, # 'args':(DB['heart_queue'], ), # 'name':'heart_monitor'}, {'target': blockchain.main, 'args': (DB,), 'name': 'blockchain'}, {'target': api.main, 'args': (DB, DB['heart_queue']), 'name': 'api'}, {'target': peers_check.main, 'args': (b, DB), 'name': 'peers_check'}, {'target': networking.serve_forever, 'args': (peer_recieve_func, custom.port, DB['heart_queue'], True), 'name': 'peer_recieve'} ] cmds=[] cmd=multiprocessing.Process(**processes[0]) cmd.start() cmds.append(cmd) tools.log('starting '+cmd.name) time.sleep(4) b=tools.db_existence(0) #def empty_memoized(): return({'blockcount':-3000}) if not b: tools.local_put('length', -1) tools.local_put('height', -1) tools.local_put('memoized_votes', {}) tools.local_put('txs', []) tools.local_put('peers', {}) tools.local_put('targets', {}) tools.local_put('times', {}) tools.local_put('mine', False) tools.local_put('my_sign_txs', {})#empty_memoized()) tools.local_put('secrets', {}) money=db.default_entry() money['amount']+=custom.all_money tools.db_put(custom.creator, money) tools.local_put('stop', False) tools.log('stop: ' +str(tools.local_get('stop'))) for process in processes[1:]: cmd=multiprocessing.Process(**process) cmd.start() cmds.append(cmd) tools.log('starting '+cmd.name) if not pubkey_flag: tools.local_put('privkey', privkey) else: tools.local_put('privkey', 'Default') Address=tools.make_address([pubkey], 1) tools.local_put('address', Address) a=tools.db_proof(Address) tools.local_put('balance_proofs-1', a) tools.log('stop: ' +str(tools.local_get('stop'))) while not tools.local_get('stop'): time.sleep(0.5) tools.log('about to stop threads') DB['heart_queue'].put('stop') for p in [[custom.port, '127.0.0.1'], [custom.api_port, '127.0.0.1']]: networking.connect('stop', p[0], p[1]) cmds.reverse() for cmd in cmds[:-1]: cmd.join() tools.log('stopped a thread: '+str(cmd)) time.sleep(2) networking.connect('stop', custom.database_port, '127.0.0.1') cmds[-1].join() tools.log('stopped a thread: '+str(cmds[-1])) tools.log('all threads stopped') sys.exit(0)
script=file(sys.argv[1],'r').read() except: script='' db = leveldb.LevelDB(custom.database_name) DB = {'stop':False, 'mine':False, 'db': db, 'txs': [], 'suggested_blocks': suggested_blocks, 'suggested_txs': Queue.Queue(), 'heart_queue': heart_queue, 'memoized_votes':{}, 'peers_ranked':[], 'brainwallet':'brain wallet', 'diffLength': '0'} DB['privkey']=tools.det_hash(DB['brainwallet']) DB['pubkey']=tools.privtopub(DB['privkey']) DB['address']=tools.make_address([DB['pubkey']], 1) def len_f(i, DB): if not tools.db_existence(str(i), DB): return i-1 return len_f(i+1, DB) DB['length']=len_f(0, DB) DB['diffLength']='0' if DB['length']>-1: DB['diffLength']=tools.db_get(str(DB['length']), DB)['diffLength'] worker_tasks = [ # Keeps track of blockchain database, checks on peers for new blocks and # transactions. #all these workers share memory DB #if any one gets blocked, then they are all blocked. {'target': api.main,
listen_port = 8900 gui_port = 8700 version = "VERSION" block_reward = 10**5 premine = 5 * 10**6 fee = 10**3 # Lower limits on what the "time" tag in a block can say. mmm = 100 # Take the median of this many of the blocks. # How far back in history do we look when we use statistics to guess at # the current blocktime and difficulty. history_length = 400 # This constant is selected such that the 50 most recent blocks count for 1/2 the # total weight. inflection = 0.985 download_many = 500 # Max number of blocks to request from a peer at the same time. max_download = 50000 brainwallet = 'brain wallet' privkey = tools.det_hash(brainwallet) pubkey = tools.privtopub(privkey) peers = [['localhost', 8901], ['localhost', 8902], ['localhost', 8903], ['localhost', 8904], ['localhost', 8905]] hashes_per_check = 10**5 def blocktime(length): if length * block_reward < premine: return 30 # seconds else: return 60
def main(brainwallet): print('starting truthcoin') heart_queue=multiprocessing.Queue() suggested_blocks=multiprocessing.Queue() #db = leveldb.LevelDB(custom.database_name) DB = {#'targets':{}, #'times':{}, #'db': db, 'txs': [], 'reward_peers_queue':multiprocessing.Queue(), 'suggested_blocks': suggested_blocks, 'suggested_txs': multiprocessing.Queue(), 'heart_queue': heart_queue, 'memoized_votes':{}, #'peers_ranked':[], 'diffLength': '0'} tools.db_put('peers_ranked', []) tools.db_put('targets', {}) tools.db_put('times', {}) tools.db_put('stop', False) tools.db_put('mine', False) DB['privkey']=tools.det_hash(brainwallet) DB['pubkey']=tools.privtopub(DB['privkey']) DB['address']=tools.make_address([DB['pubkey']], 1) def len_f(i, DB): if not tools.db_existence(str(i), DB): return i-1 return len_f(i+1, DB) DB['length']=len_f(0, DB) DB['diffLength']='0' if DB['length']>-1: ''' {'target': blockchain.suggestion_txs, 'args': (DB,), 'daemon': True}, {'target': blockchain.suggestion_blocks, 'args': (DB,), 'daemon': True}, ''' #print('thing: ' +str(tools.db_get(str(DB['length']), DB))) DB['diffLength']=tools.db_get(str(DB['length']), DB)['diffLength'] worker_tasks = [ #all these workers share memory DB #if any one gets blocked, then they are all blocked. {'target': truthcoin_api.main, 'args': (DB, heart_queue), 'daemon':True}, {'target': blockchain.main, 'args': (DB,), 'daemon': True}, {'target': miner.main, 'args': (DB['pubkey'], DB), 'daemon': False}, {'target': peers_check.main, 'args': (custom.peers, DB), 'daemon': True}, {'target': networking.serve_forever, 'args': (custom.port, lambda d: peer_recieve.main(d, DB), heart_queue, DB), 'daemon': True} ] processes= [#this thread does NOT share memory with the rest. {'target':tools.heart_monitor, 'args':(heart_queue, )} ] cmds=[] for process in processes: cmd=multiprocessing.Process(target=process['target'], args=process['args']) cmd.start() cmds.append(cmd) def start_worker_proc(**kwargs): daemon=kwargs.pop('daemon', True) proc = threading.Thread(**kwargs) proc.daemon = daemon proc.start() return proc workers = [start_worker_proc(**task_info) for task_info in worker_tasks] while not tools.db_get('stop'): time.sleep(0.5) tools.log('about to stop threads') DB['heart_queue'].put('stop') for worker in workers: tools.log('stopped a thread') worker.join() for cmd in cmds: tools.log('stopped a thread') cmd.join() #del DB['db'] tools.log('all threads stopped') sys.exit(1)
def main(brainwallet): print('starting truthcoin') heart_queue = multiprocessing.Queue() suggested_blocks = multiprocessing.Queue() #db = leveldb.LevelDB(custom.database_name) DB = { #'targets':{}, #'times':{}, #'db': db, 'txs': [], 'reward_peers_queue': multiprocessing.Queue(), 'suggested_blocks': suggested_blocks, 'suggested_txs': multiprocessing.Queue(), 'heart_queue': heart_queue, 'memoized_votes': {}, #'peers_ranked':[], 'diffLength': '0' } tools.db_put('peers_ranked', []) tools.db_put('targets', {}) tools.db_put('times', {}) tools.db_put('stop', False) tools.db_put('mine', False) DB['privkey'] = tools.det_hash(brainwallet) DB['pubkey'] = tools.privtopub(DB['privkey']) DB['address'] = tools.make_address([DB['pubkey']], 1) def len_f(i, DB): if not tools.db_existence(str(i), DB): return i - 1 return len_f(i + 1, DB) DB['length'] = len_f(0, DB) DB['diffLength'] = '0' if DB['length'] > -1: ''' {'target': blockchain.suggestion_txs, 'args': (DB,), 'daemon': True}, {'target': blockchain.suggestion_blocks, 'args': (DB,), 'daemon': True}, ''' #print('thing: ' +str(tools.db_get(str(DB['length']), DB))) DB['diffLength'] = tools.db_get(str(DB['length']), DB)['diffLength'] worker_tasks = [ #all these workers share memory DB #if any one gets blocked, then they are all blocked. { 'target': truthcoin_api.main, 'args': (DB, heart_queue), 'daemon': True }, { 'target': blockchain.main, 'args': (DB, ), 'daemon': True }, { 'target': miner.main, 'args': (DB['pubkey'], DB), 'daemon': False }, { 'target': peers_check.main, 'args': (custom.peers, DB), 'daemon': True }, { 'target': networking.serve_forever, 'args': (custom.port, lambda d: peer_recieve.main(d, DB), heart_queue, DB), 'daemon': True } ] processes = [ #this thread does NOT share memory with the rest. { 'target': tools.heart_monitor, 'args': (heart_queue, ) } ] cmds = [] for process in processes: cmd = multiprocessing.Process(target=process['target'], args=process['args']) cmd.start() cmds.append(cmd) def start_worker_proc(**kwargs): daemon = kwargs.pop('daemon', True) proc = threading.Thread(**kwargs) proc.daemon = daemon proc.start() return proc workers = [start_worker_proc(**task_info) for task_info in worker_tasks] while not tools.db_get('stop'): time.sleep(0.5) tools.log('about to stop threads') DB['heart_queue'].put('stop') for worker in workers: tools.log('stopped a thread') worker.join() for cmd in cmds: tools.log('stopped a thread') cmd.join() #del DB['db'] tools.log('all threads stopped') sys.exit(1)
['192.241.212.114', 80]] def hash_(x): return hashlib.sha256(x).hexdigest() database_name='DB.db' listen_port=8900 gui_port=8700 version="VERSION" block_reward=10**5 premine=5*10**6 fee=10**3 mmm=100#lower limits on what #the "time" tag in a block can say. Take the median #of this many of the blocks. history_length=400#how far back in history do #we look when we use statistics to guess at #the current blocktime and difficulty. inflection=0.985#This constant is selected such #that the 50 most recent blocks count for 1/2 the #total weight. download_many=20#max number of blocks to request #from a peer at the same time. max_download=50000 privkey=tools.det_hash(brainwallet) pubkey=tools.privtopub(privkey) hashes_per_check=10**5 def blocktime(length): if length*block_reward<premine: return 30 else: return 60
def home(DB, dic): def display_msg(msg): try: return str(msg['msg'])+' : '+str(msg['reputation']/100000.0) except: return str(msg['msg'])+' : '+str(msg['amount']/100000.0) def display_posts(posts, parent, tabs): out='{}' if tabs>2: return out for pos in posts: id_=transactions.postid(pos) if pos['parent']==parent: bumper='<div class="contentcontainer med left" style="margin-left: '+str(100*tabs)+'px;"><p>{}</p></div>' if pos in zeroth_confirmations: print('pos: ' +str(pos)) out=out.format(bumper.format(display_msg(pos))+'{}') else: txt=bumper.format(easyForm('/home', display_msg(pos), ''' <input type="hidden" name="location" value="{}"> <input type="hidden" name="parent" value="{}"> <input type="hidden" name="privkey" value="{}">'''.format(id_, id_,privkey))).format('')+'{}' out=out.format(txt) out=out.format(display_posts(posts, id_, tabs+1)) return out def balance_(address, DB): balance=blockchain.db_get(address, DB)['amount'] for tx in DB['txs']: if tx['type'] == 'spend': if tx['to'] == address: balance += tx['amount'] if tx['pubkeys'][0] == pubkey: balance -= tx['amount'] + custom.fee if tx['type'] == 'post': if tx['pubkeys'][0] == pubkey: balance -= tx['amount'] + custom.fee return balance if 'BrainWallet' in dic: dic['privkey']=tools.det_hash(dic['BrainWallet']) elif 'privkey' not in dic: return "<p>You didn't type in your brain wallet.</p>" privkey=dic['privkey'] pubkey=tools.privtopub(dic['privkey']) address=tools.make_address([pubkey], 1) balance=balance_(address, DB) doFunc={'spend': (lambda dic: spend(float(dic['amount']), pubkey, privkey, dic['to'], DB)), 'post': (lambda dic: post(float(dic['amount']), pubkey, privkey, dic['msg'], dic['parent'], DB)), 'vote': (lambda dic: vote(float(dic['amount']), pubkey, privkey, dic['location'], DB))} try: if 'do' in dic.keys(): doFunc[dic['do']](dic) except: pass out=empty_page out=out.format('<p>your address: ' +str(address)+'</p>{}') out=out.format('<p>current block: ' +str(DB['length'])+'</p>{}') out=out.format('<p>current balance is: ' +str(balance/100000.0)+'</p>{}') if balance>0: out=out.format(easyForm('/home', 'spend money', ''' <input type="hidden" name="location" value="{}"> <input type="hidden" name="do" value="spend"> <input type="text" name="to" value="address to give to"> <input type="text" name="amount" value="amount to spend"> <input type="hidden" name="privkey" value="{}">'''.format(dic['location'], privkey))) out=out.format(newline) out=out.format(easyForm('/home', 'create post', ''' <input type="hidden" name="location" value="{}"> <input type="hidden" name="do" value="post"> <input type="text" name="msg" value="message"> <input type="hidden" name="parent" value="{}"> <input type="text" name="amount" value="amount to spend"> <input type="hidden" name="privkey" value="{}">'''.format(dic['location'], dic['location'], privkey))) out=out.format(newline) posts=map(lambda x: blockchain.db_get(x, DB), DB['posts']) zeroth_confirmations=filter(lambda tx: tx['type']=='post', DB['txs']) posts+=zeroth_confirmations msg=blockchain.db_get(dic['location'], DB) txt=''' <input type="hidden" name="privkey" value="{}"> <input type="hidden" name="location" value="{}"> '''.format(privkey, '{}') out=out.format(easyForm('/home', 'Refresh: cd ./', txt.format(dic['location']))) out=out.format(easyForm('/home', 'Back: cd ../', txt.format(msg['parent']))) out=out.format(easyForm('/home', 'Root: cd /', txt.format('root'))) out=out.format('<h2>'+display_msg(msg)+'</h2>{}') if balance>0: out=out.format(easyForm('/home', 'upvote/downvote', txt.format(dic['location'])+''' <input type="hidden" name="do" value="vote"> <input type="text" name="amount" value="amount +/-"> ''')) out=out.format(display_posts(posts, dic['location'], 0)) return out.format('')
db = leveldb.LevelDB(custom.database_name) DB = { 'stop': False, 'mine': False, 'db': db, 'txs': [], 'suggested_blocks': suggested_blocks, 'suggested_txs': Queue.Queue(), 'heart_queue': heart_queue, 'memoized_votes': {}, 'peers_ranked': [], 'brainwallet': 'brain wallet', 'diffLength': '0' } DB['privkey'] = tools.det_hash(DB['brainwallet']) DB['pubkey'] = tools.privtopub(DB['privkey']) DB['address'] = tools.make_address([DB['pubkey']], 1) def len_f(i, DB): if not tools.db_existence(str(i), DB): return i - 1 return len_f(i + 1, DB) DB['length'] = len_f(0, DB) DB['diffLength'] = '0' if DB['length'] > -1: DB['diffLength'] = tools.db_get(str(DB['length']), DB)['diffLength'] worker_tasks = [ # Keeps track of blockchain database, checks on peers for new blocks and # transactions. #all these workers share memory DB