Example #1
0
 def peer_check(peer, DB):
     cmd=(lambda x: networking.send_command(peer, x))
     block_count=cmd({'type':'blockCount'})
     if type(block_count)!=type({'a':1}):
         return 
     if 'error' in block_count.keys():
         return         
     length=copy.deepcopy(DB['length'])
     us=copy.deepcopy(DB['diffLength'])
     them=block_count['diffLength']
     ahead=length-block_count['length']
     if them < us and ahead>0:#if we are ahead of them
         cmd({'type':'pushblock', 
              'block':blockchain.db_get(block_count['length']+1, DB)})
         return []
     if length<0: return []
     if us == them:#if we are on the same block, ask for any new txs
         block=blockchain.db_get(length, DB)
         if 'recent_hash' in block_count:
             if tools.det_hash(block)!=block_count['recent_hash']:
                 blockchain.delete_block()
                 #print('WE WERE ON A FORK. time to back up.')
                 return []
         my_txs=DB['txs']
         txs=cmd({'type':'txs'})
         for tx in txs:
             DB['suggested_txs'].append(tx)
         pushers=[x for x in my_txs if x not in txs]
         for push in pushers:
             cmd({'type':'pushtx', 'tx':push})
         return []
     start=length-2
     if start<0:
         start=0
     if ahead>custom.download_many:
         end=length+custom.doanload_many-1
     else:
         end=block_count['length']
     blocks= cmd({'type':'rangeRequest', 
                  'range':[start, end]})
     if type(blocks)!=type([1,2]):
         return []
     times=2
     while fork_check(blocks, DB) and times>0:
         times-=1
         blockchain.delete_block(DB)
     for block in blocks:
         DB['suggested_blocks'].append(block)
Example #2
0
def spend_verify(tx, txs, DB):

    def sigs_match(sigs, pubs, msg):
        return all(tools.verify(msg, sig, pub) for sig in sigs for pub in pubs)

    tx_copy = copy.deepcopy(tx)
    tx_copy_2 = copy.deepcopy(tx)
    tx_copy.pop('signatures')
    if len(tx['pubkeys']) == 0:
        return False
    if len(tx['signatures']) > len(tx['pubkeys']):
        return False
    msg = tools.det_hash(tx_copy)
    if not sigs_match(copy.deepcopy(tx['signatures']),
                      copy.deepcopy(tx['pubkeys']), msg):
        return False
    if tx['amount'] < custom.fee:
        return False
    address = addr(tx_copy_2)
    total_cost = 0
    for Tx in filter(lambda t: address == addr(t), [tx] + txs):
        if Tx['type'] == 'spend':
            total_cost += Tx['amount']
        if Tx['type'] == 'mint':
            total_cost -= custom.block_reward
    return int(blockchain.db_get(address, DB)['amount']) >= total_cost
Example #3
0
def home(DB, dic):
    if 'BrainWallet' in dic:
        dic['privkey'] = pt.sha256(dic['BrainWallet'])
    elif 'privkey' not in dic:
        return "<p>You didn't type in your brain wallet.</p>"
    privkey = dic['privkey']
    pubkey = pt.privtopub(dic['privkey'])
    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(tools.pub2addr(pubkey)) + '</p>{}')
    out = out.format('<p>current block: ' + str(DB['length']) + '</p>{}')
    try:
        balance = blockchain.db_get(pubkey, DB)
        balance = balance['amount']
    except:
        balance = 0
    for tx in DB['txs']:
        if tx['type'] == 'spend' and tx['to'] == tools.pub2addr(pubkey):
            balance += tx['amount']
        if tx['type'] == 'spend' and tx['id'] == 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)
Example #4
0
def spend_verify(tx, txs, DB):
    def sigs_match(sigs, pubs, msg):
        return all(tools.verify(msg, sig, pub) for sig in sigs for pub in pubs)

    tx_copy = copy.deepcopy(tx)
    tx_copy_2 = copy.deepcopy(tx)
    tx_copy.pop('signatures')
    if len(tx['pubkeys']) == 0:
        return False
    if len(tx['signatures']) > len(tx['pubkeys']):
        return False
    msg = tools.det_hash(tx_copy)
    if not sigs_match(copy.deepcopy(tx['signatures']),
                      copy.deepcopy(tx['pubkeys']), msg):
        return False
    if tx['amount'] < custom.fee:
        return False
    address = addr(tx_copy_2)
    total_cost = 0
    for Tx in filter(lambda t: address == addr(t), [tx] + txs):
        if Tx['type'] == 'spend':
            total_cost += Tx['amount']
        if Tx['type'] == 'mint':
            total_cost -= custom.block_reward
    return int(blockchain.db_get(address, DB)['amount']) >= total_cost
Example #5
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)
Example #6
0
def spend_verify(tx, txs, DB): 
    tx_copy=copy.copy(tx)
    tx_copy.pop('signature')
    if not pt.ecdsa_verify(tools.det_hash(tx_copy), tx['signature'], tx['id']): return False
    if tx['amount']<custom.fee: return False
    if int(blockchain.db_get(tx['id'], DB)['amount'])<int(tx['amount']): return False
    return True
Example #7
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)
Example #8
0
def adjust_amount(pubkey, amount, DB):
    try:
        acc=blockchain.db_get(pubkey, DB)
    except:
        blockchain.db_put(pubkey, {'amount': amount}, DB)
        return
    if 'amount' not in acc: acc['amount']=amount
    else: acc['amount']+=amount
    blockchain.db_put(pubkey, acc, DB)        
Example #9
0
def mine(hashes_till_check, reward_address, DB):
    #tries to mine the next block hashes_till_check many times.
    def make_mint(pubkey, DB): return {'type':'mint', 'id':[pubkey], 'signature':['first_sig'],
                                       'count':blockchain.count(pubkey, DB)}
                                       
    def genesis(pubkey, DB):
        target=blockchain.target(DB)
        out={'version':custom.version,
             'length':0,
             'time':time.time(),
             'target':target,
             'diffLength':blockchain.hexInvert(target),
             'txs':[make_mint(pubkey, DB)]}
        out=tools.unpackage(tools.package(out))
        return out
        
    def make_block(prev_block, txs, pubkey, DB):
        leng=int(prev_block['length'])+1
        target=blockchain.target(DB, leng)
        diffLength=blockchain.hexSum(prev_block['diffLength'], 
                                     blockchain.hexInvert(target))
        out={'version':custom.version,
             'txs':txs+[make_mint(pubkey, DB)],
             'length':leng,
             'time':time.time(),
             'diffLength':diffLength,
             'target':target,
             'prevHash':tools.det_hash(prev_block)}
        out=tools.unpackage(tools.package(out))
        return out
        
    def POW(block, hashes, target):
        halfHash=tools.det_hash(block)
        block[u'nonce']=random.randint(0,100000000000000000)
        count=0
        while tools.det_hash({u'nonce':block['nonce'], 
                              u'halfHash':halfHash})>target:
            count+=1
            block[u'nonce']+=1
            if count>hashes:
                return {'error':False}
            ''' for testing sudden loss in hashpower from miners.
            if block[u'length']>150:
            else: time.sleep(0.01)
            '''
        return block
        
    length=copy.deepcopy(DB['length'])
    if length==-1:
        block=genesis(reward_address, DB)
        txs=[]
    else:
        prev_block=blockchain.db_get(length, DB)
        txs=DB['txs']
        block=make_block(prev_block, txs, reward_address, DB)
    block=POW(block, hashes_till_check, blockchain.target(DB, block['length']))
    DB['suggested_blocks'].append(block)
Example #10
0
def enough_coins(tx, txs, DB):
    address=addr(tx)
    total_cost=0
    for Tx in filter(lambda t: address==addr(t), [tx]+txs):
        if Tx['type'] in ['spend', 'post', 'reputation']:
            total_cost+=Tx['amount']
        if Tx['type']=='mint':
            total_cost-=custom.block_reward
    return int(blockchain.db_get(address, DB)['amount'])>=total_cost+custom.fee
Example #11
0
def adjust_count(pubkey, DB, upward=True):
    try:
        acc=blockchain.db_get(pubkey, DB)
    except:
        blockchain.db_put(pubkey, {'count': 1}, DB)
        return
    if 'count' not in acc: acc['count']=0
    if upward: acc['count']+=1
    else: acc['count']-=1
    blockchain.db_put(pubkey, acc, DB)
Example #12
0
def enough_coins(tx, txs, DB):
    address = addr(tx)
    total_cost = 0
    for Tx in filter(lambda t: address == addr(t), [tx] + txs):
        if Tx['type'] in ['spend', 'post', 'reputation']:
            total_cost += Tx['amount']
        if Tx['type'] == 'mint':
            total_cost -= custom.block_reward
    return int(blockchain.db_get(address,
                                 DB)['amount']) >= total_cost + custom.fee
Example #13
0
 def fork_check(newblocks, DB):
     #if we are on a fork, return True
     try:
         length=copy.deepcopy(DB['length'])
         block=blockchain.db_get(length, DB)
         recent_hash=tools.det_hash(block)
         return recent_hash not in map(tools.det_hash, newblocks)
     except Exception as e:
         #print('ERROR: ' +str(e))
         return False
Example #14
0
 def rangeRequest(dic, DB):
     ran = dic['range']
     out = []
     counter = 0
     while len(tools.package(out)) < 50000 and ran[0] + counter <= ran[1]:
         block = blockchain.db_get(ran[0] + counter, DB)
         if 'length' in block:
             out.append(block)
         counter += 1
     return out
Example #15
0
def spend_verify(tx, txs, DB):
    tx_copy = copy.copy(tx)
    tx_copy.pop("signature")
    msg = tools.det_hash(tx_copy)
    if not pt.ecdsa_verify(msg, tx["signature"], tx["id"]):
        return False
    if tx["amount"] < custom.fee:
        return False
    if int(blockchain.db_get(tx["id"], DB)["amount"]) < int(tx["amount"]):
        return False
    return True
Example #16
0
def adjust_amount(pubkey, amount, DB):
    try:
        acc = blockchain.db_get(pubkey, DB)
    except:
        blockchain.db_put(pubkey, {"amount": amount}, DB)
        return
    if "amount" not in acc:
        acc["amount"] = amount
    else:
        acc["amount"] += amount
    blockchain.db_put(pubkey, acc, DB)
Example #17
0
 def rangeRequest(dic, DB):
     ran = dic['range']
     out = []
     counter = 0
     while len(tools.package(
             out)) < custom.max_download and ran[0] + counter <= ran[1]:
         block = blockchain.db_get(ran[0] + counter, DB)
         if 'length' in block:
             out.append(block)
         counter += 1
     return out
Example #18
0
 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
Example #19
0
 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
Example #20
0
def adjust_count(pubkey, DB, upward=True):
    try:
        acc = blockchain.db_get(pubkey, DB)
    except:
        blockchain.db_put(pubkey, {"count": 1}, DB)
        return
    if "count" not in acc:
        acc["count"] = 0
    if upward:
        acc["count"] += 1
    else:
        acc["count"] -= 1
    blockchain.db_put(pubkey, acc, DB)
Example #21
0
def mine(hashes_till_check, reward_address, DB):
    def make_mint(pubkey, DB): return {'type':'mint', 'id':pubkey, 'count':blockchain.count(pubkey, DB)}
    def genesis(pubkey, DB):
        out={'version':custom.version,
             'length':0,
             'time':time.time(),
             'target':blockchain.target(DB),
             'txs':[make_mint(pubkey, DB)]}
        out=tools.unpackage(tools.package(out))
        return out
    def make_block(prev_block, txs, pubkey, DB):
        leng=int(prev_block['length'])+1
        out={'version':custom.version,
             'txs':txs+[make_mint(pubkey, DB)],
             'length':leng,
             'time':time.time(),
             'target':blockchain.target(DB, leng),
             'prevHash':tools.det_hash(prev_block)}
        out=tools.unpackage(tools.package(out))
        return out
    def POW(block, hashes, target):
        halfHash=tools.det_hash(block)
        block[u'nonce']=random.randint(0,100000000000000000)
        count=0
        while tools.det_hash({u'nonce':block['nonce'], u'halfHash':halfHash})>target:
            count+=1
            block[u'nonce']+=1
            if count>hashes:
                return {'error':False}
            ''' for testing sudden loss in hashpower from miners.
            if block[u'length']>150:# and block[u'nonce']%10==0: time.sleep(0.1)
            else: time.sleep(0.01)
            '''
        print('found block: ' +str(block))
        return block
    length=copy.deepcopy(DB['length'])
    if length==-1:
        block=genesis(reward_address, DB)
        txs=[]
    else:
        prev_block=blockchain.db_get(length, DB)
        txs=DB['txs']
        block=make_block(prev_block, txs, reward_address, DB)
    block=POW(block, hashes_till_check, blockchain.target(DB, block['length']))
    DB['suggested_blocks'].append(block)
Example #22
0
def home(DB, dic):
    if "BrainWallet" in dic:
        dic["privkey"] = pt.sha256(dic["BrainWallet"])
    elif "privkey" not in dic:
        return "<p>You didn't type in your brain wallet.</p>"
    privkey = dic["privkey"]
    pubkey = pt.privtopub(dic["privkey"])
    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 is: " + str(tools.pub2addr(pubkey)) + "</p>{}")
    out = out.format("<p>current block is: " + str(DB["length"]) + "</p>{}")
    try:
        balance = blockchain.db_get(pubkey, DB)
        balance = balance["amount"]
    except:
        balance = 0
    for tx in DB["txs"]:
        if tx["type"] == "spend" and tx["to"] == tools.pub2addr(pubkey):
            balance += tx["amount"]
        if tx["type"] == "spend" and tx["id"] == 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
                ),
            )
        )
    s = easyForm("/home", "Refresh", """    <input type="hidden" name="privkey" value="{}">""".format(privkey))
    return out.format(s)
Example #23
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']) 
Example #24
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('')
Example #25
0
def mine(dic):
    hashes_till_check = dic['hashes']
    reward_address = dic['reward_address']
    DB = dic['DB']

    # Tries to mine the next block hashes_till_check many times.
    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)
        }

    def genesis(pubkey, DB):
        target = blockchain.target(DB)
        out = {
            'version': custom.version,
            'length': 0,
            'time': time.time(),
            'target': target,
            'diffLength': blockchain.hexInvert(target),
            'txs': [make_mint(pubkey, DB)]
        }
        out = tools.unpackage(tools.package(out))
        return out

    def make_block(prev_block, txs, pubkey, DB):
        try:
            leng = int(prev_block['length']) + 1
        except:
            print('prev: ' + str(prev_block))
            error('here')
        target = blockchain.target(DB, leng)
        diffLength = blockchain.hexSum(prev_block['diffLength'],
                                       blockchain.hexInvert(target))
        out = {
            'version': custom.version,
            'txs': txs + [make_mint(pubkey, DB)],
            'length': leng,
            'time': time.time(),
            'diffLength': diffLength,
            'target': target,
            'prevHash': tools.det_hash(prev_block)
        }
        out = tools.unpackage(tools.package(out))
        return out

    def POW(block, hashes, target):
        halfHash = tools.det_hash(block)
        block[u'nonce'] = random.randint(0, 100000000000000000)
        count = 0
        while tools.det_hash({
                u'nonce': block['nonce'],
                u'halfHash': halfHash
        }) > target:
            count += 1
            block[u'nonce'] += 1
            if count > hashes:
                return {'error': False}
            ''' for testing sudden loss in hashpower from miners.
            if block[u'length']>150:
            else: time.sleep(0.01)
            '''
        return block

    length = DB['length']
    if length == -1:
        block = genesis(reward_address, DB)
        txs = []
    else:
        prev_block = blockchain.db_get(length, DB)
        txs = DB['txs']
        block = make_block(prev_block, txs, reward_address, DB)
    block = POW(block, hashes_till_check,
                blockchain.target(DB, block['length']))
    DB['suggested_blocks'].append(block)
Example #26
0
 def fork_check(newblocks, DB):
     length = copy.deepcopy(DB['length'])
     block = blockchain.db_get(length, DB)
     recent_hash = tools.det_hash(block)
     their_hashes = map(tools.det_hash, newblocks)
     return recent_hash not in map(tools.det_hash, newblocks)
Example #27
0
 def give_block(peer, DB, block_count):
     cmd({'type': 'pushblock',
          'block': blockchain.db_get(block_count['length'] + 1,
                                     DB)})
     return []
Example #28
0
def adjust(key, pubkey, amount, DB):
    acc=blockchain.db_get(pubkey, DB)
    acc[key]+=amount
    blockchain.db_put(pubkey, acc, DB)
Example #29
0
def adjust(key, pubkey, amount, DB):
    acc = blockchain.db_get(pubkey, DB)
    acc[key] += amount
    blockchain.db_put(pubkey, acc, DB)
Example #30
0
 def fork_check(newblocks, DB):
     block = blockchain.db_get(DB['length'], DB)
     recent_hash = tools.det_hash(block)
     their_hashes = map(tools.det_hash, newblocks)
     return recent_hash not in their_hashes
Example #31
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('')
Example #32
0
 def give_block(peer, DB, block_count):
     cmd({'type': 'pushblock',
          'block': blockchain.db_get(block_count['length'] + 1,
                                     DB)})
     return []
def adjust(key, pubkey, amount, DB, sign=1):
    acc = blockchain.db_get(pubkey, DB)
    if not DB['add_block']: sign=-1
    acc[key] += amount*sign
    blockchain.db_put(pubkey, acc, DB)
Example #34
0
def miner_controller(reward_address, peers, hashes_till_check, DB):
    """ Spawns worker CPU mining processes and coordinates the effort."""
    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)}

    def genesis(pubkey, DB):
        target = blockchain.target(DB)
        out = {'version': custom.version,
               'length': 0,
               'time': time.time(),
               'target': target,
               'diffLength': blockchain.hexInvert(target),
               'txs': [make_mint(pubkey, DB)]}
        print('out: ' + str(out))
        out = tools.unpackage(tools.package(out))
        return out

    def make_block(prev_block, txs, pubkey, DB):
        leng = int(prev_block['length']) + 1
        target = blockchain.target(DB, leng)
        diffLength = blockchain.hexSum(prev_block['diffLength'],
                                       blockchain.hexInvert(target))
        out = {'version': custom.version,
               'txs': txs + [make_mint(pubkey, DB)],
               'length': leng,
               'time': time.time(),
               'diffLength': diffLength,
               'target': target,
               'prevHash': tools.det_hash(prev_block)}
        out = tools.unpackage(tools.package(out))
        return out
    def restart_workers():
        print("Possible solution found, restarting mining workers.")
        for worker_mailbox in worker_mailboxes:
            worker_mailbox['restart'].set()

    def spawn_worker():
        print("Spawning worker")
        restart_signal = multiprocessing.Event()
        work_queue = multiprocessing.Queue()
        worker_proc = multiprocessing.Process(target=miner,
                                              args=(submitted_blocks, work_queue,
                                                    restart_signal))
        worker_proc.daemon = True
        worker_proc.start()
        return {'restart': restart_signal, 'worker': worker_proc,
                'work_queue': work_queue}

    submitted_blocks = multiprocessing.Queue()
    num_cores = multiprocessing.cpu_count()
    print("Creating %d mining workers." % num_cores)
    worker_mailboxes = [spawn_worker() for _ in range(num_cores)]
    candidate_block = None
    length = None
    while True:
        length = DB['length']
        if length == -1:
            candidate_block = genesis(reward_address, DB)
            txs = []
        else:
            prev_block = blockchain.db_get(length, DB)
            txs = DB['txs']
            candidate_block = make_block(prev_block, txs, reward_address, DB)

        work = (candidate_block, hashes_till_check)

        for worker_mailbox in worker_mailboxes:
            worker_mailbox['work_queue'].put(copy.copy(work))

        # When block found, add to suggested blocks.
        solved_block = submitted_blocks.get()  # TODO(roasbeef): size=1?
        if solved_block['length'] != length + 1:
            continue
        DB['suggested_blocks'].append(solved_block)
        restart_workers()
Example #35
0
 def fork_check(newblocks, DB):
     length = copy.deepcopy(DB['length'])
     block = blockchain.db_get(length, DB)
     recent_hash = tools.det_hash(block)
     their_hashes = map(tools.det_hash, newblocks)
     return recent_hash not in map(tools.det_hash, newblocks)
Example #36
0
def adjust(key, pubkey, amount, DB, sign=1):
    acc = blockchain.db_get(pubkey, DB)
    if not DB['add_block']: sign = -1
    acc[key] += amount * sign
    blockchain.db_put(pubkey, acc, DB)