Exemplo n.º 1
0
def add_tx(tx, DB):
    #Attempt to add a new transaction into the pool.
    address=tools.make_address(tx['id'], len(tx['signature']))
    #print('address: ' +str(address))
    #if address in ['01907260ccad051d995b3566307b7b785b0ef04664ab027e8ad2a037c1522693',0x01907260ccad051d995b3566307b7b785b0ef04664ab027e8ad2a037c1522693]: error('here')
    #print('tx: ' +str(tx))

    def verify_count(tx, txs): return tx['count']!=count(address, DB)
    
    def tx_type_check(tx, txs): return type(tx) != type({'a':1})
    
    def type_check(tx, txs): 
        return 'type' not in tx or tx['type'] not in transactions.tx_check
        
    def too_big_block(tx, txs): 
        return len(tools.package(txs+[tx]))>networking.MAX_MESSAGE_SIZE-5000
        
    def verify_tx(tx, txs):
        if type_check(tx, txs): return False
        if verify_count(tx, txs): return False
        if too_big_block(tx, txs): return False
        if 'start' in tx and DB['length']<tx['start']: return False
        if 'end' in tx and DB['length']>tx['end']: return False
        #print('tx to transcations: ' +str(tx))
        return transactions.tx_check[tx['type']](tx, txs, DB)
        
    if verify_tx(tx, DB['txs']): DB['txs'].append(tx)
Exemplo n.º 2
0
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)
Exemplo n.º 3
0
def get_address(tx):
    pubkey = str(raw_input('What is your address or pubkey\n>'))
    if len(pubkey) > 40:
        out = tools.make_address([pubkey], 1)
    else:
        out = pubkey
    return tx
Exemplo n.º 4
0
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)
Exemplo n.º 5
0
def get_address(tx):
    pubkey=str(raw_input('What is your address or pubkey\n>'))
    if len(pubkey)>40:
        out=tools.make_address([pubkey], 1)
    else:
        out=pubkey    
    return tx
Exemplo n.º 6
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.º 7
0
def build_pm():
    tx={'type':'prediction_market', 'fees':0}
    pubkey=str(raw_input('What is the address or pubkey of the owner of the PM?\n>'))
    if len(pubkey)>40:
        tx['owner']=tools.make_address([pubkey], 1)
    else:
        tx['owner']=pubkey
    tx['PM_id']=str(raw_input('What is the unique name for this new prediction market?\n>'))
    tx['B']=int(raw_input('how big should B be? Initial investment is B*ln(n) where n is the number of states\n>'))
    num_decisions=int(raw_input('how many decisions is this prediction market to be based upon?\n>'))
    tx['decisions']=[]
    for i in range(num_decisions):
        tx['decisions'].append(str(raw_input('What is the unique name of the '+str(i)+' decision?\n>')))
    num_states=int(raw_input('how many states can this PM result in?\n>'))
    if num_states>2**num_decisions: 
        print('too many states')
        return False
    tx['states_combinatory']=[]
    tx['states']=[]
    for i in range(num_states):
        tx['states'].append(str(raw_input('what is the text title of the '+str(i)+' state?\n>')))
        if i!=num_states-1:
            next_comb=(str(raw_input('how does the '+str(i)+' state depend upon the outcome of the decisions? For example: if there are 2 decisions, and this market only comes true when the first is "yes" and the second is "no", then you would put: "1 0" here.\n>')))
            tx['states_combinatory'].append(map(int, next_comb.split(' ')))
    return tx
Exemplo n.º 8
0
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)
Exemplo n.º 9
0
def add_tx(tx, DB):
    # Attempt to add a new transaction into the pool.
    address = tools.make_address(tx['pubkeys'], len(tx['signatures']))

    def verify_count(tx, txs):
        return tx['count'] != count(address, DB)

    def type_check(tx, txs):
        if 'type' not in tx:
            return True
        if tx['type'] == 'mint':
            return True
        return tx['type'] not in transactions.tx_check

    def too_big_block(tx, txs):
        return len(tools.package(txs+[tx])) > networking.MAX_MESSAGE_SIZE - 5000

    def verify_tx(tx, txs):
        if type_check(tx, txs):
            return False
        if tx in txs:
            return False
        if verify_count(tx, txs):
            return False
        if too_big_block(tx, txs):
            return False
        return transactions.tx_check[tx['type']](tx, txs, DB)

    if verify_tx(tx, DB['txs']):
        DB['txs'].append(tx)
Exemplo n.º 10
0
def add_tx(tx, DB):
    # Attempt to add a new transaction into the pool.
    address = tools.make_address(tx['pubkeys'], len(tx['signatures']))

    def verify_count(tx, txs):
        return tx['count'] != count(address, DB)

    def type_check(tx, txs):
        if 'type' not in tx:
            return True
        if tx['type'] == 'mint':
            return True
        return tx['type'] not in transactions.tx_check

    def too_big_block(tx, txs):
        return len(tools.package(txs+[tx])) > networking.MAX_MESSAGE_SIZE - 5000

    def verify_tx(tx, txs):
        if type_check(tx, txs):
            return False
        if tx in txs:
            return False
        if verify_count(tx, txs):
            return False
        if too_big_block(tx, txs):
            return False
        return transactions.tx_check[tx['type']](tx, txs, DB)

    if verify_tx(tx, DB['txs']):
        DB['txs'].append(tx)
Exemplo n.º 11
0
def make_mint(pubkey):
    address = tools.make_address([pubkey], 1)
    return {
        'type': 'mint',
        'pubkeys': [pubkey],
        'signatures': ['first_sig'],
        'count': tools.count(address, custom.queues)
    }
Exemplo n.º 12
0
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
Exemplo n.º 13
0
 def make_mint(pubkey, DB):
     address = tools.make_address([reward_address], 1)
     return {
         'type': 'mint',
         'pubkeys': [pubkey],
         'signatures': ['first_sig'],
         'count': blockchain.count(address, DB)
     }
Exemplo n.º 14
0
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
Exemplo n.º 15
0
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
Exemplo n.º 16
0
def add_tx(tx, DB={}):
    # Attempt to add a new transaction into the pool.
    #print('top of add_tx')
    out = ['']
    if type(tx) != type({'a': 1}):
        return False
    address = tools.make_address(tx['pubkeys'], len(tx['signatures']))

    def verify_count(tx, txs):
        return tx['count'] != tools.count(address, DB)

    def type_check(tx, txs):
        if not tools.E_check(tx, 'type', [str, unicode]):
            out[0] += 'blockchain type'
            return False
        if tx['type'] == 'mint':
            return False
        if tx['type'] not in transactions.tx_check:
            out[0] += 'bad type'
            return False
        return True

    def too_big_block(tx, txs):
        return len(
            tools.package(txs + [tx])) > networking.MAX_MESSAGE_SIZE - 5000

    def verify_tx(tx, txs, out):
        if not type_check(tx, txs):
            out[0] += 'type error'
            return False
        if tx in txs:
            out[0] += 'no duplicates'
            return False
        if verify_count(tx, txs):
            out[0] += 'count error'
            return False
        if too_big_block(tx, txs):
            out[0] += 'too many txs'
            return False
        try:
            if not transactions.tx_check[tx['type']](tx, txs, out, DB):
                out[0] += 'tx: ' + str(tx)
                return False
        except Exception as exc:
            out[0] += 'badly formatted tx caused error: ' + str(tx)
            return False
        return True

    #tools.log('attempt to add tx: ' +str(tx))
    T = tools.db_get('txs')
    if verify_tx(tx, T, out):
        T.append(tx)
        tools.db_put('txs', T)
        return (tx)
    else:
        return ('failed to add tx because: ' + out[0])
Exemplo n.º 17
0
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)
Exemplo n.º 18
0
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)
Exemplo n.º 19
0
def add_tx(tx, DB={}):
    # Attempt to add a new transaction into the pool.
    #print('top of add_tx')
    out = ['']
    if type(tx) != type({'a': 1}):
        return False
    address = tools.make_address(tx['pubkeys'], len(tx['signatures']))
    '''
    def verify_count(tx, txs):
        return tx['count'] != tools.count(address, DB)
    '''
    def type_check(tx, txs):
        if not tools.E_check(tx, 'type', [str, unicode]):
            out[0] += 'blockchain type'
            return False
        if tx['type'] not in transactions.tx_check:
            out[0] += 'bad type'
            return False
        return True

    def too_big_block(tx, txs):
        return len(
            tools.package(txs + [tx])) > networking.MAX_MESSAGE_SIZE - 5000

    def verify_tx(tx, txs, out):
        #do not allow tx which fail to reference one of the 10 most recent blocks. do not allow tx which have an identical copy in the last 10 blocks.
        if not type_check(tx, txs):
            out[0] += 'type error'
            return False
        if tx in txs:
            out[0] += 'no duplicates'
            return False
        #if verify_count(tx, txs):
        #    out[0]+='count error'
        #    return False
        if too_big_block(tx, txs):
            out[0] += 'too many txs'
            return False
        if not transactions.tx_check[tx['type']](tx, txs, out, DB):
            out[0] += 'tx: ' + str(tx)
            return False
        return True

    #tools.log('attempt to add tx: ' +str(tx))
    T = tools.local_get('txs')
    if verify_tx(tx, T, out):
        T.append(tx)
        tools.local_put('txs', T)
        return ('added tx: ' + str(tx))
    else:
        return ('failed to add tx because: ' + out[0])
Exemplo n.º 20
0
def add_tx(tx, DB):
    # Attempt to add a new transaction into the pool.
    #print('top of add_tx')
    out = ['']
    if type(tx) != type({'a': 1}):
        return False
    address = tools.make_address(tx['pubkeys'], len(tx['signatures']))

    def verify_count(tx, txs):
        return tx['count'] != tools.count(address, DB)

    def type_check(tx, txs):
        if not tools.E_check(tx, 'type', [str, unicode]):
            out[0] += 'blockchain type'
            return False
        if tx['type'] == 'mint':
            return False
        if tx['type'] not in transactions.tx_check:
            out[0] += 'bad type'
            return False
        return True

    def too_big_block(tx, txs):
        return len(
            tools.package(txs + [tx])) > networking.MAX_MESSAGE_SIZE - 5000

    def verify_tx(tx, txs, out):
        if not type_check(tx, txs):
            out[0] += 'type error'
            return False
        if tx in txs:
            out[0] += 'no duplicates'
            return False
        if verify_count(tx, txs):
            out[0] += 'count error'
            return False
        if too_big_block(tx, txs):
            out[0] += 'too many txs'
            return False
        if not transactions.tx_check[tx['type']](tx, txs, DB):
            out[0] += 'update transactions.py to find out why. print statements are no good. ' + str(
                tx)
            return False
        return True

    if verify_tx(tx, DB['txs'], out):
        DB['txs'].append(tx)
        return ('added tx: ' + str(tx))
    else:
        return ('failed to add tx because: ' + out[0])
Exemplo n.º 21
0
def add_tx(tx, DB={}):
    # Attempt to add a new transaction into the pool.
    #print('top of add_tx')
    out=['']
    if type(tx) != type({'a':1}): 
        return False
    address = tools.make_address(tx['pubkeys'], len(tx['signatures']))
    def verify_count(tx, txs):
        return tx['count'] != tools.count(address, DB)
    def type_check(tx, txs):
        if not tools.E_check(tx, 'type', [str, unicode]):
            out[0]+='blockchain type'
            return False
        if tx['type'] == 'mint':
            return False
        if tx['type'] not in transactions.tx_check:
            out[0]+='bad type'
            return False
        return True
    def too_big_block(tx, txs):
        return len(tools.package(txs+[tx])) > networking.MAX_MESSAGE_SIZE - 5000
    def verify_tx(tx, txs, out):
        if not type_check(tx, txs):
            out[0]+='type error'
            return False
        if tx in txs:
            out[0]+='no duplicates'
            return False
        if verify_count(tx, txs):
            out[0]+='count error'
            return False
        if too_big_block(tx, txs):
            out[0]+='too many txs'
            return False
        try:
            if not transactions.tx_check[tx['type']](tx, txs, out, DB):
                out[0]+= 'tx: ' + str(tx)
                return False
        except Exception as exc:
            out[0]+='badly formatted tx caused error: ' +str(tx)
            return False
        return True
    #tools.log('attempt to add tx: ' +str(tx))
    T=tools.db_get('txs')
    if verify_tx(tx, T, out):
        T.append(tx)
        tools.db_put('txs', T)
        return(tx)
    else:
        return('failed to add tx because: '+out[0])
Exemplo n.º 22
0
def add_tx(tx, DB={}):
    # Attempt to add a new transaction into the pool.
    #print('top of add_tx')
    out=['']
    if type(tx) != type({'a':1}): 
        return False
    address = tools.make_address(tx['pubkeys'], len(tx['signatures']))
    '''
    def verify_count(tx, txs):
        return tx['count'] != tools.count(address, DB)
    '''
    def type_check(tx, txs):
        if not tools.E_check(tx, 'type', [str, unicode]):
            out[0]+='blockchain type'
            return False
        if tx['type'] not in transactions.tx_check:
            out[0]+='bad type'
            return False
        return True
    def too_big_block(tx, txs):
        return len(tools.package(txs+[tx])) > networking.MAX_MESSAGE_SIZE - 5000
    def verify_tx(tx, txs, out):
        #do not allow tx which fail to reference one of the 10 most recent blocks. do not allow tx which have an identical copy in the last 10 blocks.
        if not type_check(tx, txs):
            out[0]+='type error'
            return False
        if tx in txs:
            out[0]+='no duplicates'
            return False
        #if verify_count(tx, txs):
        #    out[0]+='count error'
        #    return False
        if too_big_block(tx, txs):
            out[0]+='too many txs'
            return False
        if not transactions.tx_check[tx['type']](tx, txs, out, DB):
            out[0]+= 'tx: ' + str(tx)
            return False
        return True
    #tools.log('attempt to add tx: ' +str(tx))
    T=tools.local_get('txs')
    if verify_tx(tx, T, out):
        T.append(tx)
        tools.local_put('txs', T)
        return('added tx: ' +str(tx))
    else:
        return('failed to add tx because: '+out[0])
Exemplo n.º 23
0
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)
Exemplo n.º 24
0
def build_pm():
    tx = {'type': 'prediction_market', 'fees': 0}
    pubkey = str(
        raw_input('What is the address or pubkey of the owner of the PM?\n>'))
    if len(pubkey) > 40:
        tx['owner'] = tools.make_address([pubkey], 1)
    else:
        tx['owner'] = pubkey
    tx['PM_id'] = str(
        raw_input(
            'What is the unique name for this new prediction market?\n>'))
    tx['B'] = int(
        raw_input(
            'how big should B be? Initial investment is B*ln(n) where n is the number of states\n>'
        ))
    num_decisions = int(
        raw_input(
            'how many decisions is this prediction market to be based upon?\n>'
        ))
    tx['decisions'] = []
    for i in range(num_decisions):
        tx['decisions'].append(
            str(
                raw_input('What is the unique name of the ' + str(i) +
                          ' decision?\n>')))
    num_states = int(raw_input('how many states can this PM result in?\n>'))
    if num_states > 2**num_decisions:
        print('too many states')
        return False
    tx['states_combinatory'] = []
    tx['states'] = []
    for i in range(num_states):
        tx['states'].append(
            str(
                raw_input('what is the text title of the ' + str(i) +
                          ' state?\n>')))
        if i != num_states - 1:
            next_comb = (str(
                raw_input(
                    'how does the ' + str(i) +
                    ' state depend upon the outcome of the decisions? For example: if there are 2 decisions, and this market only comes true when the first is "yes" and the second is "no", then you would put: "1 0" here.\n>'
                )))
            tx['states_combinatory'].append(map(int, next_comb.split(' ')))
    print('tx for copy/pasting into pushtx: ' +
          tools.package(tx).encode('base64'))
    return tx
Exemplo n.º 25
0
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
Exemplo n.º 26
0
def add_tx(tx, DB):
    # Attempt to add a new transaction into the pool.
    #print('top of add_tx')
    out=['']
    if type(tx) != type({'a':1}): 
        return False
    address = tools.make_address(tx['pubkeys'], len(tx['signatures']))
    def verify_count(tx, txs):
        return tx['count'] != tools.count(address, DB)
    def type_check(tx, txs):
        if not tools.E_check(tx, 'type', [str, unicode]):
            out[0]+='blockchain type'
            return False
        if tx['type'] == 'mint':
            return False
        if tx['type'] not in transactions.tx_check:
            out[0]+='bad type'
            return False
        return True
    def too_big_block(tx, txs):
        return len(tools.package(txs+[tx])) > networking.MAX_MESSAGE_SIZE - 5000
    def verify_tx(tx, txs, out):
        if not type_check(tx, txs):
            out[0]+='type error'
            return False
        if tx in txs:
            out[0]+='no duplicates'
            return False
        if verify_count(tx, txs):
            out[0]+='count error'
            return False
        if too_big_block(tx, txs):
            out[0]+='too many txs'
            return False
        if not transactions.tx_check[tx['type']](tx, txs, DB):
            out[0]+='update transactions.py to find out why. print statements are no good. ' +str(tx)
            return False
        return True
    if verify_tx(tx, DB['txs'], out):
        DB['txs'].append(tx)
        return('added tx: ' +str(tx))
    else:
        return('failed to add tx because: '+out[0])
Exemplo n.º 27
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.º 28
0
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
Exemplo n.º 29
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.º 30
0
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)
Exemplo n.º 31
0
def spend_verify(tx, txs, DB): 
    def sigs_match(sigs, pubs, msg):
        for sig in sigs:
            for pub in pubs:
                try:
                    if tools.verify(msg, sig, pub):
                        sigs.remove(sig)
                        pubs.remove(pub)
                except:
                    pass
        return len(sigs)==0
    tx_copy=copy.deepcopy(tx)
    tx_copy_2=copy.deepcopy(tx)
    tx_copy.pop('signature')
    if len(tx['id'])==0: return False
    if len(tx['signature'])>len(tx['id']): return False
    msg=tools.det_hash(tx_copy)
    if not sigs_match(copy.deepcopy(tx['signature']), copy.deepcopy(tx['id']), msg): return False
    if tx['amount']<custom.fee: return False
    address=tools.make_address(tx_copy_2['id'], len(tx_copy_2['signature']))
    print('tx: ' +str(tx_copy_2))
    print('address: ' +str(address))
    return int(blockchain.db_get(address, DB)['amount'])>=int(tx['amount']) 
Exemplo n.º 32
0
    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.
Exemplo n.º 33
0
 def make_mint(pubkey, DB):
     address = tools.make_address([reward_address], 1)
     return {'type': 'mint',
             'pubkeys': [pubkey],
             'signatures': ['first_sig'],
             'count': blockchain.count(address, DB)}
Exemplo n.º 34
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.º 35
0
def add_tx(tx, DB={}):
    # Attempt to add a new transaction into the pool.
    #print('top of add_tx')
    out = ['']
    if type(tx) != type({'a': 1}):
        return False
    address = tools.make_address(tx['pubkeys'], len(tx['signatures']))
    '''
    def verify_count(tx, txs):
        return tx['count'] != tools.count(address, DB)
    '''
    def repeat_check(tx, txs):
        l = tools.local_get('length')
        if l <= 1: return True
        h = tx['recent_hash']
        r = range(l - 10, l)
        r = filter(lambda l: l > 0, r)
        recent_blocks = map(lambda x: tools.db_get(x), r)
        recent_hashes = map(lambda x: x['block_hash'], recent_blocks)
        if h not in recent_hashes:
            tools.log('have : ' + str(h))
            tools.log('need: ' + str(recent_hashes))
            tools.log('recent hash error')
            return False
        recent_txs = []
        for block in recent_blocks:
            recent_txs += block['txs']

        def f(d):
            d = copy.deepcopy(d)
            d.pop('signatures')
            return tools.det_hash(d)

        if f(tx) in map(f, recent_txs):
            tools.log('no repeated tx')
            return False
        return True

    def type_check(tx, txs):
        if not tools.E_check(tx, 'type', [str, unicode]):
            out[0] += 'blockchain type'
            return False
        if tx['type'] not in transactions.tx_check:
            out[0] += 'bad type'
            return False
        return True

    def too_big_block(tx, txs):
        return len(
            tools.package(txs + [tx])) > networking.MAX_MESSAGE_SIZE - 5000

    def verify_tx(tx, txs, out):
        #do not allow tx which fail to reference one of the 10 most recent blocks. do not allow tx which have an identical copy in the last 10 blocks.
        if not type_check(tx, txs):
            out[0] += 'type error'
            return False
        if tx in txs:
            out[0] += 'no duplicates'
            return False
        #if verify_count(tx, txs):
        #    out[0]+='count error'
        #    return False
        if too_big_block(tx, txs):
            out[0] += 'too many txs'
            return False
        if not tools.fee_check(tx, txs, DB):
            out[0] += 'not enough money: ' + str(tx)
            return False
        if not tools.signature_check(tx):
            out[0] += 'bad signature: ' + str(tx)
            return False
        if not transactions.tx_check[tx['type']](tx, txs, out, DB):
            out[0] += 'tx: ' + str(tx)
            return False
        return True

    #tools.log('attempt to add tx: ' +str(tx))
    T = tools.local_get('txs')
    try:
        if verify_tx(tx, T, out):
            T.append(tx)
            tools.local_put('txs', T)
            return ('added tx: ' + str(tx))
        else:
            return ('failed to add tx because: ' + out[0])
    except Exception as exc:
        tools.log(exc)
        return ('failed to add tx because an error occured while adding tx')
Exemplo n.º 36
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.º 37
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('')
Exemplo n.º 38
0
def add_tx(tx):
    # Attempt to add a new transaction into the pool.

    out = ['']
    # check tx variable's type
    if type(tx) != type({'a': 1}):
        return False

    # make address from pubkeys and signatures of transaction
    address = tools.make_address(tx['pubkeys'], len(tx['signatures']))

    def verify_count(tx, txs):
        return tx['count'] != tools.count(address)

    def type_check(tx, txs):
        if not tools.E_check(tx, 'type', [str, unicode]):
            out[0] += 'Blockchain type'
            return False

        # mint type cannot be added to database
        if tx['type'] == 'mint':
            return False

        # type is not recognized
        if tx['type'] not in transactions.tx_check:
            out[0] += 'Bad type'
            return False

        return True

    def too_big_block(tx, txs):
        return len(
            tools.package(txs + [tx])) > networking.MAX_MESSAGE_SIZE - 5000

    def verify_tx(tx, txs, out):
        # check if the type of transaction lets you add the transaction back to database
        if not type_check(tx, txs):
            out[0] += 'Type error\n'
            return False
        if tx in txs:
            out[0] += 'No duplicates\n'
            return False
        # is this transaction possible with this count
        if verify_count(tx, txs):
            out[0] += 'Count error\n'
            return False
        # this block cannot be sent over network
        if too_big_block(tx, txs):
            out[0] += 'Too many txs\n'
            return False
        # run the last tx_check test from transactions module
        if not transactions.tx_check[tx['type']](tx, txs, out):
            out[0] += 'Transaction was not verified!\n'
            return False
        return True

    txs_from_db = tools.db_get('txs')

    if verify_tx(tx, txs_from_db, out):

        txs_from_db.append(tx)
        tools.db_put('txs', txs_from_db)
        return ('Added transaction with %d amount to %s' %
                (tx['amount'], tx['to']))

    else:
        return ('Failed to add tx because: \n' + out[0])
Exemplo n.º 39
0
 def is_zero_conf(t):
     address == tools.make_address(t['pubkeys'], len(t['signatures']))
Exemplo n.º 40
0
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)
Exemplo n.º 41
0
 def func(t):
     address == tools.make_address(t['pubkeys'], len(t['signatures']))
Exemplo n.º 42
0
def addr(tx):
    return tools.make_address(tx['pubkeys'], len(tx['signatures']))
Exemplo n.º 43
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)