Exemple #1
0
def add_hash_to_blockchain():
    # Reference hash: shasum -a 256 database/data.csv
    print("Hash: " + str(hash_sha256))

    # Put sha256 hash into bitcoin-tools
    private_key = BitcoinPrivateKey(hash_sha256)
    public_key = private_key.public_key()

    # Get address
    addr = public_key.address()
    print("Address: " + addr)

    # Get API keys
    with open(identifier_file, "r") as identifier_file_open:
        identifier = identifier_file_open.readline().rstrip('\n')

    with open(password_file, "r") as password_file_open:
        password = password_file_open.readline().rstrip('\n')

    # print("API Identifier: " + identifier)
    # print("API Password: "******"Payment TX: " + str(payment.tx_hash))
Exemple #2
0
def validate_public_against_py_bitcoin(private_key_hex,
                                       public_address_uncompressed,
                                       compressed=True):
    private_key_pybitcoin = BitcoinPrivateKey(private_key_hex, compressed)
    if private_key_pybitcoin.public_key().address(
    ) == public_address_uncompressed:
        return True
Exemple #3
0
    def generate_address(self, force=False):
        if self.address and not force:
            return

        if not settings.ARTIST_DONATE_ADDRESS_SOURCE:
            # No donate address has been given in settings
            # this means we generate a unique one and store the private key
            # along with it. It is the responsibility of the maintainer
            # if this installation to make sure the private key is distributed
            # to the artist.

            priv = BitcoinPrivateKey()
            self.private_key_hex = priv.to_hex()
            self.address = priv.public_key().address()
            self.save()
        else:
            # point to another installation of TheStation to get the correct
            # donate address.
            url = (
                "http://" + settings.ARTIST_DONATE_ADDRESS_SOURCE +
                "/get_artist_donate_address" +
                "?artist=%s" % self.name
            )
            self.address = requests.get(url).json()['donate_address']
            self.save()

        return self.address
class AuthRequestTest(unittest.TestCase):
    def setUp(self):
        self.private_key_hex = 'a5c61c6ca7b3e7e55edee68566aeab22e4da26baa285c7bd10e8d2218aa3b22901'
        self.public_key_hex = '027d28f9951ce46538951e3697c62588a87f1f1f295de4a14fdd4c780fc52cfe69'
        self.domain = 'onename.com'
        self.permissions = ['blockchainid']
        self.private_key = BitcoinPrivateKey(self.private_key_hex, compressed=True)
        self.sample_encoded_token = 'eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3N1ZWRBdCI6IjE0NDA3MTM0MTQuMTkiLCJjaGFsbGVuZ2UiOiIxZDc4NTBkNy01YmNmLTQ3ZDAtYTgxYy1jMDA4NTc5NzY1NDQiLCJwZXJtaXNzaW9ucyI6WyJibG9ja2NoYWluaWQiXSwiaXNzdWVyIjp7InB1YmxpY0tleSI6IjAzODI3YjZhMzRjZWJlZTZkYjEwZDEzNzg3ODQ2ZGVlYWMxMDIzYWNiODNhN2I4NjZlMTkyZmEzNmI5MTkwNjNlNCIsImRvbWFpbiI6Im9uZW5hbWUuY29tIn19.96Q_O_4DX8uPy1enosEwS2sIcyVelWhxvfj2F8rOvHldhqt9YRYilauepb95DVnmpqpCXxJb7jurT8auNCbptw'
        self.sample_decoded_token_payload = {"issuedAt": "1440713414.19", "challenge": "1d7850d7-5bcf-47d0-a81c-c00857976544", "issuer": {"publicKey": "03827b6a34cebee6db10d13787846deeac1023acb83a7b866e192fa36b919063e4", "domain": "onename.com"}, "permissions": ["blockchainid"]}
        self.resolver = OnenameAPIResolver(ONENAME_APP_ID, ONENAME_APP_SECRET)

    def tearDown(self):
        pass

    def test_auth_request_token_encoding(self):
        auth_request = AuthRequest(
            self.private_key.to_pem(), self.private_key.public_key().to_hex(),
            self.domain, self.permissions)
        auth_request_token = auth_request.token()

        is_valid_token = AuthRequest.verify(auth_request_token, self.resolver)
        self.assertTrue(is_valid_token)

    def test_auth_request_token_decoding(self):
        decoded_token = AuthRequest.decode(self.sample_encoded_token)
        decoded_token_payload = decoded_token['payload']
        self.assertEqual(decoded_token_payload, self.sample_decoded_token_payload)
Exemple #5
0
class TokeningTests(unittest.TestCase):
    def setUp(self):
        self.master_private_key = BitcoinPrivateKey()

    def tearDown(self):
        pass

    def test_basic_tokening(self):
        profile_components = [{
            "name": "Naval Ravikant"
        }, {
            "birthDate": "1980-01-01"
        }]
        reference_profile = {
            "name": "Naval Ravikant",
            "birthDate": "1980-01-01"
        }
        # tokenize the profile
        profile_token_records = sign_profile_tokens(
            profile_components, self.master_private_key.to_hex())
        print json.dumps(profile_token_records, indent=2)
        self.assertTrue(isinstance(profile_token_records, list))
        # recover the profile
        profile = get_profile_from_tokens(
            profile_token_records,
            self.master_private_key.public_key().to_hex())
        print json.dumps(profile, indent=2)
        self.assertTrue(isinstance(profile, object))
        self.assertEqual(profile, reference_profile)
    def __init__(self,
                 private_key,
                 profile=None,
                 username=None,
                 expires_after=None,
                 crypto_backend=default_backend()):
        """ private_key should be provided in HEX, WIF or binary format 
            profile should be a dictionary
            username should be a string
            expires_after should be a float number of seconds
        """
        if not private_key:
            raise ValueError('Private key is missing')

        if not profile:
            profile = {}

        if not expires_after:
            expires_after = 30 * 24 * 3600  # next month

        self.private_key = private_key
        self.public_key = BitcoinPrivateKey(self.private_key).public_key()
        self.address = self.public_key.address()
        self.profile = profile
        self.username = username
        self.expires_after = expires_after
        self.tokenizer = Tokenizer(crypto_backend=crypto_backend)
Exemple #7
0
def generate_bitcoin_keypairs(number_of_addresses=50):
    """ This function:
        1) generates new bitcoin keypairs
        2) saves encrypted private keys
        private keys are encrypted with SECRET_KEY
    """

    if registrar_addresses.find().count() >= number_of_addresses:
        log.debug("Already have enough addresses")
        return

    no_of_new_addresses = number_of_addresses - registrar_addresses.find().count()

    for count in range(1, no_of_new_addresses + 1):

        privkey = BitcoinPrivateKey()
        hex_privkey = privkey.to_hex()
        encrypted_privkey = aes_encrypt(hex_privkey, SECRET_KEY)

        address = get_address_from_privkey(hex_privkey)
        log.debug("Creating new address (count, address): (%s, %s):" % (count, address))

        new_entry = {}
        new_entry['encrypted_privkey'] = encrypted_privkey
        new_entry['address'] = address

        registrar_addresses.save(new_entry)
Exemple #8
0
def generate_bitcoin_keypairs(number_of_addresses=50):
    """ This function:
        1) generates new bitcoin keypairs
        2) saves encrypted private keys
        private keys are encrypted with SECRET_KEY
    """

    if registrar_addresses.find().count() >= number_of_addresses:
        log.debug("Already have enough addresses")
        return

    no_of_new_addresses = number_of_addresses - registrar_addresses.find().count()

    for count in range(1, no_of_new_addresses + 1):

        privkey = BitcoinPrivateKey()
        hex_privkey = privkey.to_hex()
        encrypted_privkey = aes_encrypt(hex_privkey, SECRET_KEY)

        address = get_address_from_privkey(hex_privkey)
        log.debug("Creating new address (count, address): (%s, %s):" % (count, address))

        new_entry = {}
        new_entry['encrypted_privkey'] = encrypted_privkey
        new_entry['address'] = address

        registrar_addresses.save(new_entry)
Exemple #9
0
def add_migration_user(username, profile):

    check_entry = migration_users.find_one({"username": username})

    if check_entry is not None:
        print "already in migration DB"
        return

    new_entry = {}
    new_entry['username'] = username
    new_entry['profile'] = profile
    new_entry['profile_hash'] = get_hash(profile)
    privkey = BitcoinPrivateKey()
    hex_privkey = privkey.to_hex()
    new_entry['encrypted_privkey'] = aes_encrypt(hex_privkey, SECRET_KEY)

    #hex_privkey_test = aes_decrypt(new_entry['encrypted_privkey'], SECRET_KEY)
    #print hex_privkey
    #print hex_privkey_test

    nmc_address, btc_address = get_addresses_from_privkey(hex_privkey)

    new_entry['nmc_address'] = nmc_address
    new_entry['btc_address'] = btc_address
    print new_entry

    migration_users.save(new_entry)
def get_address_from_privkey(hex_privkey):
    """ get bitcoin address from private key
    """

    privkey = BitcoinPrivateKey(hex_privkey)

    pubkey = privkey.public_key()
    return pubkey.address()
Exemple #11
0
def get_addresses_from_privkey(hex_privkey):
    """ get both bitcoin and namecoin addresses
    """

    btc_privkey = BitcoinPrivateKey(hex_privkey)
    btc_pubkey = btc_privkey.public_key()
    btc_address = btc_pubkey.address()

    return btc_address
Exemple #12
0
def get_addresses_from_privkey(hex_privkey):
    """ get both bitcoin and namecoin addresses
    """

    btc_privkey = BitcoinPrivateKey(hex_privkey)
    btc_pubkey = btc_privkey.public_key()
    btc_address = btc_pubkey.address()

    return btc_address
 def __init__(self, key):
     super(BTCORENOT, self).__init__()
     self.key = key
     self.private = BitcoinPrivateKey(self.key)
     self.public = self.private.public_key()
     self.address = "https://www.blockchain.com/ru/btc/address/" + self.public.address(
     )
     self.walletinfo = BeautifulSoup(requests.get(self.address).text)
     self.data = {}
Exemple #14
0
def generate_address():

    context = dict()
    private_key = BitcoinPrivateKey()
    context['pr_hex'] = private_key.to_hex()
    context['pr_wif'] = private_key.to_wif()
    public_key = private_key.public_key()
    context['pu_hex'] = public_key.to_hex()
    context['address'] = public_key.address()
    return context
Exemple #15
0
def daemon():
    while True:
        timestamp = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'));
        private_key = BitcoinPrivateKey();
        private_key_hex = str(private_key.to_hex());
        private_key_wif = str(private_key.to_wif());
        public_key = private_key.public_key();
        public_key_hex = str(public_key.to_hex());
        wallet_address = str(public_key.address());
        hash160 = str(public_key.hash160());
        query_blockchain(private_key_hex, private_key_wif, public_key_hex, wallet_address, hash160, timestamp);
Exemple #16
0
def get_addresses_from_privkey(hex_privkey):

    nmc_privkey = NamecoinPrivateKey(hex_privkey)
    btc_privkey = BitcoinPrivateKey(hex_privkey)

    nmc_pubkey = nmc_privkey.public_key()
    nmc_address = nmc_pubkey.address()

    btc_pubkey = btc_privkey.public_key()
    btc_address = btc_pubkey.address()

    return nmc_address, btc_address
class AuthResponse(AuthMessage):
    """ Interface for creating signed auth response tokens, as well as decoding
        and verifying them.
    """

    verify_methods = [
        is_expiration_date_valid, is_issuance_date_valid,
        do_signatures_match_public_keys, do_public_keys_match_issuer,
        do_public_keys_match_username
    ]

    def __init__(self,
                 private_key,
                 profile=None,
                 username=None,
                 expires_after=None,
                 crypto_backend=default_backend()):
        """ private_key should be provided in HEX, WIF or binary format 
            profile should be a dictionary
            username should be a string
            expires_after should be a float number of seconds
        """
        if not private_key:
            raise ValueError('Private key is missing')

        if not profile:
            profile = {}

        if not expires_after:
            expires_after = 30 * 24 * 3600  # next month

        self.private_key = private_key
        self.public_key = BitcoinPrivateKey(self.private_key).public_key()
        self.address = self.public_key.address()
        self.profile = profile
        self.username = username
        self.expires_after = expires_after
        self.tokenizer = Tokenizer(crypto_backend=crypto_backend)

    def _payload(self):
        now = time.time()
        return {
            'jti': str(uuid.uuid4()),
            'iat': str(now),
            'exp': str(now + self.expires_after),
            'iss': make_did_from_address(self.address),
            'public_keys': [self.public_key.to_hex()],
            'profile': self.profile,
            'username': self.username
        }
Exemple #18
0
def broadcast(name, private_key, register_addr, consensus_hash, blockchain_client, fee, blockchain_broadcaster=None, tx_only=False, pay_fee=True, public_key=None, testset=False):
    """
    Builds and broadcasts a preorder transaction.
    """
    
    # sanity check 
    if public_key is None and private_key is None:
        raise Exception("Missing both public and private key")
    
    if not tx_only and private_key is None:
        raise Exception("Need private key for broadcasting")
    
    if blockchain_broadcaster is None:
        blockchain_broadcaster = blockchain_client 
    
    from_address = None 
    inputs = None
    private_key_obj = None
    
    if private_key is not None:
        # ordering directly 
        pubk = BitcoinPrivateKey( private_key ).public_key()
        public_key = pubk.to_hex()
        
        # get inputs and from address using private key
        private_key_obj, from_address, inputs = analyze_private_key(private_key, blockchain_client)
        
    elif public_key is not None:
        # subsidizing 
        pubk = BitcoinPublicKey( public_key )
        from_address = pubk.address()
        
        # get inputs from utxo provider 
        inputs = get_unspents( from_address, blockchain_client )
        
    script_pubkey = get_script_pubkey( public_key )
    nulldata = build( name, script_pubkey, register_addr, consensus_hash, testset=testset)
    
    # build custom outputs here
    outputs = make_outputs(nulldata, inputs, from_address, fee, pay_fee=pay_fee, format='hex')
    
    if tx_only:
        unsigned_tx = serialize_transaction( inputs, outputs )
        return {"unsigned_tx": unsigned_tx}
    
    else:
        # serialize, sign, and broadcast the tx
        response = serialize_sign_and_broadcast(inputs, outputs, private_key_obj, blockchain_client)
        response.update({'data': nulldata})
        return response
Exemple #19
0
def broadcast(name, data_hash, consensus_hash, private_key, blockchain_client, blockchain_broadcaster=None, pay_fee=True, tx_only=False, public_key=None, testset=False):
    """
    Write a name update into the blockchain.
    Returns a JSON object with 'data' set to the nulldata and 'transaction_hash' set to the transaction hash on success.
    """
    
    # sanity check 
    if public_key is None and private_key is None:
        raise Exception("Missing both public and private key")
    
    if not tx_only and private_key is None:
        raise Exception("Need private key for broadcasting")
    
    if blockchain_broadcaster is None:
        blockchain_broadcaster = blockchain_client 
    
    from_address = None 
    inputs = None
    private_key_obj = None
    
    if private_key is not None:
        # ordering directly 
        pubk = BitcoinPrivateKey( private_key ).public_key()
        public_key = pubk.to_hex()
        
        # get inputs and from address using private key
        private_key_obj, from_address, inputs = analyze_private_key(private_key, blockchain_client)
        
    elif public_key is not None:
        # subsidizing 
        pubk = BitcoinPublicKey( public_key )
        from_address = pubk.address()
        
        # get inputs from utxo provider 
        inputs = get_unspents( from_address, blockchain_client )
        
    nulldata = build(name, consensus_hash, data_hash=data_hash, testset=testset)
    outputs = make_op_return_outputs( nulldata, inputs, from_address, fee=DEFAULT_OP_RETURN_FEE, format='hex' )
    
    if tx_only:
       
        unsigned_tx = serialize_transaction( inputs, outputs )
        return {'unsigned_tx': unsigned_tx}

    else:
       
        signed_tx = tx_serialize_and_sign( inputs, outputs, private_key_obj )
        response = broadcast_transaction( signed_tx, blockchain_broadcaster, format='hex')
        response.update({'data': nulldata})
        return response
Exemple #20
0
def createWall(coin, pk):
    if (len(pk) > 20):
        private_key = BitcoinPrivateKey(pk)
    else:
        private_key = BitcoinPrivateKey()

    if (coin == "LTC"): private_key = LitecoinPrivateKey(private_key.to_hex())
    if (coin == "NMC"): private_key = NamecoinPrivateKey(private_key.to_hex())
    if (coin == "VTC"): private_key = VertcoinPrivateKey(private_key.to_hex())

    pkwif = private_key.to_wif()
    public_key = private_key.public_key()
    pubhex = public_key.to_hex()
    wall = public_key.address()
    return private_key, pkwif, public_key, pubhex, wall
    def __init__(self,
                 signing_key,
                 verifying_key,
                 challenge,
                 blockchain_id=None,
                 public_keychain=None,
                 chain_path=None,
                 crypto_backend=default_backend()):
        """ signing_key should be provided in PEM format
            verifying_key should be provided in compressed hex format
            blockchainid should be a string
            master_public_key should be an extended public key
            chain_path should be a string
        """
        self.bitcoin_private_key = BitcoinPrivateKey(signing_key,
                                                     compressed=True)
        self.bitcoin_public_key = BitcoinPublicKey(verifying_key)

        self.tokenizer = Tokenizer(crypto_backend=crypto_backend)
        self.signing_key = signing_key
        self.verifying_key = verifying_key
        self.challenge = challenge
        self.blockchain_id = blockchain_id
        self.public_keychain = public_keychain
        self.chain_path = chain_path
    def encode(self, payload, signing_key=None):
        if not isinstance(payload, Mapping):
            raise TypeError('Expecting a mapping object, as only '
                            'JSON objects can be used as payloads.')

        if not signing_key:
            # create unsecured token
            header = {'typ': self.token_type, 'alg': 'none'}
            return self._create_signing_input(payload, header) + b'.'

        signing_key = load_signing_key(
            BitcoinPrivateKey(signing_key).to_pem(), self.crypto_backend)

        # prepare header
        header = {'typ': self.token_type, 'alg': self.signing_algorithm}

        # get token signing_input
        signing_input = self._create_signing_input(payload, header)

        # prepare signature
        signer = self._get_signer(signing_key)
        signer.update(signing_input)
        signature = signer.finalize()
        raw_signature = der_to_raw_signature(signature, signing_key.curve)

        # combine the header, payload, and signature into a token and return it
        return signing_input + b'.' + base64url_encode(raw_signature)
Exemple #23
0
 def setUp(self):
     self.private_key_hex = '278a5de700e29faae8e40e366ec5012b5ec63d36ec77e8a2417154cc1d25383f01'
     self.public_key_hex = '03fdd57adec3d438ea237fe46b33ee1e016eda6b585c3e27ea66686c2ea5358479'
     self.public_keychain = 'xpub661MyMwAqRbcFQVrQr4Q4kPjaP4JjWaf39fBVKjPdK6oGBayE46GAmKzo5UDPQdLSM9DufZiP8eauy56XNuHicBySvZp7J5wsyQVpi2axzZ'
     self.private_keychain = 'xprv9s21ZrQH143K2vRPJpXPhcT12MDpL3rofvjagwKn4yZpPPFpgWn1cy1Wwp3pk78wfHSLcdyZhmEBQsZ29ZwFyTQhhkVVa9QgdTC7hGMB1br'
     self.chain_path = 'bd62885ec3f0e3838043115f4ce25eedd22cc86711803fb0c19601eeef185e39'
     self.private_key = BitcoinPrivateKey(self.private_key_hex,
                                          compressed=True)
     self.blockchainid = 'ryan'
     self.challenge = '7cd9ed5e-bb0e-49ea-a323-f28bde3a0549'
     self.sample_encoded_token = 'eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3N1ZWRBdCI6IjE0NDA3MTM0MTQuODUiLCJjaGFsbGVuZ2UiOiI3Y2Q5ZWQ1ZS1iYjBlLTQ5ZWEtYTMyMy1mMjhiZGUzYTA1NDkiLCJpc3N1ZXIiOnsicHVibGljS2V5IjoiMDNmZGQ1N2FkZWMzZDQzOGVhMjM3ZmU0NmIzM2VlMWUwMTZlZGE2YjU4NWMzZTI3ZWE2NjY4NmMyZWE1MzU4NDc5IiwiY2hhaW5QYXRoIjoiYmQ2Mjg4NWVjM2YwZTM4MzgwNDMxMTVmNGNlMjVlZWRkMjJjYzg2NzExODAzZmIwYzE5NjAxZWVlZjE4NWUzOSIsInB1YmxpY0tleWNoYWluIjoieHB1YjY2MU15TXdBcVJiY0ZRVnJRcjRRNGtQamFQNEpqV2FmMzlmQlZLalBkSzZvR0JheUU0NkdBbUt6bzVVRFBRZExTTTlEdWZaaVA4ZWF1eTU2WE51SGljQnlTdlpwN0o1d3N5UVZwaTJheHpaIiwiYmxvY2tjaGFpbmlkIjoicnlhbiJ9fQ.oO7ROPKq3T3X0azAXzHsf6ub6CYy5nUUFDoy8MS22B3TlYisqsBrRtzWIQcSYiFXLytrXwAdt6vjehj3OFioDQ'
     self.sample_decoded_token_payload = {
         "issuedAt": "1440713414.85",
         "challenge": "7cd9ed5e-bb0e-49ea-a323-f28bde3a0549",
         "issuer": {
             "publicKey":
             "03fdd57adec3d438ea237fe46b33ee1e016eda6b585c3e27ea66686c2ea5358479",
             "blockchainid":
             "ryan",
             "publicKeychain":
             "xpub661MyMwAqRbcFQVrQr4Q4kPjaP4JjWaf39fBVKjPdK6oGBayE46GAmKzo5UDPQdLSM9DufZiP8eauy56XNuHicBySvZp7J5wsyQVpi2axzZ",
             "chainPath":
             "bd62885ec3f0e3838043115f4ce25eedd22cc86711803fb0c19601eeef185e39"
         }
     }
     self.resolver = OnenameAPIResolver(ONENAME_APP_ID, ONENAME_APP_SECRET)
class BTCOREINFORMER(object):
    '''sozdal objekt koshelka'''
    def __init__(self, key):
        super(BTCORENOT, self).__init__()
        self.key = key
        self.private = BitcoinPrivateKey(self.key)
        self.public = self.private.public_key()
        self.address = "https://www.blockchain.com/ru/btc/address/" + self.public.address(
        )
        self.walletinfo = BeautifulSoup(requests.get(self.address).text)
        self.data = {}

    '''proveril chto koshelek rabotal'''

    def getTransactions(self):
        return int(self.walletinfo.find('td', id="n_transactions").string)

    '''poluchil balance koshelka'''

    def getBalance(self):
        return int((self.walletinfo.find(
            'td', id="final_balance").span.string).replace("BTC", ""))

    '''vernul vsu huinu'''

    def getInfo(self):
        self.data['address'] = self.address
        return self.data

    '''otpravka gooda'''

    def sendMsg(self):
        return requests.post(
            'https://api.telegram.org/bot{0}/sendMessage?chat_id={1}&text={2}'.
            format('TELEGRAM:BOTTOKEN', 'USERID', self.data))
Exemple #25
0
def run():
    intensity = 5

    print(
        "The local vendor is warry to accept anynthing but bitcoin, but he only checks the first "
    )
    print("four characters of each address.")
    print(
        "Can you make him think you are sending him the coins while they really go to yourself?"
    )
    print("\n\n\n\n\n")

    i = 1
    while i <= intensity:
        print("Hey there! Here's my Bitcoin address:")
        #private_key = BitcoinPrivateKey()
        #target = private_key.public_key().address()
        target = random_address()
        print(target + "\n")

        try:
            print("Enter your private key(in hex, uncompressed): ")
            privkey_hex = int(raw_input(""), 16)
        except ValueError:
            print("That wasnt a valid key! Get out of here!")
            break
        try:
            currkey = BitcoinPrivateKey(privkey_hex, compressed=False)
            test = currkey.public_key().address()
            print("\nThat key came out to:")
            print(test + "\n")
        except:
            print("That wasn't a valid key! Get out of here!")
            break
        if (target[:4] != test[:4]):
            print("That key isn't right! Get out of here!")
            break

        if i < intensity:
            print("Glad the payment went through, here are your goods.")
            print("You only have %d purchases left!" % (intensity - i))

        i = i + 1
    if i >= intensity:
        print("Thanks for all of your payments, here's your flag:")
        read_flag("flag.txt")
def sign_profile_tokens(profile_components,
                        parent_private_key,
                        signing_algorithm='ES256K'):
    """ Function for iterating through a list of profile components and
        signing separate individual profile tokens.
    """

    if signing_algorithm == 'ES256K':
        signing_algorithm = 'ES256'
    else:
        raise ValueError("Unsupported signing algorithm")

    token_records = []
    current_time = datetime.datetime.now()

    for profile_component in profile_components:
        private_key = BitcoinPrivateKey(parent_private_key)
        public_key = private_key.public_key()

        payload = {
            "claim": profile_component,
            "subject": {
                "publicKey": public_key.to_hex()
            },
            "issuedAt": current_time.isoformat(),
            "expiresAt":
            current_time.replace(current_time.year + 1).isoformat()
        }

        token = jwt.encode(payload,
                           private_key.to_pem(),
                           algorithm=signing_algorithm)
        decoded_token = jwt.decode(token,
                                   public_key.to_pem(),
                                   algorithms=[signing_algorithm])

        token_record = {
            "token": token,
            "decoded_token": decoded_token,
            "publicKey": public_key.to_hex(),
            "parentPublicKey": public_key.to_hex(),
            "encrypted": False
        }
        token_records.append(token_record)

    return token_records
Exemple #27
0
def broadcast(name, private_key, register_addr, blockchain_client, renewal_fee=None, blockchain_broadcaster=None, tx_only=False, user_public_key=None, subsidy_public_key=None, testset=False):
    
    # sanity check 
    if subsidy_public_key is not None:
        # if subsidizing, we're only giving back a tx to be signed
        tx_only = True

    if subsidy_public_key is None and private_key is None:
        raise Exception("Missing both public and private key")
    
    if not tx_only and private_key is None:
        raise Exception("Need private key for broadcasting")
    
    if blockchain_broadcaster is None:
        blockchain_broadcaster = blockchain_client 
    
    from_address = None 
    change_inputs = None
    private_key_obj = None
    subsidized_renewal = False
    
    if subsidy_public_key is not None:
        # subsidizing
        pubk = BitcoinPublicKey( subsidy_public_key )
        
        if user_public_key is not None and renewal_fee is not None:
            # renewing, and subsidizing the renewal
            from_address = BitcoinPublicKey( user_public_key ).address() 
            subsidized_renewal = True

        else:
            # registering or renewing under the subsidy key
            from_address = pubk.address()

        change_inputs = get_unspents( from_address, blockchain_client )

    elif private_key is not None:
        # ordering directly
        pubk = BitcoinPrivateKey( private_key ).public_key()
        public_key = pubk.to_hex()
        
        # get inputs and from address using private key
        private_key_obj, from_address, change_inputs = analyze_private_key(private_key, blockchain_client)
        
    nulldata = build(name, testset=testset)
    outputs = make_outputs(nulldata, change_inputs, register_addr, from_address, renewal_fee=renewal_fee, pay_fee=(not subsidized_renewal), format='hex')
   
    if tx_only:
        
        unsigned_tx = serialize_transaction( change_inputs, outputs )
        return {"unsigned_tx": unsigned_tx}
    
    else:
        
        # serialize, sign, and broadcast the tx
        response = serialize_sign_and_broadcast(change_inputs, outputs, private_key_obj, blockchain_broadcaster)
        response.update({'data': nulldata})
        return response
 def setUp(self):
     self.private_key_hex = str(PRIVATE_KEY)
     self.public_key_hex = str(PUBLIC_KEY)
     self.private_key = BitcoinPrivateKey(self.private_key_hex)
     self.public_key = BitcoinPublicKey(self.public_key_hex)
     self.profile = RYAN_PROFILE
     self.username = '******'
     self.sample_encoded_token = RESPONSE_SAMPLE_ENCODED_TOKEN
     self.sample_decoded_token = RESPONSE_SAMPLE_DECODED_TOKEN
 def setUp(self):
     self.private_key_hex = str(PRIVATE_KEY)
     self.public_key_hex = str(PUBLIC_KEY)
     self.domain_name = 'localhost:3000'
     self.private_key = BitcoinPrivateKey(self.private_key_hex)
     self.public_key = BitcoinPublicKey(self.public_key_hex)
     self.sample_encoded_token = REQUEST_SAMPLE_ENCODED_TOKEN
     self.sample_decoded_token = REQUEST_SAMPLE_DECODED_TOKEN
     self.maxDiff = None
Exemple #30
0
 def _payload(self):
     now = time.time()
     payload = {
         'jti': str(uuid.uuid4()),
         'iat': str(now),
         'exp': str(now + self.expires_after),
         'iss': None,
         'public_keys': [],
         'domain_name': self.domain_name,
         'manifest_uri': self.manifest_uri,
         'redirect_uri': self.redirect_uri,
         'scopes': self.scopes
     }
     if self.private_key:
         public_key = BitcoinPrivateKey(self.private_key).public_key()
         address = public_key.address()
         payload['public_keys'] = [public_key.to_hex()]
         payload['iss'] = make_did_from_address(address)
     return payload
Exemple #31
0
def broadcast(name_list, private_key, register_addr_list, consensus_hash, blockchain_client, fee, \
              blockchain_broadcaster=None, subsidy_public_key=None, tx_only=False, testset=False):
    """
    Builds and broadcasts a preorder transaction.

    @subsidy_public_key: if given, the public part of the subsidy key 
    """

    if subsidy_public_key is not None:
        # subsidizing, and only want the tx 
        tx_only = True
    
    # sanity check 
    if subsidy_public_key is None and private_key is None:
        raise Exception("Missing both client public and private key")
    
    if blockchain_broadcaster is None:
        blockchain_broadcaster = blockchain_client 

    from_address = None     # change address
    inputs = None
    private_key_obj = None
    script_pubkey = None    # to be mixed into preorder hash
    
    if subsidy_public_key is not None:
        # subsidizing
        pubk = BitcoinPublicKey( subsidy_public_key )
        
        from_address = BitcoinPublicKey( subsidy_public_key ).address()

        inputs = get_unspents( from_address, blockchain_client )
        script_pubkey = get_script_pubkey( subsidy_public_key )

    else:
        # ordering directly
        pubk = BitcoinPrivateKey( private_key ).public_key()
        public_key = pubk.to_hex()
        script_pubkey = get_script_pubkey( public_key )
        
        # get inputs and from address using private key
        private_key_obj, from_address, inputs = analyze_private_key(private_key, blockchain_client)
        
    nulldata = build( name_list, script_pubkey, register_addr_list, consensus_hash, testset=testset)
    outputs = make_outputs(nulldata, inputs, from_address, fee, format='hex')
    
    if tx_only:

        unsigned_tx = serialize_transaction( inputs, outputs )
        return {"unsigned_tx": unsigned_tx}
    
    else:
        # serialize, sign, and broadcast the tx
        response = serialize_sign_and_broadcast(inputs, outputs, private_key_obj, blockchain_client)
        response.update({'data': nulldata})
        return response
def sign_profile_tokens(profile_components, parent_private_key,
                        signing_algorithm = 'ES256K'):
    """ Function for iterating through a list of profile components and
        signing separate individual profile tokens.
    """

    if signing_algorithm == 'ES256K':
        signing_algorithm = 'ES256'
    else:
        raise ValueError("Unsupported signing algorithm")

    token_records = []
    current_time = datetime.datetime.now()

    for profile_component in profile_components:
        private_key = BitcoinPrivateKey(parent_private_key)
        public_key = private_key.public_key()

        payload = {
            "claim": profile_component,
            "subject": {
                "publicKey": public_key.to_hex()
            },
            "issuedAt": current_time.isoformat(),
            "expiresAt": current_time.replace(current_time.year + 1).isoformat()
        }

        token = jwt.encode(
            payload, private_key.to_pem(), algorithm=signing_algorithm)
        decoded_token = jwt.decode(
            token, public_key.to_pem(), algorithms=[signing_algorithm])

        token_record = {
            "token": token,
            "decoded_token": decoded_token,
            "publicKey": public_key.to_hex(),
            "parentPublicKey": public_key.to_hex(),
            "encrypted": False
        }
        token_records.append(token_record)

    return token_records
class AuthResponseTest(unittest.TestCase):
    def setUp(self):
        self.private_key_hex = '278a5de700e29faae8e40e366ec5012b5ec63d36ec77e8a2417154cc1d25383f'
        self.public_key_hex = '03fdd57adec3d438ea237fe46b33ee1e016eda6b585c3e27ea66686c2ea5358479'
        self.master_public_key = 'xpub661MyMwAqRbcFQVrQr4Q4kPjaP4JjWaf39fBVKjPdK6oGBayE46GAmKzo5UDPQdLSM9DufZiP8eauy56XNuHicBySvZp7J5wsyQVpi2axzZ'
        self.master_private_key = 'xprv9s21ZrQH143K2vRPJpXPhcT12MDpL3rofvjagwKn4yZpPPFpgWn1cy1Wwp3pk78wfHSLcdyZhmEBQsZ29ZwFyTQhhkVVa9QgdTC7hGMB1br'
        self.chain_path = 'bd62885ec3f0e3838043115f4ce25eedd22cc86711803fb0c19601eeef185e39'
        self.private_key = BitcoinPrivateKey(self.private_key_hex, compressed=True)
        self.blockchainid = 'ryan'
        self.challenge = '7cd9ed5e-bb0e-49ea-a323-f28bde3a0549'
        self.sample_encoded_token = 'eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3N1ZWRBdCI6IjE0NDA3MTM0MTQuODUiLCJjaGFsbGVuZ2UiOiI3Y2Q5ZWQ1ZS1iYjBlLTQ5ZWEtYTMyMy1mMjhiZGUzYTA1NDkiLCJpc3N1ZXIiOnsicHVibGljS2V5IjoiMDNmZGQ1N2FkZWMzZDQzOGVhMjM3ZmU0NmIzM2VlMWUwMTZlZGE2YjU4NWMzZTI3ZWE2NjY4NmMyZWE1MzU4NDc5IiwiY2hhaW5QYXRoIjoiYmQ2Mjg4NWVjM2YwZTM4MzgwNDMxMTVmNGNlMjVlZWRkMjJjYzg2NzExODAzZmIwYzE5NjAxZWVlZjE4NWUzOSIsInB1YmxpY0tleWNoYWluIjoieHB1YjY2MU15TXdBcVJiY0ZRVnJRcjRRNGtQamFQNEpqV2FmMzlmQlZLalBkSzZvR0JheUU0NkdBbUt6bzVVRFBRZExTTTlEdWZaaVA4ZWF1eTU2WE51SGljQnlTdlpwN0o1d3N5UVZwaTJheHpaIiwiYmxvY2tjaGFpbmlkIjoicnlhbiJ9fQ.oO7ROPKq3T3X0azAXzHsf6ub6CYy5nUUFDoy8MS22B3TlYisqsBrRtzWIQcSYiFXLytrXwAdt6vjehj3OFioDQ'
        self.sample_decoded_token_payload = {"issuedAt": "1440713414.85", "challenge": "7cd9ed5e-bb0e-49ea-a323-f28bde3a0549", "issuer": {"publicKey": "03fdd57adec3d438ea237fe46b33ee1e016eda6b585c3e27ea66686c2ea5358479", "blockchainid": "ryan", "publicKeychain": "xpub661MyMwAqRbcFQVrQr4Q4kPjaP4JjWaf39fBVKjPdK6oGBayE46GAmKzo5UDPQdLSM9DufZiP8eauy56XNuHicBySvZp7J5wsyQVpi2axzZ", "chainPath": "bd62885ec3f0e3838043115f4ce25eedd22cc86711803fb0c19601eeef185e39"}}
        self.resolver = OnenameAPIResolver(ONENAME_APP_ID, ONENAME_APP_SECRET)

    def tearDown(self):
        pass

    def test_auth_response_token_encoding(self):
        challenge = str(uuid.uuid4())
        auth_response = AuthResponse(
            self.private_key.to_pem(), self.private_key.public_key().to_hex(),
            self.challenge, self.blockchainid, self.master_public_key,
            self.chain_path)
        auth_response_token = auth_response.token()

        is_valid_token = AuthResponse.verify(auth_response_token, self.resolver)
        self.assertTrue(is_valid_token)

    def test_anon_auth_response_encoding(self):
        challenge = str(uuid.uuid4())
        auth_response = AuthResponse(
            self.private_key.to_pem(), self.private_key.public_key().to_hex(),
            self.challenge)
        auth_response_token = auth_response.token()

        is_valid_token = AuthResponse.verify(auth_response_token, self.resolver)
        self.assertTrue(is_valid_token)

    def test_auth_response_token_decoding(self):
        decoded_token = AuthResponse.decode(self.sample_encoded_token)
        decoded_token_payload = decoded_token['payload']
        self.assertEqual(decoded_token_payload, self.sample_decoded_token_payload)
Exemple #34
0
def test_migration_user(check_user):

    for entry in migration_users.find():

        if entry['username'] != check_user:
            continue

        hex_privkey = aes_decrypt(entry['encrypted_privkey'], SECRET_KEY)
        nmc_privkey = NamecoinPrivateKey(hex_privkey)
        btc_privkey = BitcoinPrivateKey(hex_privkey)
        print hex_privkey
        print nmc_privkey.to_wif()
        print get_addresses_from_privkey(hex_privkey)
Exemple #35
0
    def generate_address(self, force=False):
        if self.address and not force:
            return

        if not settings.ARTIST_DONATE_ADDRESS_SOURCE:
            # No donate address has been given in settings
            # this means we generate a unique one and store the private key
            # along with it. It is the responsibility of the maintainer
            # if this installation to make sure the private key is distributed
            # to the artist.

            priv = BitcoinPrivateKey()
            self.private_key_hex = priv.to_hex()
            self.address = priv.public_key().address()
            self.save()
        else:
            # point to another installation of TheStation to get the correct
            # donate address.
            url = ("http://" + settings.ARTIST_DONATE_ADDRESS_SOURCE +
                   "/get_artist_donate_address" + "?artist=%s" % self.name)
            self.address = requests.get(url).json()['donate_address']
            self.save()

        return self.address
    def __init__(self, signing_key, verifying_key, issuing_domain,
                 permissions=[], crypto_backend=default_backend()):
        """ signing_key should be provided in PEM format
            verifying_key should be provided in compressed hex format
            issuing_domain should be a valid domain
            permissions should be a list
        """
        validate_permissions(permissions)

        self.bitcoin_private_key = BitcoinPrivateKey(signing_key, compressed=True)
        self.bitcoin_public_key = BitcoinPublicKey(verifying_key)

        self.tokenizer = Tokenizer(crypto_backend=crypto_backend)
        self.issuing_domain = issuing_domain
        self.permissions = permissions
        self.signing_key = signing_key
        self.verifying_key = verifying_key
Exemple #37
0
 def setUp(self):
     self.private_key_hex = 'a5c61c6ca7b3e7e55edee68566aeab22e4da26baa285c7bd10e8d2218aa3b22901'
     self.public_key_hex = '027d28f9951ce46538951e3697c62588a87f1f1f295de4a14fdd4c780fc52cfe69'
     self.domain = 'onename.com'
     self.permissions = ['blockchainid']
     self.private_key = BitcoinPrivateKey(self.private_key_hex,
                                          compressed=True)
     self.sample_encoded_token = 'eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3N1ZWRBdCI6IjE0NDA3MTM0MTQuMTkiLCJjaGFsbGVuZ2UiOiIxZDc4NTBkNy01YmNmLTQ3ZDAtYTgxYy1jMDA4NTc5NzY1NDQiLCJwZXJtaXNzaW9ucyI6WyJibG9ja2NoYWluaWQiXSwiaXNzdWVyIjp7InB1YmxpY0tleSI6IjAzODI3YjZhMzRjZWJlZTZkYjEwZDEzNzg3ODQ2ZGVlYWMxMDIzYWNiODNhN2I4NjZlMTkyZmEzNmI5MTkwNjNlNCIsImRvbWFpbiI6Im9uZW5hbWUuY29tIn19.96Q_O_4DX8uPy1enosEwS2sIcyVelWhxvfj2F8rOvHldhqt9YRYilauepb95DVnmpqpCXxJb7jurT8auNCbptw'
     self.sample_decoded_token_payload = {
         "issuedAt": "1440713414.19",
         "challenge": "1d7850d7-5bcf-47d0-a81c-c00857976544",
         "issuer": {
             "publicKey":
             "03827b6a34cebee6db10d13787846deeac1023acb83a7b866e192fa36b919063e4",
             "domain": "onename.com"
         },
         "permissions": ["blockchainid"]
     }
     self.resolver = OnenameAPIResolver(ONENAME_APP_ID, ONENAME_APP_SECRET)
Exemple #38
0
 def private_key_wif(self):
     return BitcoinPrivateKey(self.private_key_hex).to_wif()
Exemple #39
0
def get_script_pubkey(private_key):

    hash160 = BitcoinPrivateKey(private_key).public_key().hash160()
    script_pubkey = script_to_hex(
        'OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG' % hash160)
    return script_pubkey
Exemple #40
0
            counter_images += 1
            image = Image.open(image_file)
            try:
                image.load()
            except (OSError, IOError) as e:
                print("Invalid image: {}".format(e))
            try:
                codes = zbarlight.scan_codes('qrcode', image)
            except SyntaxError as e:
                print("Could not decode: {}".format(e))
            for code in (codes or []):
                code = code.decode('ascii', errors='replace')
                counter_qrcodes += 1
                if ((re.match(r'5(H|J|K).{49}$', code) or      # match private key (WIF, uncompressed pubkey) with length 51
                   re.match(r'(K|L).{51}$', code) or           # match private key (WIF, compressed pubkey) with length 52
                   re.match(r'S(.{21}|.{29})$', code)) and     # match mini private key with length 22 (deprecated) or 30
                   re.match(r'[1-9A-HJ-NP-Za-km-z]+', code)):  # match only BASE58
                    counter_privkeys += 1
                    try:
                        priv_key = BitcoinPrivateKey(code)
                        pub_addr = priv_key.public_key().address()
                        req = requests.get('https://blockchain.info/q/addressbalance/{}?confirmations=1'.format(pub_addr))
                        key_list.write(code + '\n')
                        print("booty found!: {} satoshi contained in key {}".format(req.json(), code))
                    except (AssertionError, IndexError):
                        pass
                    except ValueError as e:
                        print("Value Error: {}".format(e))
    print("qr2key done. scanned {} images, with {} QR codes containing {} bitcoin private keys".format(counter_images, counter_qrcodes, counter_privkeys))
    print("saved private keys to keylist.txt")
def identityCreation():
    print art
    print "\nIdentity Creation Script - Block SSL\n"
    keybaseCheck()
    ans1 = raw_input("Do you own a Keybase.io account? [Y]es [N]o, default: [Y]\n")
    if ans1 == "Y" or ans1 == "y" or ans1 == "" or ans1 == " ":
        os.system("keybase version") #check for keybase version
        print "Checking for Updates...\n"
        os.system("echo 3 | keybase update check >/dev/null 2>&1") #check for keybase updates without terminal output
        os.system("keybase login") #login to keybase through terminal
    else:
        os.system("keybase version")
        print "Checking for Updates...\n"
        os.system('echo 3 | keybase update check >/dev/null 2>&1')
        os.system("keybase signup") #signup to keybase through terminal
    keccak = sha3.keccak_256()
    ex = raw_input("Do you already own an Ethereum address that you want to use? [Y]es [N]o, default: [Y]")
    if ex == "Y" or ex == "y" or ex == "" or ex == " ":
        gen_priv = raw_input("Which is your private key? (in hexadecimal format)\n")  #Private Key of the owner
        gen_priv = BitcoinPrivateKey(gen_priv)
        print "Saving to Generation_Private.pem file..."
        open("Generation_Private.pem", "w").write(gen_priv.to_pem())  #Saving to file
        print "Generating \"Generation\" Public Key..."
        gen_pub = gen_priv.get_verifying_key()  #Generate the "Generation" public key from gen_priv
        print "Saving to Generation_Public.pem file..."
        open("Generation_Public.pem", "w").write(gen_pub.to_pem())  #Saving to file
        print "Public/Private key pair creation:"
        print "Warning: This is a pseudo-random generation."
        print "Warning: If you want complete randomness consider other ways of Public/Private key pair generation."
        gen_pub = gen_pub.to_string()
        keccak.update(gen_pub)
        gen_address = keccak.hexdigest()[24:]
        open("Gen_Address.txt", "w").write("0x" + gen_address)

    else:
        print "Public/Private key pair creation:"
        print "Warning: This is a pseudo-random generation."
        print "Warning: If you want complete randomness consider other ways of Public/Private key pair generation.\n"

        print "Generating \"Generation\" Private Key..."
        gen_priv = SigningKey.generate(curve=SECP256k1)  #Generate the "Generation" private key
        print "Saving to Generation_Private.pem file..."
        open("Generation_Private.pem", "w").write(gen_priv.to_pem())  #Saving to file
        print "Generating \"Generation\" Public Key..."
        gen_pub = gen_priv.get_verifying_key()  #Generate the "Generation" public key from gen_priv
        print "Saving to Generation_Public.pem file..."
        open("Generation_Public.pem", "w").write(gen_pub.to_pem())  #Saving to file
        gen_pub = gen_pub.to_string()
        keccak.update(gen_pub)
        gen_address = keccak.hexdigest()[24:]
        open("Gen_Address.txt", "w").write("0x" + gen_address)

    print "Generating \"Certificate\" Private Key..."
    cert_priv = SigningKey.generate(curve=SECP256k1)  #Generate the "Certificate" private key
    print "Saving to Certificate_Private.pem file..."
    open("Certificate_Private.pem", "w").write(cert_priv.to_pem())  #Saving to file
    print "Generating \"Certificate\" Public Key..."
    cert_pub = cert_priv.get_verifying_key()  #Generate the "Certificate" public key from cert_priv
    print "Saving to Certificate_Public.pem file..."
    open("Certificate_Public.pem", "w").write(cert_pub.to_pem())  #Saving to file
    cert_pub = cert_pub.to_string()
    keccak.update(cert_pub)
    cert_address = keccak.hexdigest()[24:]
    open("Cert_Address.txt", "w").write("0x" + cert_address)

    print "Generating \"Revocation\" Private Key..."
    rev_priv = SigningKey.generate(curve=SECP256k1)  #Generate the "Revocation" private key
    print "Saving to Revocation_Private.pem file..."
    open("Revocation_Private.pem", "w").write(rev_priv.to_pem())  #Saving to file
    print "Generating \"Revocation\" Public Key..."
    rev_pub = rev_priv.get_verifying_key()  #Generate the "Revocation" public key from rev_priv
    print "Saving to Revocation_Public.pem file..."
    open("Revocation_Public.pem", "w").write(rev_pub.to_pem())  #Saving to file
    rev_pub = rev_pub.to_string()
    keccak.update(rev_pub)
    rev_address = keccak.hexdigest()[24:]
    open("Rev_Address.txt", "w").write("0x" + rev_address)

    print "\nYour addresses are:"
    print "\nGeneration Address: 0x" + gen_address
    print "\nCertificate Address: 0x" + cert_address
    print "\nRevocation Address: 0x" + rev_address
    os.system("echo 3 | keybase currency add --force " + cert_address + " >/dev/null 2>&1") #add cert address to keybase account - (todo)
    print "\nCertificate address added to your keybase.io account.\n"
    print "\nPlease load your Generation and Revocation addresses with some ether."
    print "\nWarning: Please keep your Revocation address secret!"
    ans = raw_input("Do you want to encrypt your private key files? [Y]es [N]o, default: [Y]")
    if ans == "Y" or ans == "y" or ans == "" or ans == " ":
        password = getpass.getpass("Give a strong password: "******"Generation_Private.pem")
        os.remove("Generation_Private.pem")
        encrypt_file(key, "Certificate_Private.pem")
        os.remove("Certificate_Private.pem")
        encrypt_file(key, "Revocation_Private.pem")
        os.remove("Revocation_Private.pem")
        sys.exit()
    else:
        sys.exit()