Exemplo n.º 1
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
Exemplo n.º 2
0
    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)
Exemplo n.º 3
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)
Exemplo n.º 4
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
    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)
Exemplo n.º 6
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)
Exemplo n.º 7
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)
    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
Exemplo n.º 9
0
def get_address_from_privkey(hex_privkey):
    """ get bitcoin address from private key
    """

    privkey = BitcoinPrivateKey(hex_privkey)

    pubkey = privkey.public_key()
    return pubkey.address()
Exemplo n.º 10
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
Exemplo n.º 11
0
 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 = {}
Exemplo n.º 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
Exemplo n.º 13
0
 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
Exemplo n.º 14
0
 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
Exemplo n.º 15
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
Exemplo n.º 16
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
Exemplo n.º 17
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);
Exemplo n.º 18
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)
    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
Exemplo n.º 20
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")
Exemplo n.º 21
0
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
Exemplo n.º 22
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)
Exemplo n.º 23
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
Exemplo n.º 24
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
Exemplo n.º 25
0
 def private_key_wif(self):
     return BitcoinPrivateKey(self.private_key_hex).to_wif()
Exemplo n.º 26
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
Exemplo n.º 27
0
 def setUp(self):
     self.master_private_key = BitcoinPrivateKey()
def main():
    global args
    addresses = []
    private_keys = []
    addresses_with_balance = []
    private_keys_with_balance = []

    #Print messages
    if (args.anonymous):
        print("Anonymous mode enalbed. Check that Tor Router is running.")

    #Find addresses and private keys inside STDIN
    print("Searching for bitcoin addresses...")
    print("")
    with open(args.input) as f:
        content = f.readlines()
    for line in content:

        #Find all bitcoin addresses
        for match in re.findall('[13][a-km-zA-HJ-NP-Z1-9]{25,34}', line):
            print("Match: " + match)
            addresses.append(match)

        #Find all bitcoin private keys
        for match in re.findall('[5KL][1-9A-HJ-NP-Za-km-z]{50,51}', line):
            print("Match: " + match)
            private_keys.append(match)
    print("")

    #Remove duplicate public addresses (that correspond to some private key)
    print("Removing duplicate addresses (private key match)...")
    print("")
    for private_key in private_keys:
        address = BitcoinPrivateKey(private_key).public_key().address()
        if address in addresses:
            print("Removed: " + address)
            addresses.remove(address)
    print("")

    #Get addressess with balance
    print("Getting address with balance...")
    print("")

    max_progress = len(addresses) + len(private_keys)
    with tqdm(total=max_progress, unit='check') as pbar:

        for address in addresses:
            balance = checkBalance(address)
            balance = float(balance) / float(
                100000000)  #Convert satoshi to Bitcoin
            if balance > 0:
                #print(address + " has " + str(balance) + " satoshi (" + str(float(balance)/float(100000000)) + " BTC)")
                with open(args.output, "a") as myfile:
                    myfile.write(address + ",," + str(balance) + "\n")
            pbar.update(1)

        for private_key in private_keys:
            address = privateKeyToAddress(private_key)
            balance = checkBalance(address)
            balance = float(balance) / float(
                100000000)  #Convert satoshi to Bitcoin
            if balance > 0:
                #print(address + " " + str(balance) + " has " + str(balance) + " satoshi (" + str(float(balance)/float(100000000)) + " BTC)")
                with open(args.output, "a") as myfile:
                    myfile.write(address + "," + private_key + "," +
                                 str(balance) + "\n")
            pbar.update(1)

    print("")
Exemplo n.º 29
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 privateKeyToAddress(private_key):
    return BitcoinPrivateKey(private_key).public_key().address()