Exemplo n.º 1
0
def create_jury_check(tx, txs, out, DB):
    address=addr(tx)
    mine=filter(lambda t: t['type']=='create_jury', txs)
    mine=filter(lambda t: addr(t)==address, mine)
    if len(mine)>0:
        out[0]+='you cannot create 2 juries on the same block from the same address'
        return False
    if not transactions.signature_check(tx):
        out[0]+='signature check'
        return False
    if not E_check(tx, 'vote_id', [str, unicode]): 
        out[0]+='vote id error'
        return False
    if tools.is_number(tx['vote_id']):
        out[0]+='vote_id can not be a number'
        return False
    if len(tx['vote_id'])>1000: return False
    if tools.db_existence(tx['vote_id'], DB): 
        out[0]+='this vote_id is already being used'
        return False
    if not tools.db_existence(address, DB): 
        out[0]+='this address is not used by anyone'
        return False
    acc=tools.db_get(address, DB)
    if not txs_tools.fee_check(tx, txs, DB): return False
    return True
Exemplo n.º 2
0
def create_jury_check(tx, txs, out, DB):
    address=addr(tx)
    if not transactions.signature_check(tx):
        out[0]+='signature check'
        return False
    if not E_check(tx, 'vote_id', [str, unicode]): 
        out[0]+='vote id error'
        return False
    if tools.is_number(tx['vote_id']):
        out[0]+='vote_id can not be a number'
        return False
    if len(tx['vote_id'])>1000: return False
    if tools.db_existence(tx['vote_id'], DB): 
        out[0]+='this vote_id is already being used'
        return False
    if not tools.db_existence(address, DB): 
        out[0]+='this address is not used by anyone'
        return False
    acc=tools.db_get(address, DB)
    for t in txs:
        if 'jury_id' in t:
            if t['jury_id']==tx['jury_id']:
                out[0]+='this zeroth confirmation transaction already exists'
                return False
    if not txs_tools.fee_check(tx, txs, DB): return False
    return True
Exemplo n.º 3
0
def create_jury_check(tx, txs, out, DB):
    address=addr(tx)
    mine=filter(lambda t: t['type']=='create_jury', txs)
    mine=filter(lambda t: addr(t)==address, mine)
    if len(mine)>0:
        out[0]+='you cannot create 2 juries on the same block from the same address'
        return False
    if not transactions.signature_check(tx):
        out[0]+='signature check'
        return False
    if not E_check(tx, 'vote_id', [str, unicode]): 
        out[0]+='vote id error'
        return False
    if tools.is_number(tx['vote_id']):
        out[0]+='vote_id can not be a number'
        return False
    if len(tx['vote_id'])>1000: return False
    if tools.db_existence(tx['vote_id'], DB): 
        out[0]+='this vote_id is already being used'
        return False
    if not tools.db_existence(address, DB): 
        out[0]+='this address is not used by anyone'
        return False
    acc=tools.db_get(address, DB)
    for t in txs:
        if t['type']=='prediction_market':
            if t['jury_id']==tx['jury_id']:
                out[0]+='this zeroth confirmation transaction already exists'
                return False
    if not txs_tools.fee_check(tx, txs, DB): return False
    return True
Exemplo n.º 4
0
def prediction_market_check(tx, txs, out, DB):
    if not transactions.signature_check(tx):
        out[0]+='signature check'
        return False
    address=addr(tx)
    for l in ['states', 'states_combinatory', 'decisions']:
        if not E_check(tx, l, list): 
            out[0]+=str(l)+ ' error'
            return False
    for dec in tx['decisions']:
        if not tools.db_existence(dec, DB): 
            out[0]+='decision is not in the database: ' +str(dec)
            return False
        if is_number(dec):
            out[0]+='decision_id can not be a number'
            return False
    if is_number(tx['PM_id']):
        out[0]+='PM_id can not be a number'
        return False
    if len(tx['states'])>200:
        out[0]+='too many states'
        return False
    if not E_check(tx, 'B', int):
        out[0]+='B error'
        return False
    for comb in tx['states_combinatory']:
        if len(comb)!=len(tx['decisions']):
            out[0]+=str(comb)+' comb error'
            return False
    for l in [tx['states_combinatory'], tx['states'], tx['decisions']]:
        for comb in l:
            copies=len(filter(lambda comb2: comb==comb2, l))
            if copies!=1:
                out[0]+=str(comb)+' not mutually exclusive'
                return False
    if len(tx['states'])!=len(tx['states_combinatory'])+1:
        out[0]+='wrong number of possible states?'
        return False
    if not E_check(tx, 'PM_id', [str, unicode]):
        out[0]+='PM_id error'
        return False        
    if len(tx['PM_id'])>1000: 
        out[0]+='PM_id too long'
        return False
    if tools.db_existence(tx['PM_id'], DB): 
        #out[0]+='PM: ' +str(tools.db_get(tx['PM_id'], DB))
        out[0]+='this PM_id is already being used'
        return False
    for t in txs:
        if 'PM_id' in t:
            if t['PM_id']==tx['PM_id']:
                out[0]+='Someone used that PM in this block already'
                return False
    acc=tools.db_get(address, DB)
    if not txs_tools.fee_check(tx, txs, DB): 
        out[0]+='you do not have enough money'
        return False
    return True
Exemplo n.º 5
0
def jury_vote_check(tx, txs, out, DB):
    #make sure that this person is one of the 1000 richest people for this rep type.
    if not transactions.signature_check(tx):
        out[0]+='signature check'
        return False
    if not E_check(tx, 'decision_id', [str, unicode]): return False
    if not E_check(tx, 'vote_id', [str, unicode]): return False
    if is_number(tx['vote_id']) or is_number(tx['decision_id']):
        out[0]+='that can not be a number'
        return False
    if not E_check(tx, 'old_vote', [str, unicode]): return False
    if not E_check(tx, 'new_vote', [str, unicode]): return False
    decision=tools.db_get(tx['decision_id'], DB)
    if 'state' not in decision:
        out[0]+='that is not a decision_id'
        out[0]+='decision: ' +str(decision)
        out[0]+='tx: ' +str(tx)
        return False
    if decision['state']!='proposed':
        out[0]+='this decision has already been decided'
        return False
    if not tools.db_existence(tx['decision_id'], DB): 
        out[0]+='decision error'
        return False
    if tools.reveal_time_p(DB): 
        out[0]+='reveal time check'
        return False
    if len(tx['new_vote'])<4: 
        out[0]+='secret too short error'
        return False
    if not txs_tools.fee_check(tx, txs, DB): return False
    return True
Exemplo n.º 6
0
def insert_block(pubkey, rewarded_pubkey):
    length = tools.db_get('length')

    if length == -1:
        # this is the first ever block
        candidate_block = genesis(pubkey)
    else:
        # get the last block
        prev_block = tools.db_get(length)
        candidate_block = make_block(prev_block, tools.db_get('txs'), pubkey)

    txs = copy.deepcopy(candidate_block['txs'])
    flag = True
    for tx in txs:
        if tx['type'] == 'mint':
            # no need to add reward
            flag = False
    if flag:
        txs = txs + [make_mint(rewarded_pubkey)]
        candidate_block['txs'] = txs

    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(txs).encode('base64').replace('\n', ''))

    candidate_block['auth_sign'] = tools.sign(tools.det_hash(candidate_block), privkey)
    candidate_block['auth_pubkey'] = pubkey

    if candidate_block is None:
        return
    else:
        custom.queues['suggested_blocks'].put(candidate_block)
Exemplo n.º 7
0
def insert_block(pubkey, rewarded_pubkey):
    length = tools.db_get('length')

    if length == -1:
        # this is the first ever block
        candidate_block = genesis(pubkey)
    else:
        # get the last block
        prev_block = tools.db_get(length)
        candidate_block = make_block(prev_block, tools.db_get('txs'), pubkey)

    txs = copy.deepcopy(candidate_block['txs'])
    flag = True
    for tx in txs:
        if tx['type'] == 'mint':
            # no need to add reward
            flag = False
    if flag:
        txs = txs + [make_mint(rewarded_pubkey)]
        candidate_block['txs'] = txs

    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(txs).encode('base64').replace('\n', ''))

    candidate_block['auth_sign'] = tools.sign(tools.det_hash(candidate_block),
                                              privkey)
    candidate_block['auth_pubkey'] = pubkey

    if candidate_block is None:
        return
    else:
        custom.queues['suggested_blocks'].put(candidate_block)
Exemplo n.º 8
0
def jury_vote_check(tx, txs, out, DB):
    if not transactions.signature_check(tx):
        out[0]+='signature check'
        return False
    if not E_check(tx, 'decision_id', [str, unicode]): return False
    if not E_check(tx, 'vote_id', [str, unicode]): return False
    if is_number(tx['vote_id']) or is_number(tx['decision_id']):
        out[0]+='that can not be a number'
        return False
    if not E_check(tx, 'old_vote', [str, unicode]): return False
    if not E_check(tx, 'new_vote', [str, unicode]): return False
    decision=tools.db_get(tx['decision_id'], DB)
    if 'state' not in decision:
        out[0]+='that is not a decision_id'
        out[0]+='decision: ' +str(decision)
        out[0]+='tx: ' +str(tx)
        return False
    if decision['state']!='proposed':
        out[0]+='this decision has already been decided'
        return False
    if not tools.db_existence(tx['decision_id'], DB): 
        out[0]+='decision error'
        return False
    if tools.reveal_time_p(DB): 
        out[0]+='reveal time check'
        return False
    if len(tx['new_vote'])<4: 
        out[0]+='secret too short error'
        return False
    if not txs_tools.fee_check(tx, txs, DB): return False
    return True
Exemplo n.º 9
0
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)
Exemplo n.º 10
0
def longest_peer():
    if not tools.db_existence('peers'):
        return 1000000
    peers = tools.db_get('peers')
    peers = map(lambda p: peers[p], peers.keys())
    peers = filter(lambda x: x['blacklist'] < 500, peers)
    peers = sorted(peers, key=lambda x: x['diffLength'])
    return peers[-1]['length']
Exemplo n.º 11
0
def longest_peer():
    if not tools.db_existence('peers'):
        return 1000000
    peers=tools.db_get('peers')
    peers=map(lambda p: peers[p], peers.keys())
    peers=filter(lambda x: x['blacklist']<500, peers)
    peers=sorted(peers, key=lambda x: x['diffLength'])
    return peers[-1]['length']
Exemplo n.º 12
0
def propose_decision_check(tx, txs, out, DB):
    if 'maturation' in tx:
        n=tx['maturation']
        if type(n)!=int or n<0: return False
    if not transactions.signature_check(tx):
        out[0]+='signature check'
        return False
    if not E_check(tx, 'vote_id', [str, unicode]): 
        out[0]+='no vote id'
        return False
    if not E_check(tx, 'decision_id', [str, unicode]): 
        out[0]+='no decision id'
        return False
    if is_number(tx['vote_id']) or is_number(tx['decision_id']):
        out[0]+='that can not be a number'
        return False
    if len(tx['decision_id'])>custom.max_key_length: 
        out[0]+='decision id too long'
        return False
    if not tools.db_existence(tx['vote_id'], DB): 
        out[0]+='that vote id has not been created yet'
        return False
    if tools.db_existence(tx['decision_id'], DB): 
        out[0]+='that decision id has already been used'
        return False
    for t in txs:
        if 'decision_id' in t:
            if t['decision_id']==tx['decision_id']:
                out[0]+='already have a zeroth confirmation tx of this'
                return False
    if not txs_tools.fee_check(tx, txs, DB): 
        out[0]+='you do not have enough money'
        return False
    if not E_check(tx, 'txt', [str, unicode]): 
        out[0]+='what is the txt of this decision?'
        return False
    if len(tx['txt'])>6**5: 
        out[0]+='the txt of this decision is too long'
        return False
    return True
Exemplo n.º 13
0
def propose_decision_check(tx, txs, out, DB):
    if 'maturation' in tx:
        n=tx['maturation']
        if type(n)!=int or n<0: return False
    if not transactions.signature_check(tx):
        out[0]+='signature check'
        return False
    if not E_check(tx, 'vote_id', [str, unicode]): 
        out[0]+='no vote id'
        return False
    if not E_check(tx, 'decision_id', [str, unicode]): 
        out[0]+='no decision id'
        return False
    if is_number(tx['vote_id']) or is_number(tx['decision_id']):
        out[0]+='that can not be a number'
        return False
    if len(tx['decision_id'])>custom.max_key_length: 
        out[0]+='decision id too long'
        return False
    if not tools.db_existence(tx['vote_id'], DB): 
        out[0]+='that vote id has not been created yet'
        return False
    if tools.db_existence(tx['decision_id'], DB): 
        out[0]+='that decision id has already been used'
        return False
    for t in txs:
        if 'decision_id' in t:
            if t['decision_id']==tx['decision_id']:
                out[0]+='already have a zeroth confirmation tx of this'
                return False
    if not txs_tools.fee_check(tx, txs, DB): 
        out[0]+='you do not have enough money'
        return False
    if not E_check(tx, 'txt', [str, unicode]): 
        out[0]+='what is the txt of this decision?'
        return False
    if len(tx['txt'])>6**5: 
        out[0]+='the txt of this decision is too long'
        return False
    return True
Exemplo n.º 14
0
def make_contract_verify(tx, txs, out, DB):
    if tools.db_existence(tx['id']):
        tools.log('contract already exists')
        return False
    contract = {
        'gas': int(tx['amount']) - custom.make_contract_fee,
        'mem': tx['mem'],
        'stack': []
    }
    if contract['gas'] < 0:
        tools.log('insufficient gas')
        return False
    return True
Exemplo n.º 15
0
def mine(DB, args):
    if len(args)>0:
        if args[0]=='off': 
            tools.db_put('mine', False)
            return('miner is now turned off')
        elif args[0]=='on':
            if tools.db_existence('privkey'):
                tools.db_put('mine', True)
                return ('miner on. (use "./truth_cli.py mine off" to turn off)')
            else:
                return('there is no private key with which to sign blocks. If you want to mine, you need to uncomment the "brain_wallet" line in custom.py')
    else:
        m=tools.db_get('mine')
        if m: 
            m='on'
        else: 
            m='off'
        return('miner is currently: ' +m)
Exemplo n.º 16
0
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))
Exemplo n.º 17
0
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))
Exemplo n.º 18
0
def mine(DB, args):
    if len(args) > 0:
        if args[0] == 'off':
            tools.db_put('mine', False)
            return ('miner is now turned off')
        elif args[0] == 'on':
            if tools.db_existence('privkey'):
                tools.db_put('mine', True)
                return (
                    'miner on. (use "./truth_cli.py mine off" to turn off)')
            else:
                return (
                    'there is no private key with which to sign blocks. If you want to mine, you need to uncomment the "brain_wallet" line in custom.py'
                )
    else:
        m = tools.db_get('mine')
        if m:
            m = 'on'
        else:
            m = 'off'
        return ('miner is currently: ' + m)
Exemplo n.º 19
0
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)
Exemplo n.º 20
0
 def len_f(i, DB):
     if not tools.db_existence(str(i), DB): return i-1
     return len_f(i+1, DB)
Exemplo n.º 21
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)
Exemplo n.º 22
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)
Exemplo n.º 23
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)
Exemplo n.º 24
0
 def len_f(i, DB):
     if not tools.db_existence(str(i), DB): return i - 1
     return len_f(i + 1, DB)
Exemplo n.º 25
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)