Пример #1
0
def wif_private_key(private_key_with_version):

    # Hash the private_key_with_version value using the cryptographic hash function SHA256.
    # This Secure Hash Algorithm generates a 256-bit (32-byte) signature which cannot be decrypted back
    # to the original value (it is a one-way cryptographic function).
    # The hash_a1 value is always 32 bytes or 64 characters long.
    hash_a1 = pybitcointools.sha256(private_key_with_version.decode('hex'))

    # Hash the hash_a1 value using the same cryptographic hash function SHA256.
    # The hash_a2 value is always 32 bytes or 64 characters long.
    hash_a2 = pybitcointools.sha256(hash_a1.decode('hex'))

    # Get the first 4 bytes (or first 8 characters) of the hash_a2 value.
    # These 4 bytes is the checksum value which will be used to validate the address.
    # The checksum_a value is always 4 bytes or 8 characters long.
    checksum_a = BytesIO(hash_a2.decode('hex')).read(4).encode('hex')

    # Append the checksum_a value at the end of the private_key_with_version value.
    # The private_key_checksum value is always (33+4=) 37 bytes or 74 characters long.
    private_key_checksum = private_key_with_version + checksum_a

    # The Private Key Wallet Import Format (WIF) for uncompressed public key is the private_key_checksum
    # value encoded into a Base58 value. The private_key_wif_uncompressed value must be kept secret and
    # can be converted into QR codes and can be printed on paper wallets.
    #
    # If your software uses the private_key_wif_uncompressed value, it also means you are the using the
    # and uncompressed Public Key.
    #
    # It is recommended to always to use the compressed public key (public_address_compressed) and the compressed
    # private key (private_key_wif_for_compressed). If your software does not support the compressed keys you can use
    # the uncompressed public key (public_address_uncompressed) and the
    # corresponding WIF (private_key_wif_for_uncompressed).
    return base58.b58encode(private_key_checksum.decode('hex'))
    def create_signup_info(cls, originator_public_key_hash,
                           most_recent_wait_certificate_id):
        with cls._lock:
            # First we need to create a public/private key pair for the PoET
            # enclave to use.
            cls._poet_private_key = pybitcointools.random_key()
            cls._poet_public_key = \
                pybitcointools.privtopub(cls._poet_private_key)
            cls._active_wait_timer = None

            # We are going to fake out the sealing the signup data.
            signup_data = {
                'poet_public_key':
                pybitcointools.encode_pubkey(cls._poet_public_key, 'hex'),
                'poet_private_key':
                pybitcointools.encode_privkey(cls._poet_private_key, 'hex')
            }
            sealed_signup_data = \
                pybitcointools.base64.b64encode(dict2json(signup_data))

            # Create a fake report
            report_data = {
                'originator_public_key_hash':
                originator_public_key_hash.upper(),
                'poet_public_key':
                pybitcointools.encode_pubkey(cls._poet_public_key,
                                             'hex').upper()
            }
            report = {
                'report_data': pybitcointools.sha256(dict2json(report_data))
            }

            # Fake our "proof" data.
            verification_report = {
                'enclave_quote':
                pybitcointools.base64.b64encode(dict2json(report)),
                'pse_manifest_hash':
                pybitcointools.base64.b64encode(
                    pybitcointools.sha256('manifest destiny')),
                'nonce':
                most_recent_wait_certificate_id
            }

            proof_data = {
                'verification_report':
                dict2json(verification_report),
                'signature':
                pybitcointools.ecdsa_sign(dict2json(verification_report),
                                          cls._report_private_key)
            }
            proof_data_dict = dict2json(proof_data)

            return \
                EnclaveSignupInfo(
                    poet_public_key=signup_data['poet_public_key'],
                    proof_data=proof_data_dict,
                    anti_sybil_id=originator_public_key_hash,
                    sealed_signup_data=sealed_signup_data)
Пример #3
0
def public_address(public_key_version):

    # Hash the public_key_version value using the cryptographic hash function SHA256.
    # This Secure Hash Algorithm generates a 256-bit (32-byte) signature which cannot be decrypted back
    # to the original value (it is a one-way cryptographic function).
    # The hash_c1 value is always 32 bytes or 64 characters long.
    hash_c1 = pybitcointools.sha256(public_key_version.decode('hex'))

    # Hash the hash_c1 value using the cryptographic hash function RIPEMD160.
    # The RIPEMD160 (RACE Integrity Primitives Evaluation Message Digest) generates a 160-bit (20-byte) signature
    # which cannot be decrypted back to the original value (it is a one-way cryptographic function).
    # The hash_c2 value is always 20 bytes or 40 characters long.
    hash_c2 = hashlib.new('ripemd160', hash_c1.decode('hex')).hexdigest()

    # Each cryptocurrency Public Key has their own prefix version number (Bitcoin= 0x00, Litecoin=0x30, etc).
    # Prepend this version number in front of the hash_c2 value.
    # The prefix version number is always 1 byte in size and the hash_c2 is 20 bytes.
    # The public_key_version_hash_c value is always (1+20=) 21 bytes or 42 characters long.
    public_key_version_hash_c = '00' + hash_c2

    # Hash the public_key_version_hash_c value using the cryptographic hash function SHA256.
    # This Secure Hash Algorithm generates a 256-bit (32-byte) signature which cannot be decrypted back
    # to the original value (it is a one-way cryptographic function).
    # The hash_c3 value is always 32 bytes or 64 characters long.
    hash_c3 = pybitcointools.sha256(public_key_version_hash_c.decode('hex'))

    # Hash the hash_c3 value using the cryptographic hash function SHA256.
    # This Secure Hash Algorithm generates a 256-bit (32-byte) signature which cannot be decrypted back
    # to the original value (it is a one-way cryptographic function).
    # The hash_c4 value is always 32 bytes or 64 characters long.
    hash_c4 = pybitcointools.sha256(hash_c3.decode('hex'))

    # Get the first 4 bytes (or first 8 characters) of the hash_c4 value.
    # These 4 bytes is the checksum value which will be used to validate the address.
    # The checksum_c value is always 4 bytes or 8 characters long.
    checksum_c = BytesIO(hash_c4.decode('hex')).read(4).encode('hex')

    # Append the checksum_c value at the end of the public_key_version_hash_c value.
    # The public_key_checksum_c value is always (21+4=) 25 bytes or 50 characters long.
    public_key_checksum_c = public_key_version_hash_c + checksum_c

    # The Public Address uncompressed is the public_key_checksum_c value encoded into a
    # Base58Check value. The generated value can be made public and can be converted into QR codes
    # for sharing it easily via wallet apps.
    #
    # It is recommended to always to use a compressed Public Key/Public Address and the corresponding
    # WIF. If your software does not support the compressed format you can still use
    # the uncompressed keypair, although not recommended.
    return base58.b58encode(public_key_checksum_c.decode('hex'))
Пример #4
0
def sender_payee_address_from_stealth(sender_prikey, receiver_pubkey):
    # sender - derive payee address
    ss1 = btc.multiply(receiver_pubkey, sender_prikey)
    ss2 = btc.sha256(btc.encode_pubkey((ss1), 'bin_compressed'))
    addr = btc.pubkey_to_address(btc.add_pubkeys(
        receiver_pubkey, btc.privtopub(ss2)))
    return addr
Пример #5
0
def home(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'])
    def clean_state():
        transactions=blockchain.load_transactions()
        state=state_library.current_state()
        a=blockchain.verify_transactions(transactions, state)
        print('a: ' +str(a))
        return a['newstate']
    state=clean_state()
    if 'do' in dic.keys():
        if dic['do']=='newGame':
            newgame(dic['partner'], dic['game'], pubkey, privkey, state, dic['size'])
            active_games.append(dic['game'])
        if dic['do']=='joinGame':
            active_games.append(dic['game'])
        if dic['do']=='spend':
            try:
                spend(float(dic['amount']), pubkey, privkey, dic['to'], state)
            except:
                pass
        state=clean_state()
    out=empty_page
    out=out.format('<p>your address is: ' +str(pubkey)+'</p>{}')
    print('state: ' +str(state))
    out=out.format('<p>current block is: ' +str(state['length'])+'</p>{}')
    if pubkey not in state:
        state[pubkey]={'amount':0}
    if 'amount' not in state[pubkey]:
        state[pubkey]['amount']=0
    out=out.format('<p>current balance is: ' +str(state[pubkey]['amount']/100000.0)+'</p>{}')        
    if state[pubkey]['amount']>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))
    out=out.format(s)
    out=out.format("<p>You are currently watching these games: {}</p>{}".format(str(active_games),"{}"))
    out=out.format(easyForm('/game', 'Play games', '''<input type="hidden" name="privkey" value="{}">'''.format(privkey)))

    out=out.format(easyForm('/home', 'Join Game', '''
    <input type="hidden" name="do" value="joinGame">
    <input type="hidden" name="privkey" value="{}">
    <input type="text" name="game" value="unique game name">
    '''.format(privkey)))
    out=out.format(easyForm('/home', 'New Game', '''
    <input type="hidden" name="do" value="newGame">
    <input type="hidden" name="privkey" value="{}">
    <input type="text" name="game" value="unique game name">
    <input type="text" name="partner" value="put your partners address here.">
    <input type="text" name="size" value="board size (9, 13, 19 are popular)">
    '''.format(privkey)))
    return out
Пример #6
0
    def identifier(self):
        my_id = NullIdentifier
        if self.signature is not None:
            my_id = \
                pybitcointools.base64.b32encode(
                    pybitcointools.sha256(self.signature))

        return my_id[:16]
Пример #7
0
def uniqueSavePathName(dirname, filename):
    basename, ext = os.path.splitext(filename)
    try:
        basename_hash = pybitcointools.sha256(basename)
    except Exception:
        basename_hash = util.randomStr(64)
    return os.path.join(dirname,
                        str(time.time()).replace('.', ''), basename_hash + ext)
    def identifier(self):
        my_id = NullIdentifier
        if self.signature is not None:
            my_id = \
                pybitcointools.base64.b32encode(
                    pybitcointools.sha256(self.signature))

        return my_id[:16]
Пример #9
0
def game(dic):
    if 'BrainWallet' in dic:
        dic['privkey']=pt.sha256(dic['BrainWallet'])
    privkey=dic['privkey']
    pubkey=pt.privtopub(dic['privkey'])
    def clean_state():
        transactions=blockchain.load_transactions()
        state=state_library.current_state()
        return blockchain.verify_transactions(transactions, state)['newstate']
    state=clean_state()
    if 'do' in dic.keys():
        if dic['do']=='winGame':
            wingame(dic['game'], pubkey, privkey, state)
        if dic['do']=='deleteGame':
            active_games.remove(dic['game'])
        state=clean_state()
    if 'move' in dic.keys():
        string=dic['move'].split(',')
        i=int(string[0])
        j=int(string[1])
        move(dic['game'], [i, j], pubkey, privkey, state)
        state=clean_state()
    out=empty_page
    out=out.format('<p>your address is: ' +str(pubkey)+'</p>{}')
    print('state: ' +str(state))
    out=out.format('<p>current block is: ' +str(state['length'])+'</p>{}')
    if pubkey not in state:
        state[pubkey]={'amount':0}
    if 'amount' not in state[pubkey]:
        state[pubkey]['amount']=0
    out=out.format('<p>current balance is: ' +str(state[pubkey]['amount']/100000.0)+'</p>{}')        
    s=easyForm('/game', 'refresh', '''    <input type="hidden" name="privkey" value="{}">'''.format(privkey))
    out=out.format(s)
    s=easyForm('/home', 'main menu', '''    <input type="hidden" name="privkey" value="{}">'''.format(privkey))
    out=out.format(s)
    for game in active_games:
        out=out.format("<h1>"+str(game)+"</h1>{}")
        if game in state:
            out=out.format('<h1>Timer: ' + str(state[game]['last_move_time']+state[game]['time']-state['length'])+' </h1>{}')
        if game in state.keys():
            in_last_block=state[game]
            out=board(out, state, game, privkey)
            out=out.format(easyForm('/game', 'win this game', '''
            <input type="hidden" name="do" value="winGame">
            <input type="hidden" name="privkey" value="{}">
            <input type="hidden" name="game"  value="{}">'''.format(privkey, game)))
            out=out.format(easyForm('/game', 'leave this game', '''
            <input type="hidden" name="do" value="deleteGame">
            <input type="hidden" name="privkey" value="{}">
            <input type="hidden" name="game"  value="{}">'''.format(privkey, game)))
        else:
            out=out.format("<p>this game does not yet exist</p>{}")
            out=out.format(easyForm('/game', 'delete this game', '''
            <input type="hidden" name="do" value="deleteGame">
            <input type="hidden" name="privkey" value="{}">
            <input type="hidden" name="game"  value="{}">'''.format(privkey,game)))
    return out
Пример #10
0
    def create_signup_info(cls, originator_public_key):
        # First we need to create a public/private key pair for the PoET
        # enclave to use.
        cls._poet_private_key = pybitcointools.random_key()
        cls._poet_public_key = pybitcointools.privtopub(cls._poet_private_key)
        cls._active_wait_timer = None

        # We are going to fake out the sealing the signup data.
        signup_data = {
            'poet_public_key':
            pybitcointools.encode_pubkey(cls._poet_public_key, 'hex'),
            'poet_private_key':
            pybitcointools.encode_privkey(cls._poet_private_key, 'hex')
        }
        sealed_signup_data = \
            pybitcointools.base64.b32encode(dict2json(signup_data))

        # Create a fake report
        report_data = {
            'originator_public_key_hash':
            pybitcointools.sha256(
                pybitcointools.encode_pubkey(originator_public_key, 'hex')),
            'poet_public_key':
            pybitcointools.encode_pubkey(cls._poet_public_key, 'hex')
        }
        report = {'report_data': pybitcointools.sha256(dict2json(report_data))}
        report = pybitcointools.base64.b32encode(dict2json(report))

        # Fake our "proof" data.
        proof_data = {
            'attestation_evidence_payload':
            pybitcointools.sha256(report),
            'attestation_verification_report':
            pybitcointools.sha256('Shave and a haircut...Two bits!')
        }

        return \
            EnclaveSignupInfo(
                anti_sybil_id='Sally Field',
                poet_public_key=signup_data['poet_public_key'],
                proof_data=proof_data,
                sealed_signup_data=sealed_signup_data)
Пример #11
0
    def __init__(self, private, url=NETVEND_URL, seed=False):
        if seed:
            self._private = pybitcointools.sha256(private)
        else:
            try:
                self._private = pybitcointools.b58check_to_hex(private)
            except AssertionError:
                raise RuntimeError("Invalid private key. Did you mean to set seed=True?")

        self.address = pybitcointools.pubkey_to_address(pybitcointools.privtopub(self._private))
        self.url = url
Пример #12
0
def blockhash(chain_length, nonce, state, transactions, bitcoin_hash):
    fixed_transactions=[]
    if len(transactions)==0:
        error('here')
    for i in transactions:
        new=''
        for key in sorted(i.keys()):
            new=new+str(key)+':'+str(i[key])+','
        fixed_transactions.append(new)
    exact=str(chain_length)+str(nonce)+str(state['recent_hash'])+str(sorted(fixed_transactions))+str(bitcoin_hash)
#    return {'hash':pt.sha256(exact), 'exact':exact}
    return {'hash':pt.sha256(exact)}
Пример #13
0
def blockhash(chain_length, nonce, state, transactions):
    fixed_transactions=[]
    if len(transactions)==0:
        error('here')
    for i in transactions:
        new=''
        for key in sorted(i.keys()):
            new=new+str(key)+':'+str(i[key])+','
        fixed_transactions.append(new)
    exact=str(chain_length)+str(nonce)+str(state['recent_hash'])+str(sorted(fixed_transactions))
#    return {'hash':pt.sha256(exact), 'exact':exact}
    return {'hash':pt.sha256(exact)}
Пример #14
0
    def __init__(self, private, url=NETVEND_URL, seed=False):
        if seed:
            self._private = pybitcointools.sha256(private)
        else:
            try:
                self._private = pybitcointools.b58check_to_hex(private)
            except AssertionError:
                raise RuntimeError(
                    "Invalid private key. Did you mean to set seed=True?")

        self.address = pybitcointools.pubkey_to_address(
            pybitcointools.privtopub(self._private))
        self.url = url
    def test_exception_on_bad_hash(self):
        """
        Tests Exception Handling
        Inputs an invalid (negative) hash value to the native method
        """
        d = pbt.sha256('private key')
        msghash = pbt.electrum_sig_hash('test message')
        z = -pbt.hash_to_int(msghash)
        v, r, s = pbt.ecdsa_raw_sign(msghash, d)
        yBit = v - 27
        with self.assertRaises(ValueError) as context:
            result = ecnative.recover_pubkey(str(z), str(r), str(s), int(yBit))

        self.assertTrue('hash' in str(context.exception))
Пример #16
0
    def test_exception_on_empty_param(self):
        """
        Tests Exception Handling
        Passes an empty string as an invalid argument to the native method
        """
        d = pbt.sha256('private key')
        msghash = pbt.electrum_sig_hash('test message')
        z = pbt.hash_to_int(msghash)
        v, _, s = pbt.ecdsa_raw_sign(msghash, d)
        y_bit = v - 27
        with self.assertRaises(ValueError) as context:
            _ = ecnative.recover_pubkey(str(z), str(""), str(s), int(y_bit))

        self.assertTrue('Empty string' in str(context.exception))
Пример #17
0
def buy_bid(dic):
    cmd_num=str(dic['cmd_num'])
    buy_currency=str(dic['buy_currency'])
    buy_coin=currencies(buy_currency)
    buy_amount=float(dic['buy_amount'])
    sell_currency=str(dic['sell_currency'])
    sell_coin=currencies(sell_currency)
    sell_amount=float(dic['sell_amount'])
    user=str(dic['user'])
    current_money=float(sell_coin.getbalance(user, 12))
    future_money=float(sell_coin.getbalance(user))
    bought_so_far=0.0
    if [buy_currency, sell_currency].count('bitcoin')!=1:
        return package({'type':'error', 'message':'you must either buy bitcoin, or sell bitcoin, every time.'})        
    if current_money>= sell_amount:
#        sell_coin.move(user, "", sell_amount)
        available=available_bids(sell_currency, sell_amount, buy_currency, buy_amount)
        out={'type':'success', 'message':empty_page}
        print('available: ' +str(available))
        while len(available)>0 and buy_amount>bought_so_far:#buy entire bid
            owner_name=available[0]['owner']
            if buy_amount-bought_so_far>=float(available[0]['sell_amount']):
                bought_so_far+=float(available[0]['buy_amount'])
                sell_coin.move(user, owner_name, float(available[0]['buy_amount']))
                buy_coin.move("", user, float(available[0]['sell_amount']))
                append_to_trades(available[0])
                remove_bid(available[0])
                out['message']=out['message'].format("<p>successfully purchased a bid</p>{}")
            else:#buy part of a bid
                buy_coin.move("", user, buy_amount-bought_so_far)
                sell_coin.move(user, owner_name, (buy_amount-bought_so_far)*price(available[0]))
                def f(a, b):
                    return (b-a)/b
                p=f(buy_amount-bought_so_far, available[0]['buy_amount'])
                adjust_bid(available[0], p)
                bought_so_far=buy_amount
                out['message']=out['message'].format("<p>successfully purchased part of a bid</p>{}")
        if buy_amount-bought_so_far>0:
            print('user: '******'buy_amount':buy_amount, 'sell_amount': sell_amount,'buy_currency':buy_currency ,'sell_currency':sell_currency ,'owner':user, 'cmd_num':cmd_num}
            newbid['price']=price(newbid)
            newbid['bid_id']=pt.sha256(json.dumps(newbid).encode('hex'))
            add2bids(newbid)
            out['message']=out['message'].format('<p>successfully submitted a bid</p>{}')
    else:
        return package({'type':'error', 'message':'not enough money'})
    return package(out)
Пример #18
0
    def test_exception_on_empty_param(self):
        """
        Tests Exception Handling
        Passes an empty string as an invalid argument to the native method
        """
        d = pbt.sha256('private key')
        msghash = pbt.electrum_sig_hash('test message')
        z = pbt.hash_to_int(msghash)
        v, r, s = pbt.ecdsa_raw_sign(msghash, d)
        yBit = v - 27
        with self.assertRaises(ValueError) as context:
            result = ecnative.recover_pubkey(
                str(z), str(""), str(s),
                int(yBit))

        self.assertTrue('Empty string' in str(context.exception))
Пример #19
0
    def test_exception_on_bad_hash(self):
        """
        Tests Exception Handling
        Inputs an invalid (negative) hash value to the native method
        """
        d = pbt.sha256('private key')
        msghash = pbt.electrum_sig_hash('test message')
        z = -pbt.hash_to_int(msghash)
        v, r, s = pbt.ecdsa_raw_sign(msghash, d)
        yBit = v - 27
        with self.assertRaises(ValueError) as context:
            result = ecnative.recover_pubkey(
                str(z), str(r), str(s),
                int(yBit))

        self.assertTrue('hash' in str(context.exception))
    def test_exception_on_bad_sig(self):
        """
        Tests Exception Handling
        Inputs an invalid number to the native method
        """
        d = pbt.sha256('private key')
        msghash = pbt.electrum_sig_hash('test message')
        z = pbt.hash_to_int(msghash)
        v, r, s = pbt.ecdsa_raw_sign(msghash, d)
        yBit = v - 27
        badval = "58995174607243353628346858794753620798088291196940745194" \
            "58148184192713284575299999999999999h"
        with self.assertRaises(ValueError) as context:
            result = ecnative.recover_pubkey(str(z), str(badval), str(s),
                                             int(yBit))

        self.assertTrue('Invalid signature' in str(context.exception))
Пример #21
0
 def parse(self, data):
     if re.match('^[0-9a-fA-F]*$', data):
         data = data.decode('hex')
     o = rlp.decode(data)
     self.nonce = o[0]
     self.to = o[1]
     self.value = o[2]
     self.fee = o[3]
     self.data = o[4]
     self.v = o[5]
     self.r = o[6]
     self.s = o[7]
     rawhash = sha256(
         rlp.encode([self.nonce, self.to, self.value, self.fee, self.data]))
     pub = encode_pubkey(
         ecdsa_raw_recover(rawhash, (self.v, self.r, self.s)), 'bin')
     self.sender = bin_sha256(pub[1:])[-20:]
     return self
Пример #22
0
    def test_exception_on_bad_sig(self):
        """
        Tests Exception Handling
        Inputs an invalid number to the native method
        """
        d = pbt.sha256('private key')
        msghash = pbt.electrum_sig_hash('test message')
        z = pbt.hash_to_int(msghash)
        v, r, s = pbt.ecdsa_raw_sign(msghash, d)
        yBit = v - 27
        badval = "58995174607243353628346858794753620798088291196940745194" \
            "58148184192713284575299999999999999h"
        with self.assertRaises(ValueError) as context:
            result = ecnative.recover_pubkey(
                str(z), str(badval), str(s),
                int(yBit))

        self.assertTrue('Invalid signature' in str(context.exception))
Пример #23
0
    def __init__(self, private, url, privtype):
        if privtype is PRIVTYPE_SEED:
            self.private = pybitcointools.sha256(private)
        elif privtype is PRIVTYPE_B58CHECK:
            try:
                self.private = pybitcointools.b58check_to_hex(private)
            except AssertionError:
                raise ValueError("Invalid private key")
        elif privtype is PRIVTYPE_HEX:
            if len(private) == 64:
                self.private = private
            else:
                raise ValueError("Invalid private key")
        else:
            # Raise a ValueError, otherwise self.private would not be defined
            raise ValueError("Invalid privtype")

        self.address = pybitcointools.pubkey_to_address(pybitcointools.privtopub(self.private))
        self.url = url
    def verify_signup_info(cls, signup_info, originator_public_key_hash,
                           most_recent_wait_certificate_id):
        # Verify the attestation verification report signature
        proof_data = json2dict(signup_info.proof_data)
        verification_report = proof_data.get('verification_report')
        if verification_report is None:
            raise \
                SignupInfoError(
                    'Verification report is missing from proof data')

        if not pybitcointools.ecdsa_verify(verification_report,
                                           proof_data.get('signature'),
                                           cls._report_public_key):
            raise \
                SignupInfoError('Verification report signature is invalid')

        # Verify that the report data field in the report contains the SHA256
        # digest of the originator's public key SHA 256 digest and the PoET
        # public key.
        verification_report_dict = json2dict(verification_report)

        enclave_quote = verification_report_dict.get('enclave_quote')
        if enclave_quote is None:
            raise \
                SignupInfoError(
                    'Verification report does not contain an enclave quote')

        report = json2dict(pybitcointools.base64.b64decode(enclave_quote))
        report_data = report.get('report_data')
        if report_data is None:
            raise \
                SignupInfoError('Enclave quote does not contain report data')

        target_report_data = {
            'originator_public_key_hash': originator_public_key_hash.upper(),
            'poet_public_key': signup_info.poet_public_key.upper()
        }
        target_report_data_digest = \
            pybitcointools.sha256(dict2json(target_report_data))

        if report_data != target_report_data_digest:
            raise SignupInfoError('Enclave quote report data is invalid')
Пример #25
0
# In our case MultiSig works with three parties.  Each party keeps
# his own private key and never shares it.  A public key is created
# for each of the three private keys -- these public keys
# *are* shared between the the parties.  This way each member of
# the party can recreate the same script.
# privkey1 = bitcoin.random_key()
# privkey2 = bitcoin.random_key()
# privkey3 = bitcoin.random_key()

# use previously defined private keys
privkey1 = 'eeaef3180e49e1910e7fb5aff6047d04c2d29aa26c84686be82fd2fbb58f22c9'
privkey2 = '17b10bb69ee84975776fe3b9af8ee6fed3709484afdb915eca6d5a1968352b8c'
privkey3 = '897c738ca8aa4dca96a68926b1877bdbcc8e198eac85d26f3fc6f8c4b1673974'

pwd = getpass.getpass('Password: '******'privkey'
print '    ' + repr(privkey)
print 'privkey1'
print '    ' + repr(privkey1)
print 'privkey2'
print '    ' + repr(privkey2)
print 'privkey3'
print '    ' + repr(privkey3)
print ' ' 
Пример #26
0
def txid(tx):
    return pt.sha256(deterministic_dic(tx))
Пример #27
0
import blockchain, config, threading, gui, listener, os, subprocess, re
import pybitcointools as pt
my_privkey = pt.sha256(config.brain_wallet)
my_pubkey = pt.privtopub(my_privkey)


def kill_processes_using_ports(ports):
    popen = subprocess.Popen(['netstat', '-lpn'],
                             shell=False,
                             stdout=subprocess.PIPE)
    (data, err) = popen.communicate()
    pattern = "^tcp.*((?:{0})).* (?P<pid>[0-9]*)/.*$"
    pattern = pattern.format(')|(?:'.join(ports))
    prog = re.compile(pattern)
    for line in data.split('\n'):
        match = re.match(prog, line)
        if match:
            pid = match.group('pid')
            subprocess.Popen(['kill', '-9', pid])


try:
    kill_processes_using_ports([str(config.listen_port), str(config.gui_port)])
    kill_processes_using_ports([str(config.listen_port), str(config.gui_port)])
except:
    #so windows doesn't die
    pass
if __name__ == '__main__':
    #the first miner is for finding blocks. the second miner is for playing go and for talking to the network.
    todo = [[
        blockchain.mainloop,
Пример #28
0
def receiver_payee_privkey_from_stealth(receiver_prikey, sender_pubkey):
    # sender - derive payee address
    ss1 = btc.multiply(sender_pubkey, receiver_prikey)
    ss2 = btc.sha256(btc.encode_pubkey((ss1), 'bin_compressed'))
    key = btc.add_privkeys(receiver_prikey, ss2)
    return key
Пример #29
0
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import string, cgi, time, json, random, copy, cPickle, image64, os, pprint
import pybitcointools as pt
import urllib
PORT = 8090

privkey = pt.sha256("Brain Wallet3 ")
privkey2 = pt.sha256("Brain Walle")

user = pt.privtopub(privkey)  #your pubkey is your identity
user2 = pt.privtopub(privkey2)  #your pubkey is your identity

#url='http://6wsygte7i4ly7htk.tor2web.org/checkSig?command={}&signature={}'
#url='http://localhost:8091/checkSig?command={}&signature={}'
#url='http://3uc1id.no-ip.biz/checkSig?command={}&signature={}'
url = 'http://24.153.161.238/checkSig?command={}&signature={}'
database = 'cmd_num.db'


def package(dic):
    return json.dumps(dic).encode('hex')


def unpackage(dic):
    return json.loads(dic.decode('hex'))


def fs_load():
    try:
        out = cPickle.load(open(database, 'rb'))
        return out
 def initialize(cls, **kwargs):
     # Create an anti-Sybil ID that is unique for this validator
     cls._anti_sybil_id = \
         pybitcointools.sha256(kwargs.get('NodeName', 'validator'))
Пример #31
0
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import string,cgi,time, json, random, copy, cPickle, image64, os, pprint
import pybitcointools as pt
import urllib
PORT=8090

privkey=pt.sha256("Brain Wallet3 ")
privkey2=pt.sha256("Brain Walle")

user=pt.privtopub(privkey)#your pubkey is your identity
user2=pt.privtopub(privkey2)#your pubkey is your identity

#url='http://6wsygte7i4ly7htk.tor2web.org/checkSig?command={}&signature={}'
#url='http://localhost:8091/checkSig?command={}&signature={}'
url='http://3uc1id.no-ip.biz/checkSig?command={}&signature={}'
database='cmd_num.db'
def package(dic):
    return json.dumps(dic).encode('hex')
def unpackage(dic):
    return json.loads(dic.decode('hex'))
def fs_load():
    try:
        out=cPickle.load(open(database, 'rb'))
        return out
    except:
        fs_save(0)
        return cPickle.load(open(database, 'rb'))      

def fs_save(dic):
    cPickle.dump(dic, open(database, 'wb'))
Пример #32
0
 def setUp(self):
     self.brainwallet_string = 'Here is a brainwallet string for testing purposes'
     self.private_key = bc.sha256(self.brainwallet_string)
     self.private_key_wif = bc.encode_privkey(self.private_key, 'wif')
     self.addr = bc.privkey_to_address(self.private_key)
Пример #33
0
def home(dic):
    print(dic)
    if 'BrainWallet' in dic:
        dic['privkey']=pt.sha256(dic['BrainWallet'])
    privkey=dic['privkey']
    print('priv: ' +str(dic['privkey']))
    pubkey=pt.privtopub(dic['privkey'])
    if 'do' in dic.keys():
        if dic['do']=='newGame':
            try:
                a=newgame(dic['partner'], dic['game'], pubkey, privkey, int(dic['size']), dic['amount'])
            except:
                a=newgame(dic['partner'], dic['game'], pubkey, privkey, 19, dic['amount'])
            active_games.append(dic['game'])
        if dic['do']=='winGame':
            wingame(dic['game'], pubkey, privkey)
        if dic['do']=='joinGame':
            active_games.append(dic['game'])
        if dic['do']=='deleteGame':
            active_games.remove(dic['game'])
    if 'move' in dic.keys():
        string=dic['move'].split(',')
        i=int(string[0])
        j=int(string[1])
        move(dic['game'], [i, j], pubkey, privkey)
    fs=fs_load()
    out=empty_page
    out=out.format('<p>your address is: ' +str(pubkey)+'</p>{}')
    state=state_library.current_state()
    out=out.format('<p>current block is: ' +str(state['length'])+'</p>{}')
    transactions=blockchain.load_transactions()
    a=blockchain.verify_transactions(transactions, state)
    if a['bool']:
        state=a['newstate']
    else:
        pass
        print(a)
        print(transactions)
        print('ERROR')
    if pubkey not in state:
        state[pubkey]={'amount':0}
    if 'amount' not in state[pubkey]:
        state[pubkey]['amount']=0
    out=out.format('<p>current balance is: ' +str(state[pubkey]['amount']/100000.0)+'</p>{}')        
    for game in active_games:
        out=out.format("<h1>"+str(game)+"</h1>{}")
        if game in state:
            out=out.format('<h1>Timer: ' + str(state[game]['last_move_time']+state[game]['time']-state['length'])+' </h1>{}')
        if game in state.keys():
            in_last_block=state[game]
            out=board(out, state, game, privkey)
            out=out.format(easyForm('/home', 'win this game', '''
            <input type="hidden" name="do" value="winGame">
            <input type="hidden" name="privkey" value="{}">
            <input type="hidden" name="game"  value="{}">'''.format(privkey, game)))
            out=out.format(easyForm('/home', 'leave this game', '''
            <input type="hidden" name="do" value="deleteGame">
            <input type="hidden" name="privkey" value="{}">
            <input type="hidden" name="game"  value="{}">'''.format(privkey, game)))
        else:
            out=out.format("<p>this game does not yet exist</p>{}")
            out=out.format(easyForm('/home', 'delete this game', '''
            <input type="hidden" name="do" value="deleteGame">
            <input type="hidden" name="privkey" value="{}">
            <input type="hidden" name="game"  value="{}">'''.format(privkey,game)))
    out=out.format(easyForm('/home', 'Refresh boards', '''
    <input type="hidden" name="privkey" value="{}">
    '''.format(privkey)))    
    out=out.format(easyForm('/home', 'Join Game', '''
    <input type="hidden" name="do" value="joinGame">
    <input type="hidden" name="privkey" value="{}">
    <input type="text" name="game" value="unique game name">
    '''.format(privkey)))
    out=out.format(easyForm('/home', 'New Game', '''
    <input type="hidden" name="do" value="newGame">
    <input type="hidden" name="privkey" value="{}">
    <input type="text" name="game" value="unique game name">
    <input type="text" name="partner" value="put your partners address here.">
    <input type="text" name="size" value="board size (9, 13, 19 are popular)">
    <input type="text" name="amount" value="0">
    '''.format(privkey)))
    return out
Пример #34
0
def game(dic):
    if 'BrainWallet' in dic:
        dic['privkey'] = pt.sha256(dic['BrainWallet'])
    privkey = dic['privkey']
    pubkey = pt.privtopub(dic['privkey'])

    def clean_state():
        transactions = blockchain.load_transactions()
        state = state_library.current_state()
        return blockchain.verify_transactions(transactions, state)['newstate']

    state = clean_state()
    if 'do' in dic.keys():
        if dic['do'] == 'winGame':
            wingame(dic['game'], pubkey, privkey, state)
        if dic['do'] == 'deleteGame':
            active_games.remove(dic['game'])
        state = clean_state()
    if 'move' in dic.keys():
        string = dic['move'].split(',')
        i = int(string[0])
        j = int(string[1])
        move(dic['game'], [i, j], pubkey, privkey, state)
        state = clean_state()
    out = empty_page
    out = out.format('<p>your address is: ' + str(pubkey) + '</p>{}')
    print('state: ' + str(state))
    out = out.format('<p>current block is: ' + str(state['length']) + '</p>{}')
    if pubkey not in state:
        state[pubkey] = {'amount': 0}
    if 'amount' not in state[pubkey]:
        state[pubkey]['amount'] = 0
    out = out.format('<p>current balance is: ' +
                     str(state[pubkey]['amount'] / 100000.0) + '</p>{}')
    s = easyForm(
        '/game', 'refresh',
        '''    <input type="hidden" name="privkey" value="{}">'''.format(
            privkey))
    out = out.format(s)
    s = easyForm(
        '/home', 'main menu',
        '''    <input type="hidden" name="privkey" value="{}">'''.format(
            privkey))
    out = out.format(s)
    for game in active_games:
        out = out.format("<h1>" + str(game) + "</h1>{}")
        if game in state:
            out = out.format('<h1>Timer: ' +
                             str(state[game]['last_move_time'] +
                                 state[game]['time'] - state['length']) +
                             ' </h1>{}')
        if game in state.keys():
            in_last_block = state[game]
            out = board(out, state, game, privkey)
            out = out.format(
                easyForm(
                    '/game', 'win this game', '''
            <input type="hidden" name="do" value="winGame">
            <input type="hidden" name="privkey" value="{}">
            <input type="hidden" name="game"  value="{}">'''.format(
                        privkey, game)))
            out = out.format(
                easyForm(
                    '/game', 'leave this game', '''
            <input type="hidden" name="do" value="deleteGame">
            <input type="hidden" name="privkey" value="{}">
            <input type="hidden" name="game"  value="{}">'''.format(
                        privkey, game)))
        else:
            out = out.format("<p>this game does not yet exist</p>{}")
            out = out.format(
                easyForm(
                    '/game', 'delete this game', '''
            <input type="hidden" name="do" value="deleteGame">
            <input type="hidden" name="privkey" value="{}">
            <input type="hidden" name="game"  value="{}">'''.format(
                        privkey, game)))
    return out
Пример #35
0
def buy_bid(dic):
    cmd_num = str(dic['cmd_num'])
    buy_currency = str(dic['buy_currency'])
    buy_coin = currencies(buy_currency)
    buy_amount = float(dic['buy_amount'])
    sell_currency = str(dic['sell_currency'])
    sell_coin = currencies(sell_currency)
    sell_amount = float(dic['sell_amount'])
    user = str(dic['user'])
    current_money = float(sell_coin.getbalance(user, 12))
    future_money = float(sell_coin.getbalance(user))
    bought_so_far = 0.0
    if [buy_currency, sell_currency].count('bitcoin') != 1:
        return package({
            'type':
            'error',
            'message':
            'you must either buy bitcoin, or sell bitcoin, every time.'
        })
    if current_money >= sell_amount:
        #        sell_coin.move(user, "", sell_amount)
        available = available_bids(sell_currency, sell_amount, buy_currency,
                                   buy_amount)
        out = {'type': 'success', 'message': empty_page}
        print('available: ' + str(available))
        while len(
                available) > 0 and buy_amount > bought_so_far:  #buy entire bid
            owner_name = available[0]['owner']
            if buy_amount - bought_so_far >= float(
                    available[0]['sell_amount']):
                bought_so_far += float(available[0]['buy_amount'])
                sell_coin.move(user, owner_name,
                               float(available[0]['buy_amount']))
                buy_coin.move("", user, float(available[0]['sell_amount']))
                append_to_trades(available[0])
                remove_bid(available[0])
                out['message'] = out['message'].format(
                    "<p>successfully purchased a bid</p>{}")
            else:  #buy part of a bid
                buy_coin.move("", user, buy_amount - bought_so_far)
                sell_coin.move(user, owner_name, (buy_amount - bought_so_far) *
                               price(available[0]))

                def f(a, b):
                    return (b - a) / b

                p = f(buy_amount - bought_so_far, available[0]['buy_amount'])
                adjust_bid(available[0], p)
                bought_so_far = buy_amount
                out['message'] = out['message'].format(
                    "<p>successfully purchased part of a bid</p>{}")
        if buy_amount - bought_so_far > 0:
            print('user: '******'buy_amount': buy_amount,
                'sell_amount': sell_amount,
                'buy_currency': buy_currency,
                'sell_currency': sell_currency,
                'owner': user,
                'cmd_num': cmd_num
            }
            newbid['price'] = price(newbid)
            newbid['bid_id'] = pt.sha256(json.dumps(newbid).encode('hex'))
            add2bids(newbid)
            out['message'] = out['message'].format(
                '<p>successfully submitted a bid</p>{}')
    else:
        return package({'type': 'error', 'message': 'not enough money'})
    return package(out)
Пример #36
0
def home(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'])

    def clean_state():
        transactions = blockchain.load_transactions()
        state = state_library.current_state()
        a = blockchain.verify_transactions(transactions, state)
        print('a: ' + str(a))
        print('transactions: ' + str(transactions))
        try:
            return a['newstate']
        except:
            blockchain.reset_transactions()

    state = clean_state()
    if 'do' in dic.keys():
        if dic['do'] == 'newGame':
            newgame(dic['partner'], dic['game'], pubkey, privkey, state,
                    dic['size'])
            active_games.append(dic['game'])
        if dic['do'] == 'joinGame':
            active_games.append(dic['game'])
        if dic['do'] == 'spend':
            try:
                spend(float(dic['amount']), pubkey, privkey, dic['to'], state)
            except:
                pass
        state = clean_state()
    out = empty_page
    out = out.format('<p>your address is: ' + str(pubkey) + '</p>{}')
    print('state: ' + str(state))
    out = out.format('<p>current block is: ' + str(state['length']) + '</p>{}')
    if pubkey not in state:
        state[pubkey] = {'amount': 0}
    if 'amount' not in state[pubkey]:
        state[pubkey]['amount'] = 0
    out = out.format('<p>current balance is: ' +
                     str(state[pubkey]['amount'] / 100000.0) + '</p>{}')
    if state[pubkey]['amount'] > 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))
    out = out.format(s)
    out = out.format(
        "<p>You are currently watching these games: {}</p>{}".format(
            str(active_games), "{}"))
    out = out.format(
        easyForm(
            '/game', 'Play games',
            '''<input type="hidden" name="privkey" value="{}">'''.format(
                privkey)))

    out = out.format(
        easyForm(
            '/home', 'Join Game', '''
    <input type="hidden" name="do" value="joinGame">
    <input type="hidden" name="privkey" value="{}">
    <input type="text" name="game" value="unique game name">
    '''.format(privkey)))
    out = out.format(
        easyForm(
            '/home', 'New Game', '''
    <input type="hidden" name="do" value="newGame">
    <input type="hidden" name="privkey" value="{}">
    <input type="text" name="game" value="unique game name">
    <input type="text" name="partner" value="put your partners address here.">
    <input type="text" name="size" value="board size (9, 13, 19 are popular)">
    '''.format(privkey)))
    return out
Пример #37
0
def home(dic):
    print (dic)
    if "BrainWallet" in dic:
        dic["privkey"] = pt.sha256(dic["BrainWallet"])
    privkey = dic["privkey"]
    print ("priv: " + str(dic["privkey"]))
    pubkey = pt.privtopub(dic["privkey"])
    if "do" in dic.keys():
        if dic["do"] == "newGame":
            try:
                a = newgame(dic["partner"], dic["game"], pubkey, privkey, int(dic["size"]), dic["amount"])
            except:
                a = newgame(dic["partner"], dic["game"], pubkey, privkey, 19, dic["amount"])
            active_games.append(dic["game"])
        if dic["do"] == "winGame":
            wingame(dic["game"], pubkey, privkey)
        if dic["do"] == "joinGame":
            active_games.append(dic["game"])
        if dic["do"] == "deleteGame":
            active_games.remove(dic["game"])
    if "move" in dic.keys():
        string = dic["move"].split(",")
        i = int(string[0])
        j = int(string[1])
        move(dic["game"], [i, j], pubkey, privkey)
    fs = fs_load()
    out = empty_page
    out = out.format("<p>your address is: " + str(pubkey) + "</p>{}")
    state = state_library.current_state()
    out = out.format("<p>current block is: " + str(state["length"]) + "</p>{}")
    transactions = blockchain.load_transactions()
    a = blockchain.verify_transactions(transactions, state)
    if a["bool"]:
        state = a["newstate"]
    else:
        pass
        print (a)
        print (transactions)
        print ("ERROR")
    if pubkey not in state:
        state[pubkey] = {"amount": 0}
    if "amount" not in state[pubkey]:
        state[pubkey]["amount"] = 0
    out = out.format("<p>current balance is: " + str(state[pubkey]["amount"] / 100000.0) + "</p>{}")
    for game in active_games:
        out = out.format("<h1>" + str(game) + "</h1>{}")
        if game in state:
            out = out.format(
                "<h1>Timer: " + str(state[game]["last_move_time"] + state[game]["time"] - state["length"]) + " </h1>{}"
            )
        if game in state.keys():
            in_last_block = state[game]
            out = board(out, state, game, privkey)
            out = out.format(
                easyForm(
                    "/home",
                    "win this game",
                    """
            <input type="hidden" name="do" value="winGame">
            <input type="hidden" name="privkey" value="{}">
            <input type="hidden" name="game"  value="{}">""".format(
                        privkey, game
                    ),
                )
            )
            out = out.format(
                easyForm(
                    "/home",
                    "leave this game",
                    """
            <input type="hidden" name="do" value="deleteGame">
            <input type="hidden" name="privkey" value="{}">
            <input type="hidden" name="game"  value="{}">""".format(
                        privkey, game
                    ),
                )
            )
        else:
            out = out.format("<p>this game does not yet exist</p>{}")
            out = out.format(
                easyForm(
                    "/home",
                    "delete this game",
                    """
            <input type="hidden" name="do" value="deleteGame">
            <input type="hidden" name="privkey" value="{}">
            <input type="hidden" name="game"  value="{}">""".format(
                        privkey, game
                    ),
                )
            )
    out = out.format(
        easyForm(
            "/home",
            "Refresh boards",
            """
    <input type="hidden" name="privkey" value="{}">
    """.format(
                privkey
            ),
        )
    )
    out = out.format(
        easyForm(
            "/home",
            "Join Game",
            """
    <input type="hidden" name="do" value="joinGame">
    <input type="hidden" name="privkey" value="{}">
    <input type="text" name="game" value="unique game name">
    """.format(
                privkey
            ),
        )
    )
    out = out.format(
        easyForm(
            "/home",
            "New Game",
            """
    <input type="hidden" name="do" value="newGame">
    <input type="hidden" name="privkey" value="{}">
    <input type="text" name="game" value="unique game name">
    <input type="text" name="partner" value="put your partners address here.">
    <input type="text" name="size" value="board size (9, 13, 19 are popular)">
    <input type="text" name="amount" value="0">
    """.format(
                privkey
            ),
        )
    )
    return out
    def create_signup_info(cls,
                           originator_public_key,
                           validator_network_basename,
                           most_recent_wait_certificate_id):
        with cls._lock:
            # First we need to create a public/private key pair for the PoET
            # enclave to use.
            cls._poet_private_key = pybitcointools.random_key()
            cls._poet_public_key = \
                pybitcointools.privtopub(cls._poet_private_key)
            cls._active_wait_timer = None

            # We are going to fake out the sealing the signup data.
            signup_data = {
                'poet_public_key':
                    pybitcointools.encode_pubkey(cls._poet_public_key, 'hex'),
                'poet_private_key':
                    pybitcointools.encode_privkey(
                        cls._poet_private_key,
                        'hex')
            }
            sealed_signup_data = \
                pybitcointools.base64.b32encode(dict2json(signup_data))

            # Create a fake report
            report_data = {
                'originator_public_key_hash':
                    pybitcointools.sha256(
                        pybitcointools.encode_pubkey(
                            originator_public_key,
                            'hex')),
                'poet_public_key':
                    pybitcointools.encode_pubkey(cls._poet_public_key, 'hex')
            }
            report = {
                'report_data': pybitcointools.sha256(dict2json(report_data)),
                'validator_network_basename': validator_network_basename
            }

            # Fake our "proof" data.
            attestation_evidence_payload = {
                'enclave_quote':
                    pybitcointools.base64.b64encode(dict2json(report)),
                'pse_manifest':
                    pybitcointools.base64.b64encode(
                        pybitcointools.sha256(
                            'manifest destiny')),
                'nonce': most_recent_wait_certificate_id
            }

            attestation_verification_report = {
                'attestation_evidence_payload': attestation_evidence_payload,
                'anti_sybil_id': cls._anti_sybil_id
            }

            proof_data = {
                'attestation_verification_report':
                    attestation_verification_report,
                'signature':
                    pybitcointools.ecdsa_sign(
                        dict2json(attestation_verification_report),
                        cls._report_private_key)
            }

            return \
                EnclaveSignupInfo(
                    poet_public_key=signup_data['poet_public_key'],
                    proof_data=proof_data,
                    sealed_signup_data=sealed_signup_data)
Пример #39
0
def info(dic):
    if 'brain_wallet' in dic:
        privkey=pt.sha256(dic['brain_wallet'])
    else:
        privkey=dic['privkey']
    print('privkey: ' +str(privkey))
    user=pt.privtopub(privkey)
    if 'command' in dic:
        if dic['command']=='sell_bid':
            exchange.sell_bid(user, privkey, dic['bid_id'])
        if dic['command']=='buy_bid':
            exchange.buy_bid(user, privkey, dic['buy_currency'], dic['buy_amount'], dic['sell_currency'], dic['sell_amount'])
    out=empty_page
    a=''
    while a=='':
        a=exchange.user_data(user, privkey)
    print('a: ' +str(a))
    out=out.format('your user name: '+str(a['user'])+'<br>{}')
    out=out.format('bitcoin deposit address: '+str(exchange.deposit_address(user, privkey, 'bitcoin')['deposit_address'])+'<br>{}')
    if a['bitcoin'] != a['bitcoin_unconfirmed']:
        string=str(a['bitcoin'])+'/'+str(a['bitcoin_unconfirmed'])
    else:
        string=str(a['bitcoin'])
    out=out.format('bitcoin balance: '+string+'<br>{}')
    if a['bitcoin']>0:
        out=out.format(easyForm('/info', 'buy litecoin', '\
<input type="hidden" name="privkey" value="'+privkey+'">\
<input type="hidden" name="command" value="buy_bid">\
<input type="hidden" name="buy_currency" value="litecoin">\
<input type="hidden" name="sell_currency" value="bitcoin">\
<input type="text" name="buy_amount" value="buy this much litecoin">\
<input type="text" name="sell_amount" value="sell this much bitcoin">\
'))
        out=out.format(easyForm('/info', 'withdraw bitcoin', '\
<input type="hidden" name="privkey" value="'+privkey+'">\
<input type="hidden" name="command" value="withdraw">\
<input type="hidden" name="currency" value="bitcoin">\
<input type="text" name="to_address" value="to address">\
<input type="text" name="amount" value="amount">\
'))
    out=out.format('litecoin deposit address: '+str(exchange.deposit_address(user, privkey, 'litecoin')['deposit_address'])+'<br>{}')
    if a['litecoin'] != a['litecoin_unconfirmed']:
        string=str(a['litecoin'])+'/'+str(a['litecoin_unconfirmed'])
    else:
        string=str(a['litecoin'])
    out=out.format('litecoin balance: '+string+'<br>{}')
    if a['litecoin']>0:
        out=out.format(easyForm('/info', 'buy bitcoin', '\
<input type="hidden" name="privkey" value="'+privkey+'">\
<input type="hidden" name="command" value="buy_bid">\
<input type="hidden" name="buy_currency" value="bitcoin">\
<input type="hidden" name="sell_currency" value="litecoin">\
<input type="text" name="buy_amount" value="buy this much bitcoin">\
<input type="text" name="sell_amount" value="sell this much litecoin">\
'))
        out=out.format(easyForm('/info', 'withdraw litecoin', '\
<input type="hidden" name="privkey" value="'+privkey+'">\
<input type="hidden" name="command" value="withdraw">\
<input type="hidden" name="currency" value="litecoin">\
<input type="text" name="to_address" value="address to send to">\
<input type="text" name="amount" value="how much you want to send">\
'))
    out=out.format('<br>{}')
    if 'bids' in a:
        for i in a['bids']:
            out=out.format('bid_id: '+i['bid_id']+'<br>{}')
            out=out.format(easyForm('/info', 'undo bid and reclaim money', '<input type="hidden" name="command" value="sell_bid"><input type="hidden" name="bid_id" value="'+i['bid_id']+'"><input type="hidden" name="privkey" value="'+privkey+'">'))
            out=out.format('buy '+str(i['buy_amount'])+' of '+str(i['buy_currency'])+'<br>{}')
            out=out.format('sell '+str(i['sell_amount'])+' of '+str(i['sell_currency'])+'<br><br>{}')
    return out.format('')
Пример #40
0
 def setUp(self):
     self.brainwallet_string = 'Here is a brainwallet string for testing purposes'
     self.private_key = bc.sha256(self.brainwallet_string)
     self.private_key_wif = bc.encode_privkey(self.private_key, 'wif')
     self.addr = bc.privkey_to_address(self.private_key)
Пример #41
0
import blockchain, config, threading, gui, listener, os, subprocess, re
import pybitcointools as pt
my_privkey=pt.sha256(config.brain_wallet)
my_pubkey=pt.privtopub(my_privkey)

def kill_processes_using_ports(ports):
    popen = subprocess.Popen(['netstat', '-lpn'],
                             shell=False,
                             stdout=subprocess.PIPE)
    (data, err) = popen.communicate()
    pattern = "^tcp.*((?:{0})).* (?P<pid>[0-9]*)/.*$"
    pattern = pattern.format(')|(?:'.join(ports))
    prog = re.compile(pattern)
    for line in data.split('\n'):
        match = re.match(prog, line)
        if match:
            pid = match.group('pid')
            subprocess.Popen(['kill', '-9', pid])
try:
    kill_processes_using_ports([str(config.listen_port), str(config.gui_port)])
    kill_processes_using_ports([str(config.listen_port), str(config.gui_port)])
except:
    #so windows doesn't die
    pass
if __name__ == '__main__':
    #the first miner is for finding blocks. the second miner is for playing go and for talking to the network.
    todo=[[blockchain.mine, 
           (my_pubkey, ['http://localhost:'+str(config.listen_port)+'/info?{}'], config.hashes_till_check, '_miner')],
          [listener.main, (config.listen_port, )],
          [blockchain.mine, (my_pubkey, config.peers_list, 0)],
          [gui.main, (config.gui_port, config.brain_wallet)]
    def create_wait_certificate(cls, block_digest):
        with cls._lock:
            # If we don't have a PoET private key, then the enclave has not
            # been properly initialized (either by calling create_signup_info
            # or unseal_signup_data)
            if cls._poet_private_key is None:
                raise \
                    WaitCertificateError(
                        'Enclave must be initialized before attempting to '
                        'create a wait certificate')

            # Several criteria we need to be met before we can create a wait
            # certificate:
            # 1. We have an active timer
            # 2. The active timer has expired
            # 3. The active timer has not timed out
            if cls._active_wait_timer is None:
                raise \
                    WaitCertificateError(
                        'Enclave active wait timer has not been initialized')

            # HACK ALERT!!  HACK ALERT!!  HACK ALERT!!  HACK ALERT!!
            #
            # Today, without the genesis utility we cannot make these checks.
            # Once we have the genesis utility, this code needs to change to
            # Depend upon the timer not being expired or timed out.  The
            # Original specification requires this check.
            #
            # HACK ALERT!!  HACK ALERT!!  HACK ALERT!!  HACK ALERT!!
            #
            # if not cls._active_wait_timer.has_expired():
            #     raise \
            #         WaitCertificateError(
            #             'Cannot create wait certificate because timer has '
            #             'not expired')
            # if wait_timer.has_timed_out():
            #     raise \
            #         WaitCertificateError(
            #             'Cannot create wait certificate because timer '
            #             'has timed out')

            # Create a random nonce for the certificate.  For our "random"
            # nonce we will take the timer signature, concat that with the
            # current time, JSON-ize it and create a SHA-256 hash over it.
            # Probably not considered random by security professional
            # standards, but it is good enough for the simulator.
            random_string = \
                dict2json({
                    'wait_timer_signature': cls._active_wait_timer.signature,
                    'now': datetime.datetime.utcnow().isoformat()
                })
            nonce = pybitcointools.sha256(random_string)

            # First create a new enclave wait certificate using the data
            # provided and then sign the certificate with the PoET private key
            wait_certificate = \
                EnclaveWaitCertificate.wait_certificate_with_wait_timer(
                    wait_timer=cls._active_wait_timer,
                    nonce=nonce,
                    block_digest=block_digest)
            wait_certificate.signature = \
                pybitcointools.ecdsa_sign(
                    wait_certificate.serialize(),
                    cls._poet_private_key)

            # Now that we have created the certificate, we no longer have an
            # active timer
            cls._active_wait_timer = None

            return wait_certificate
Пример #43
0
import blockchain
import pybitcointools as pt
my_privkey=pt.sha256("0")
my_pubkey=pt.privtopub(my_privkey)
peers_list=['http://zycr7u4ykb7kox7p.onion/info?{}',
            'http://gpvn7naihr4jk6dd.onion/info?{}',
            'http://fnsxouwikizbpqtq.onion/info?{}']#add friends!!
if __name__ == '__main__':
    blockchain.mine(my_pubkey, peers_list)
#out=blockchain.peer_check_all(peers, state)
Пример #44
0
 def sign(self, key):
     rawhash = sha256(
         rlp.encode([self.nonce, self.to, self.value, self.fee, self.data]))
     self.v, self.r, self.s = ecdsa_raw_sign(rawhash, key)
     self.sender = bin_sha256(privtopub(key)[1:])[-20:]
     return self
    def verify_signup_info(cls,
                           signup_info,
                           originator_public_key,
                           validator_network_basename,
                           most_recent_wait_certificate_id):
        # Verify the attestation verification report signature
        attestation_verification_report = \
            signup_info.proof_data.get('attestation_verification_report')
        if attestation_verification_report is None:
            raise \
                SignupInfoError(
                    'Attestation verification report is missing from proof '
                    'data')

        if not pybitcointools.ecdsa_verify(
                dict2json(attestation_verification_report),
                signup_info.proof_data.get('signature'),
                cls._report_public_key):
            raise \
                SignupInfoError(
                    'Attestation verification report signature is invalid')

        # Verify the presence of the anti-Sybil ID
        anti_sybil_id = attestation_verification_report.get('anti_sybil_id')
        if anti_sybil_id is None:
            raise \
                SignupInfoError(
                    'Attestation verification report does not contain an '
                    'anti-Sybil ID')

        # Verify that the report data field in the report contains the SHA256
        # digest of the originator's public key SHA 256 digest and the PoET
        # public key.
        attestation_evidence_payload = \
            attestation_verification_report.get(
                'attestation_evidence_payload')
        if attestation_evidence_payload is None:
            raise \
                SignupInfoError(
                    'Attestation verification report does not contain '
                    'attestation evidence payload')

        enclave_quote = attestation_evidence_payload.get('enclave_quote')
        if enclave_quote is None:
            raise \
                SignupInfoError(
                    'Attestation evidence payload does not contain an '
                    'enclave quote')

        report = json2dict(pybitcointools.base64.b64decode(enclave_quote))
        report_data = report.get('report_data')
        if report_data is None:
            raise \
                SignupInfoError('Enclave quote does not contain report data')

        target_report_data = {
            'originator_public_key_hash':
                pybitcointools.sha256(
                    pybitcointools.encode_pubkey(
                        originator_public_key,
                        'hex')),
            'poet_public_key': signup_info.poet_public_key
        }
        target_report_data_digest = \
            pybitcointools.sha256(dict2json(target_report_data))

        if report_data != target_report_data_digest:
            raise SignupInfoError('Enclave quote report data is invalid')

        # Verify that the validator base name in the enclave quote report
        # matches the provided validator network basename
        validator_net_basename = report.get('validator_network_basename')
        if validator_net_basename is None:
            raise \
                SignupInfoError(
                    'Enclave quote report does not have a validator network '
                    'basename')

        if validator_net_basename != validator_network_basename:
            raise \
                SignupInfoError(
                    'Enclave quote report validator network basename [{0}] '
                    'does not match [{1}]'.format(
                        validator_net_basename,
                        validator_network_basename))
Пример #46
0
def info(dic):
    if 'brain_wallet' in dic:
        privkey=pt.sha256(dic['brain_wallet'])
    else:
        privkey=dic['privkey']
    print('privkey: ' +str(privkey))
    user=pt.privtopub(privkey)
    if 'command' in dic:
        if dic['command']=='sell_bid':
            exchange.sell_bid(user, privkey, dic['bid_id'])
        if dic['command']=='buy_bid':
            exchange.buy_bid(user, privkey, dic['buy_currency'], dic['buy_amount'], dic['sell_currency'], dic['sell_amount'])
    out=empty_page
    a=''
    while a=='':
        a=exchange.user_data(user, privkey)
    print('a: ' +str(a))
    out=out.format('your user name: '+str(a['user'])+'<br>{}')
    out=out.format('bitcoin deposit address: '+str(exchange.deposit_address(user, privkey, 'bitcoin')['deposit_address'])+'<br>{}')
    if a['bitcoin'] != a['bitcoin_unconfirmed']:
        string=str(a['bitcoin'])+'/'+str(a['bitcoin_unconfirmed'])
    else:
        string=str(a['bitcoin'])
    out=out.format('bitcoin balance: '+string+'<br>{}')
    if a['bitcoin']>0:
        out=out.format(easyForm('/info', 'buy litecoin', '\
<input type="hidden" name="privkey" value="'+privkey+'">\
<input type="hidden" name="command" value="buy_bid">\
<input type="hidden" name="buy_currency" value="litecoin">\
<input type="hidden" name="sell_currency" value="bitcoin">\
<input type="text" name="buy_amount" value="buy this much litecoin">\
<input type="text" name="sell_amount" value="sell this much bitcoin">\
'))
        out=out.format(easyForm('/info', 'withdraw bitcoin', '\
<input type="hidden" name="privkey" value="'+privkey+'">\
<input type="hidden" name="command" value="withdraw">\
<input type="hidden" name="currency" value="bitcoin">\
<input type="text" name="to_address" value="to address">\
<input type="text" name="amount" value="amount">\
'))
    out=out.format('litecoin deposit address: '+str(exchange.deposit_address(user, privkey, 'litecoin')['deposit_address'])+'<br>{}')
    if a['litecoin'] != a['litecoin_unconfirmed']:
        string=str(a['litecoin'])+'/'+str(a['litecoin_unconfirmed'])
    else:
        string=str(a['litecoin'])
    try:
        out=out.format('litecoin balance: '+string+'<br>{}')
    except:
        print('string: ' +str(string))
        print('out: '+str(out))
        error('here')
    if a['litecoin']>0:
        out=out.format(easyForm('/info', 'buy bitcoin', '\
<input type="hidden" name="privkey" value="'+privkey+'">\
<input type="hidden" name="command" value="buy_bid">\
<input type="hidden" name="buy_currency" value="bitcoin">\
<input type="hidden" name="sell_currency" value="litecoin">\
<input type="text" name="buy_amount" value="buy this much bitcoin">\
<input type="text" name="sell_amount" value="sell this much litecoin">\
'))
        out=out.format(easyForm('/info', 'withdraw litecoin', '\
<input type="hidden" name="privkey" value="'+privkey+'">\
<input type="hidden" name="command" value="withdraw">\
<input type="hidden" name="currency" value="litecoin">\
<input type="text" name="to_address" value="address to send to">\
<input type="text" name="amount" value="how much you want to send">\
'))
    out=out.format('<br>{}')
    if 'bids' in a:
        for i in a['bids']:
            out=out.format('bid_id: '+i['bid_id']+'<br>{}')
            out=out.format(easyForm('/info', 'undo bid and reclaim money', '<input type="hidden" name="command" value="sell_bid"><input type="hidden" name="bid_id" value="'+i['bid_id']+'"><input type="hidden" name="privkey" value="'+privkey+'">'))
            out=out.format('buy '+str(i['buy_amount'])+' of '+str(i['buy_currency'])+'<br>{}')
            out=out.format('sell '+str(i['sell_amount'])+' of '+str(i['sell_currency'])+'<br><br>{}')
    return out.format('')