def test_register_validator_key_mismatch(self): key = signed_object.generate_signing_key() public_key_hash = \ hashlib.sha256( pybitcointools.encode_pubkey( pybitcointools.privtopub(key), 'hex')).hexdigest() key2 = signed_object.generate_signing_key() validator_id = signed_object.generate_identifier(key) name = 'DasValidator' signup_info = \ SignupInfo.create_signup_info( originator_public_key_hash=public_key_hash, most_recent_wait_certificate_id='0' * 16) store = ObjectStore() transaction = \ ValidatorRegistryTransaction.register_validator( name, validator_id, signup_info) transaction.sign_object(key2) with self.assertRaises(InvalidTransactionError): transaction.check_valid(store) self.fail("Failure: Verified an invalid transaction")
def test_register_validator_re_register(self): key = signed_object.generate_signing_key() validator_id = signed_object.generate_identifier(key) name = 'DasValidator' signup_info = \ SignupInfo.create_signup_info( originator_public_key=pybitcointools.privtopub(key), validator_network_basename='Intel Validator Network', most_recent_wait_certificate_id='0' * 16) store = KeyValueStore() transaction = \ ValidatorRegistryTransaction.register_validator( name, validator_id, signup_info) transaction.sign_object(key) try: transaction.check_valid(store) transaction.apply(store) except InvalidTransactionError as e: self.fail('Failed valid transaction: {}'.format(e)) try: # check if valid to register again transaction.check_valid(store) except InvalidTransactionError as e: self.fail('Failure: Double registered validator: {}'.format(e))
def test_register_permissioned_validator_invalid(self): signing_key = signed_object.generate_signing_key() unpermissiond_private_key = signed_object.generate_signing_key() pub_key = pybitcointools.encode_pubkey( pybitcointools.privtopub(unpermissiond_private_key), 'hex') permissioned_public_keys = [pub_key] addr = signed_object.generate_identifier(unpermissiond_private_key) permissioned_addrs = [addr] update = { 'whitelist_name': "hyperledger.sawtooth-core.genesis-whitelist", 'verb': 'reg', 'permissioned_public_keys': permissioned_public_keys, 'permissioned_addrs': permissioned_addrs } minfo = {'Update': update} transaction = PermissionedValidatorRegistryTransaction(minfo) transaction.sign_object(signing_key) store = ObjectStore() with self.assertRaises(InvalidTransactionError): transaction.check_valid(store) self.fail("Failure: Verified an invalid transaction")
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
def test_register_validator_re_register(self): key = signed_object.generate_signing_key() public_key_hash = \ hashlib.sha256( pybitcointools.encode_pubkey( pybitcointools.privtopub(key), 'hex')).hexdigest() validator_id = signed_object.generate_identifier(key) name = 'DasValidator' signup_info = \ SignupInfo.create_signup_info( originator_public_key_hash=public_key_hash, most_recent_wait_certificate_id='0' * 16) store = ObjectStore() transaction = \ ValidatorRegistryTransaction.register_validator( name, validator_id, signup_info) transaction.sign_object(key) try: transaction.check_valid(store) transaction.apply(store) except InvalidTransactionError as e: self.fail('Failed valid transaction: {}'.format(e)) try: # check if valid to register again transaction.check_valid(store) except InvalidTransactionError as e: self.fail('Failure: Double registered validator: {}'.format(e))
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
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)
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
def generate_identifier(signingkey): """Generates encoded version of the public key associated with signingkey. Args: signingkey (str): A private key. Returns: str: An encoded 'address' associated with the public key. """ return pybitcointools.pubtoaddr(pybitcointools.privtopub(signingkey))
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 __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_register_permissioned_validator_valid(self): signing_key = signed_object.generate_signing_key() try: priv_key1 = pybitcointools.decode_privkey( open('./tests/unit/keys/pv1.wif', "r") .read().strip(), 'wif') priv_key2 = pybitcointools.decode_privkey( open('./tests/unit/keys/pv2.wif', "r") .read().strip(), 'wif') except IOError as ex: raise Exception('IOError: {}'.format(str(ex))) pub_key1 = pybitcointools.encode_pubkey( pybitcointools.privtopub(priv_key1), 'hex') pub_key2 = pybitcointools.encode_pubkey( pybitcointools.privtopub(priv_key2), 'hex') permissioned_public_keys = [pub_key1, pub_key2] addr1 = signed_object.generate_identifier(priv_key1) addr2 = signed_object.generate_identifier(priv_key2) permissioned_addrs = [addr1, addr2] update = { 'whitelist_name': "hyperledger.sawtooth-core.genesis-whitelist", 'verb': 'reg', 'permissioned_public_keys': permissioned_public_keys, 'permissioned_addrs': permissioned_addrs } minfo = {'Update': update} transaction = PermissionedValidatorRegistryTransaction(minfo) transaction.sign_object(signing_key) store = ObjectStore() try: transaction.check_valid(store) transaction.apply(store) except InvalidTransactionError as e: self.fail('Failed valid transaction: {}'.format(e))
def test_register_permissioned_validator_valid(self): signing_key = signed_object.generate_signing_key() try: priv_key1 = pybitcointools.decode_privkey( open('./tests/unit/keys/pv1.wif', "r").read().strip(), 'wif') priv_key2 = pybitcointools.decode_privkey( open('./tests/unit/keys/pv2.wif', "r").read().strip(), 'wif') except IOError as ex: raise Exception('IOError: {}'.format(str(ex))) pub_key1 = pybitcointools.encode_pubkey( pybitcointools.privtopub(priv_key1), 'hex') pub_key2 = pybitcointools.encode_pubkey( pybitcointools.privtopub(priv_key2), 'hex') permissioned_public_keys = [pub_key1, pub_key2] addr1 = signed_object.generate_identifier(priv_key1) addr2 = signed_object.generate_identifier(priv_key2) permissioned_addrs = [addr1, addr2] update = { 'whitelist_name': "hyperledger.sawtooth-core.genesis-whitelist", 'verb': 'reg', 'permissioned_public_keys': permissioned_public_keys, 'permissioned_addrs': permissioned_addrs } minfo = {'Update': update} transaction = PermissionedValidatorRegistryTransaction(minfo) transaction.sign_object(signing_key) store = ObjectStore() try: transaction.check_valid(store) transaction.apply(store) except InvalidTransactionError as e: self.fail('Failed valid transaction: {}'.format(e))
def board(out, state, game, privkey): board=state[game] s=board['size'] pubkey=pt.privtopub(privkey) if board['whos_turn']=='white': whos_turn_pubkey=board['pubkey_white'] not_whos_turn_pubkey=board['pubkey_black'] else: whos_turn_pubkey=board['pubkey_black'] not_whos_turn_pubkey=board['pubkey_white'] for j in range(s): out=out.format('<br>{}') for i in range(s): out=out.format(board_spot(j, i, not_whos_turn_pubkey, whos_turn_pubkey, pubkey, board, privkey)) return out
def test_compressed_keys(self): """ Tests compressed key """ msg = 'foo' priv = pbt.encode_privkey(pbt.random_key(), 'hex_compressed') sig = pbt.ecdsa_sign(msg, priv) # Force old pybitcointools to behave v, r, s = pbt.decode_sig(sig) if v < 31: v += 4 sig = pbt.encode_sig(v, r, s) pub = pbt.compress(pbt.privtopub(priv)) native_recovered = pbct_nativerecover.recover_pubkey(msg, sig) self.assertEquals(native_recovered, pub, "Priv Key that failed: {}".format(priv))
def board(out, state, game, privkey): board = state[game] s = board['size'] pubkey = pt.privtopub(privkey) if board['whos_turn'] == 'white': whos_turn_pubkey = board['pubkey_white'] not_whos_turn_pubkey = board['pubkey_black'] else: whos_turn_pubkey = board['pubkey_black'] not_whos_turn_pubkey = board['pubkey_white'] for j in range(s): out = out.format('<br>{}') for i in range(s): out = out.format( board_spot(j, i, not_whos_turn_pubkey, whos_turn_pubkey, pubkey, board, privkey)) return out
def test_compressed_keys(self): """ Tests compressed key """ msg = 'foo' self.longMessage = True priv = pbt.encode_privkey(pbt.random_key(), 'hex_compressed') sig = pbt.ecdsa_sign(msg, priv) # Force old pybitcointools to behave v, r, s = pbt.decode_sig(sig) if v < 31: v += 4 sig = pbt.encode_sig(v, r, s) pub = pbt.compress(pbt.privtopub(priv)) native_recovered = gossip.signed_object.get_verifying_key(msg, sig) self.assertEquals(native_recovered, pub, "Priv Key that failed: {}".format(priv))
def board(out, state, game, privkey): # state=copy.deepcopy(state) # transactions=blockchain.load_transactions() # a=blockchain.verify_transactions(transactions, state) # if a['bool']: # state=a['newstate'] # else: # pass # print('ERROR') # print('state: ' +str(state)) board = state[game] s = board["size"] """ transactions=filter(lambda x: x['game_name']==board['game_name'], transactions) black_tx=filter(lambda x: x['id']==board['pubkey_black'], transactions) white_tx=filter(lambda x: x['id']==board['pubkey_white'], transactions) black_txs=[] white_txs=[] print('black: ' +str(black_tx)) for i in black_tx: if 'where' in i: black_txs.append(i['where']) else: out=out.format('<p>You are attempting to win this game</p>{}') for i in white_tx: if 'where' in i: white_txs.append(i['where']) else: out=out.format('<p>You are attempting to win this game</p>{}') """ pubkey = pt.privtopub(privkey) # instead of putting more stones on the board, we should be trying to calculate what the next board will look like. if board["whos_turn"] == "white": whos_turn_pubkey = board["pubkey_white"] not_whos_turn_pubkey = board["pubkey_black"] else: whos_turn_pubkey = board["pubkey_black"] not_whos_turn_pubkey = board["pubkey_white"] for j in range(s): out = out.format("<br>{}") for i in range(s): # out=out.format(board_spot(j, i, moves_played, not_whos_turn_pubkey, whos_turn_pubkey, pubkey, board, white_txs, black_txs, privkey)) out = out.format(board_spot(j, i, not_whos_turn_pubkey, whos_turn_pubkey, pubkey, board, privkey)) return out
def __init__(self, base_url, store_name=None, name='SawtoothClient', txntype_name=None, msgtype_name=None, keystring=None, keyfile=None, disable_client_validation=False): self._base_url = base_url self._message_type = msgtype_name self._transaction_type = txntype_name # an explicit store name takes precedence over a store name # implied by the transaction type self._store_name = None if store_name is not None: self._store_name = store_name.strip('/') elif txntype_name is not None: self._store_name = txntype_name.strip('/') self._communication = _Communication(base_url) self._last_transaction = None self._signing_key = None self._identifier = None self._update_batch = None self._disable_client_validation = disable_client_validation if keystring: LOGGER.debug("set signing key from string\n%s", keystring) self._signing_key = pybitcointools.decode_privkey(keystring, 'wif') elif keyfile: LOGGER.debug("set signing key from file %s", keyfile) try: self._signing_key = pybitcointools.decode_privkey( open(keyfile, "r").read().strip(), 'wif') except IOError as ex: raise ClientException("Failed to load key file: {}".format( str(ex))) if self._signing_key is not None: self._identifier = pybitcointools.pubtoaddr( pybitcointools.privtopub(self._signing_key))
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 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)
def GenerateKeys(numKeys = 10): keysGenerated = 0 totalCandidates = 0 out=[] while keysGenerated < numKeys: try: cand = Candidate() t = '%s?' % cand candHash = hashlib.sha256(t).digest() if candHash[0] == '\x00': privateKey = GetPrivateKey(cand) if CheckShortKey(cand): out.append({'mini':cand, 'priv':privateKey, 'pub':pt.privtopub(privateKey)}) else: print('Invalid!') keysGenerated += 1 totalCandidates += 1 except KeyboardInterrupt: break return out
def easy_add_transaction(tx_orig, sign_over, privkey): state=state_library.current_state() pubkey=pt.privtopub(privkey) if pubkey not in state or 'count' not in state[pubkey]: my_count=1 else: my_count=state[pubkey]['count'] txs=blockchain.load_transactions() my_txs=filter(lambda x: x['id']==pubkey, txs) tx=copy.deepcopy(tx_orig) tx['count']=len(my_txs)+my_count tx['signature']=pt.ecdsa_sign(blockchain.message2signObject(tx, sign_over), privkey) print(blockchain.add_transaction(tx)) if 'move_number' in tx: for i in range(10): tx['move_number']+=1 tx['signature']=pt.ecdsa_sign(blockchain.message2signObject(tx, sign_over), privkey) print(blockchain.add_transaction(tx)) print('tx: ' +str(tx)) blockchain.pushtx(tx, config.peers_list)
def easy_add_transaction(tx_orig, sign_over, privkey): state = state_library.current_state() pubkey = pt.privtopub(privkey) if pubkey not in state or "count" not in state[pubkey]: my_count = 1 else: my_count = state[pubkey]["count"] txs = blockchain.load_transactions() my_txs = filter(lambda x: x["id"] == pubkey, txs) tx = copy.deepcopy(tx_orig) tx["count"] = len(my_txs) + my_count tx["signature"] = pt.ecdsa_sign(blockchain.message2signObject(tx, sign_over), privkey) print (blockchain.add_transaction(tx)) if "move_number" in tx: for i in range(10): tx["move_number"] += 1 tx["signature"] = pt.ecdsa_sign(blockchain.message2signObject(tx, sign_over), privkey) print (blockchain.add_transaction(tx)) print ("tx: " + str(tx)) blockchain.pushtx(tx, quick_mine.peers_list)
def test_register_validator_key_mismatch(self): key = signed_object.generate_signing_key() key2 = signed_object.generate_signing_key() validator_id = signed_object.generate_identifier(key) name = 'DasValidator' signup_info = \ SignupInfo.create_signup_info( originator_public_key=pybitcointools.privtopub(key), validator_network_basename='Intel Validator Network', most_recent_wait_certificate_id='0' * 16) store = KeyValueStore() transaction = \ ValidatorRegistryTransaction.register_validator( name, validator_id, signup_info) transaction.sign_object(key2) with self.assertRaises(InvalidTransactionError): transaction.check_valid(store) self.fail("Failure: Verified an invalid transaction")
def easy_add_transaction(tx_orig, sign_over, privkey, state): tx=copy.deepcopy(tx_orig) pubkey=pt.privtopub(privkey) if pubkey not in state or 'count' not in state[pubkey]: tx['count']=1 else: tx['count']=state[pubkey]['count'] txs=blockchain.load_transactions() my_txs=filter(lambda x: x['id']==pubkey, txs) tx['signature']=pt.ecdsa_sign(blockchain.message2signObject(tx, sign_over), privkey) if blockchain.add_transaction(tx): blockchain.pushtx(tx, config.peers_list) return True if 'move_number' in tx: for i in range(10): tx['move_number']+=1 tx['signature']=pt.ecdsa_sign(blockchain.message2signObject(tx, sign_over), privkey) if blockchain.add_transaction(tx): blockchain.pushtx(tx, config.peers_list) return True print('SOMETHING IS BROKEN') return False
def easy_add_transaction(tx_orig, sign_over, privkey, state): tx = copy.deepcopy(tx_orig) pubkey = pt.privtopub(privkey) if pubkey not in state or 'count' not in state[pubkey]: tx['count'] = 1 else: tx['count'] = state[pubkey]['count'] txs = blockchain.load_transactions() my_txs = filter(lambda x: x['id'] == pubkey, txs) tx['signature'] = pt.ecdsa_sign(go.message2signObject(tx, sign_over), privkey) if blockchain.add_transaction(tx): blockchain.pushtx(tx, config.peers_list) return True if 'move_number' in tx: for i in range(10): tx['move_number'] += 1 tx['signature'] = pt.ecdsa_sign( go.message2signObject(tx, sign_over), privkey) if blockchain.add_transaction(tx): blockchain.pushtx(tx, config.peers_list) return True print('SOMETHING IS BROKEN') return False
def GenerateKeys(numKeys=10): keysGenerated = 0 totalCandidates = 0 out = [] while keysGenerated < numKeys: try: cand = Candidate() t = '%s?' % cand candHash = hashlib.sha256(t).digest() if candHash[0] == '\x00': privateKey = GetPrivateKey(cand) if CheckShortKey(cand): out.append({ 'mini': cand, 'priv': privateKey, 'pub': pt.privtopub(privateKey) }) else: print('Invalid!') keysGenerated += 1 totalCandidates += 1 except KeyboardInterrupt: break return out
def warp(passphrase, salt=""): s1 = _scrypt(passphrase, salt="") s2 = _pbkdf2(passphrase, salt="") key = binascii.hexlify(xor(s1, s2)) return key, bitcoin.pubtoaddr(bitcoin.privtopub(key))
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
# 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 ' ' print 'pubkey1' print ' ' + repr(pubkey1)
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
def get_pub_key(private_key): return pybitcointools.privtopub(private_key)
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
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 pair(complexity=512): se = hashlib.sha256(os.urandom(complexity)).hexdigest() priv = privateKeyToWif(se) pub = pybitcointools.privtopub(priv) addr = pybitcointools.pubtoaddr(pub) return priv, pub, addr
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)
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'))
def _create_random_public_key(cls): return pybitcointools.privtopub(cls._create_random_private_key())
def signing_address(self): return pybitcointools.pubtoaddr( pybitcointools.privtopub(self.SigningKey))
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('')
class _PoetEnclaveSimulator(object): # A lock to protect threaded access _lock = threading.Lock() # The WIF-encoded enclave private seal key. From it, we will create # private and public keys we can use for sealing and unsealing signup # info. __SEAL_PRIVATE_KEY_WIF = \ '5KYsbooGBg51Gohakgq45enpXvCXmEBed1JivFfUZskmjLegHBG' _seal_private_key = \ pybitcointools.decode_privkey(__SEAL_PRIVATE_KEY_WIF, 'wif') _seal_public_key = pybitcointools.privtopub(_seal_private_key) # The WIF-encoded private report key. From it, we will create private # key we can use for signing attestation verification reports. __REPORT_PRIVATE_KEY_WIF = \ '5Jz5Kaiy3kCiHE537uXcQnJuiNJshf2bZZn43CrALMGoCd3zRuo' _report_private_key = \ pybitcointools.decode_privkey(__REPORT_PRIVATE_KEY_WIF, 'wif') _report_public_key = pybitcointools.privtopub(_report_private_key) # Minimum duration for PoET 1 simulator is 30 seconds __MINIMUM_DURATTION = 30.0 # The anti-sybil ID for this particular validator. This will get set when # the enclave is initialized _anti_sybil_id = None # The PoET keys will remain unset until signup info is either created or # unsealed _poet_public_key = None _poet_private_key = None _active_wait_timer = None @classmethod 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')) @classmethod 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) @classmethod def deserialize_signup_info(cls, serialized_signup_info): return \ EnclaveSignupInfo.signup_info_from_serialized( serialized_signup_info=serialized_signup_info) @classmethod def unseal_signup_data(cls, sealed_signup_data): """ Args: sealed_signup_data: Sealed signup data that was returned previously in a EnclaveSignupInfo object from a call to create_signup_info Returns: A string The hex encoded PoET public key that was extracted from the sealed data """ # Reverse the process we used in creating "sealed" signup info. # Specifically, we will do a base 32 decode, which gives us json # we can convert back to a dictionary we can use to get the # data we need signup_data = \ json2dict(pybitcointools.base64.b32decode(sealed_signup_data)) with cls._lock: cls._poet_public_key = \ pybitcointools.decode_pubkey( signup_data.get('poet_public_key'), 'hex') cls._poet_private_key = \ pybitcointools.decode_privkey( signup_data.get('poet_public_key'), 'hex') cls._active_wait_timer = None return signup_data.get('poet_public_key') @classmethod 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)) # NOTE - this check is currently not performed as a transaction # does not have a good way to obtaining the most recent # wait certificate ID. # # Verify that the wait certificate ID in the attestation evidence # payload matches the provided wait certificate ID. The wait # certificate ID is stored in the AEP nonce field. # nonce = attestation_evidence_payload.get('nonce') # if nonce is None: # raise \ # SignupInfoError( # 'Attestation evidence payload does not have a nonce') # # if nonce != most_recent_wait_certificate_id: # raise \ # SignupInfoError( # 'Attestation evidence payload nonce {0} does not match ' # 'most-recently-committed wait certificate ID {1}'.format( # nonce, # most_recent_wait_certificate_id)) @classmethod def create_wait_timer(cls, previous_certificate_id, local_mean): 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 \ WaitTimerError( 'Enclave must be initialized before attempting to ' 'create a wait timer') # Create some value from the cert ID. We are just going to use # the seal key to sign the cert ID. We will then use the # low-order 64 bits to change that to a number [0, 1] tag = \ pybitcointools.base64.b64decode( pybitcointools.ecdsa_sign( previous_certificate_id, cls._seal_private_key)) tagd = float(struct.unpack('L', tag[-8:])[0]) / (2**64 - 1) # Now compute the duration duration = cls.__MINIMUM_DURATTION - local_mean * math.log(tagd) # Create and sign the wait timer wait_timer = \ EnclaveWaitTimer( duration=duration, previous_certificate_id=previous_certificate_id, local_mean=local_mean) wait_timer.signature = \ pybitcointools.ecdsa_sign( wait_timer.serialize(), cls._poet_private_key) # Keep track of the active wait timer cls._active_wait_timer = wait_timer return wait_timer @classmethod def deserialize_wait_timer(cls, serialized_timer, signature): with cls._lock: # Verify the signature before trying to deserialize if not pybitcointools.ecdsa_verify( serialized_timer, signature, cls._poet_public_key): return None return \ EnclaveWaitTimer.wait_timer_from_serialized( serialized_timer=serialized_timer, signature=signature) @classmethod 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 @classmethod def deserialize_wait_certificate(cls, serialized_certificate, signature): return \ EnclaveWaitCertificate.wait_certificate_from_serialized( serialized_certificate=serialized_certificate, signature=signature) @classmethod def verify_wait_certificate(cls, certificate, encoded_poet_public_key): # poet_public_key = \ # pybitcointools.decode_pubkey(encoded_poet_public_key, 'hex') # # return \ # pybitcointools.ecdsa_verify( # certificate.serialize(), # certificate.signature, # poet_public_key) return True
def generate_pubkey(privkey): return pybitcointools.privtopub(privkey)
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('')
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
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,
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 public_key(self): return pybitcointools.privtopub(self.SigningKey)
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
class _PoetEnclaveSimulator(object): # The WIF-encoded enclave private seal key. From it, we will create # private and public keys we can use for sealing and unsealing signup # info. __SEAL_PRIVATE_KEY_WIF = \ '5KYsbooGBg51Gohakgq45enpXvCXmEBed1JivFfUZskmjLegHBG' _seal_private_key = \ pybitcointools.decode_privkey(__SEAL_PRIVATE_KEY_WIF, 'wif') _seal_public_key = pybitcointools.privtopub(_seal_private_key) # Minimum duration for PoET 1 simulator is 30 seconds __MINIMUM_DURATTION = 30.0 # The PoET keys will remain unset until signup info is either created or # unsealed _poet_public_key = None _poet_private_key = None _active_wait_timer = None @classmethod 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) @classmethod def unseal_signup_data(cls, sealed_signup_data): """ Args: sealed_signup_data: Sealed signup data that was returned previously in a EnclaveSignupInfo object from a call to create_signup_info Returns: A string The hex encoded PoET public key that was extracted from the sealed data """ # Reverse the process we used in creating "sealed" signup info. # Specifically, we will do a base 32 decode, which gives us json # we can convert back to a dictionary we can use to get the # data we need signup_data = \ json2dict(pybitcointools.base64.b32decode(sealed_signup_data)) cls._poet_public_key = \ pybitcointools.decode_pubkey( signup_data.get('poet_public_key'), 'hex') cls._poet_private_key = \ pybitcointools.decode_privkey( signup_data.get('poet_public_key'), 'hex') cls._active_wait_timer = None return signup_data.get('poet_public_key') @classmethod def verify_signup_info(cls, serialized_signup_info): # For now, we are going to always indicate that the signup information # is valid return True @classmethod def create_wait_timer(cls, previous_certificate_id, local_mean): # Create some value from the cert ID. We are just going to use # the seal key to sign the cert ID. We will then use the low-order # 64 bits to change that to a number [0, 1] tag = \ pybitcointools.base64.b64decode( pybitcointools.ecdsa_sign( previous_certificate_id, cls._seal_private_key)) tagd = float(struct.unpack('L', tag[-8:])[0]) / (2**64 - 1) # Now compute the duration duration = cls.__MINIMUM_DURATTION - local_mean * math.log(tagd) # Create and sign the wait timer wait_timer = \ EnclaveWaitTimer( duration=duration, previous_certificate_id=previous_certificate_id, local_mean=local_mean) wait_timer.signature = \ pybitcointools.ecdsa_sign( wait_timer.serialize(), cls._poet_private_key) # Keep track of the active wait timer cls._active_wait_timer = wait_timer return wait_timer @classmethod def deserialize_wait_timer(cls, serialized_timer, signature): return \ EnclaveWaitTimer.wait_timer_from_serialized( serialized_timer=serialized_timer, signature=signature) @classmethod def create_wait_certificate(cls, timer, block_digest): # TO DO - implement PoET 1 create certificate logic # 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_timer( timer=timer, block_digest=block_digest) wait_certificate.signature = \ pybitcointools.ecdsa_sign( wait_certificate.serialize(), cls._poet_private_key) return wait_certificate @classmethod def deserialize_wait_certificate(cls, serialized_certificate, signature): return \ EnclaveWaitCertificate.wait_certificate_from_serialized( serialized_certificate=serialized_certificate, signature=signature) @classmethod def verify_wait_certificate(cls, certificate, encoded_poet_public_key): # poet_public_key = \ # pybitcointools.decode_pubkey(encoded_poet_public_key, 'hex') # # TO DO - implement PoET 1 create certificate logic # return \ # pybitcointools.ecdsa_verify( # certificate.serialize(), # certificate.signature, # poet_public_key) return True