Ejemplo n.º 1
0
def Check1000k_address(start_private_key,Num):
    global guessNum
    private_key = deepcopy(start_private_key)
    # private_key=26563230048437957592232553826663696440606756685920117476832299673293013768870
    startkey = deepcopy(start_private_key)
    while private_key < 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141:
        random_private_key=Generate_random_private_key()
        random_addresss = from_private_key_to_address(random_private_key)
        private_key += 1
        guessNum += 1
        PrivateKey_WIF = bitcoin.encode_privkey(private_key,'wif')
        compressed_private_key = bitcoin.encode_privkey(private_key,'hex') + '01'
        PrivateKey_WIF_Compressed = bitcoin.encode_privkey(bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif')
        bitcoin_address = bitcoin.privkey_to_address(PrivateKey_WIF)
        compressed_bitcoin_address = bitcoin.privkey_to_address(PrivateKey_WIF_Compressed)
        addresss = [bitcoin_address,compressed_bitcoin_address,random_addresss[0],random_addresss[1]]
        for address in addresss:
            try:
                balance = querybalainceV3(address)
            except:
                print 'failed to query private_key %s ,address %s' % (private_key,address)
                add_unquery_address_to_log(private_key,address)
                continue
            time.sleep(0.5)
            #balance = querybalance('1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa')
            if int(balance) >0 :
                print 'private_key %s has %s BTC' % (private_key,balance)
                add_query_address_has_btc(private_key,address)
                linestring = 'private_key %s has %s BTC !' % (private_key,balance)
                smtp.send_BTCmail(linestring)
        print "Check %s private_key %s " % (str(guessNum),private_key)
        if private_key==startkey + Num:
            add_query_address_has_btc(private_key,Num)
            break
Ejemplo n.º 2
0
def generate_keypair(crypto, seed, password=None):
    """
    Generate a private key and publickey for any currency, given a seed.
    That seed can be random, or a brainwallet phrase.
    """
    pub_byte, priv_byte = get_magic_bytes(crypto)
    priv = sha256(seed)
    pub = privtopub(priv)

    if priv_byte >= 128:
        priv_byte -= 128 #pybitcointools bug

    priv_wif = encode_privkey(priv, 'wif_compressed', vbyte=priv_byte)
    if password:
        priv_wif = bip38_encrypt(priv_wif, password)

    compressed_pub = encode_pubkey(pub, 'hex_compressed')
    ret = {
        'public': {
            'hex_uncompressed': pub,
            'hex': compressed_pub,
            'address': pubtoaddr(compressed_pub, pub_byte)
        },
        'private': {
            'wif': priv_wif
        }
    }
    if not password:
        # only these are valid when no bip38 password is supplied
        ret['private']['hex'] = encode_privkey(priv, 'hex_compressed', vbyte=priv_byte)
        ret['private']['hex_uncompressed'] = encode_privkey(priv, 'hex', vbyte=priv_byte)
        ret['private']['wif_uncompressed'] = encode_privkey(priv, 'wif', vbyte=priv_byte)

    return ret
Ejemplo n.º 3
0
def generate_address(secret_bytes):
    int_privkey = int.from_bytes(secret_bytes, 'big')
    print('privkey (int): {privkey}'.format(privkey=int_privkey))
    wif_not_compressing_privkey = bitcoin.encode_privkey(secret_bytes, 'wif')
    print('privkey (wif, not compressing): {privkey}'.format(
        privkey=wif_not_compressing_privkey))
    wif_compressing_privkey = bitcoin.encode_privkey(secret_bytes,
                                                     'wif_compressed')
    print('privkey (wif, compressing): {privkey}'.format(
        privkey=wif_compressing_privkey))
    print()

    public_key = bitcoin.fast_multiply(bitcoin.G, int_privkey)
    print('pubkey pair (int): {pubkey}'.format(pubkey=public_key))
    pubkey_not_compressed = bitcoin.encode_pubkey(public_key, 'hex')
    print('pubkey (not compressed, hex): {pubkey}'.format(
        pubkey=pubkey_not_compressed))
    pubkey_compressed = bitcoin.encode_pubkey(public_key, 'hex_compressed')
    print(
        'pubkey (compressed, hex): {pubkey}'.format(pubkey=pubkey_compressed))
    address_not_compressed = bitcoin.pubkey_to_address(public_key)
    print('address (not compressed, b58check): {address}'.format(
        address=address_not_compressed))
    address_compressed = bitcoin.pubkey_to_address(pubkey_compressed)
    print('address (compressed, b58check): {address}'.format(
        address=address_compressed))
    return address_compressed
Ejemplo n.º 4
0
def generate_keypair(crypto, seed, password=None):
    """
    Generate a private key and publickey for any currency, given a seed.
    That seed can be random, or a brainwallet phrase.
    """
    pub_byte, priv_byte = get_magic_bytes(crypto)
    priv = sha256(seed)
    pub = privtopub(priv)

    priv_wif = encode_privkey(priv, 'wif_compressed', vbyte=priv_byte)
    if password:
        # pycrypto etc. must be installed or this will raise ImportError, hence inline import.
        from .bip38 import Bip38EncryptedPrivateKey
        priv_wif = str(Bip38EncryptedPrivateKey.encrypt(crypto, priv_wif, password))

    compressed_pub = encode_pubkey(pub, 'hex_compressed')
    ret = {
        'public': {
            'hex_uncompressed': pub,
            'hex': compressed_pub,
            'address': pubtoaddr(compressed_pub, pub_byte)
        },
        'private': {
            'wif': priv_wif
        }
    }
    if not password:
        # only these are valid when no bip38 password is supplied
        ret['private']['hex'] = encode_privkey(priv, 'hex_compressed', vbyte=priv_byte)
        ret['private']['hex_uncompressed'] = encode_privkey(priv, 'hex', vbyte=priv_byte)
        ret['private']['wif_uncompressed'] = encode_privkey(priv, 'wif', vbyte=priv_byte)

    return ret
Ejemplo n.º 5
0
def generate_key():
    #generate a random private key
    valid_private_key = False
    while not valid_private_key:
        private_key = bitcoin.random_key()
        decoded_private_key = bitcoin.decode_privkey(private_key, 'hex')
        valid_private_key = 0 < decoded_private_key < bitcoin.N
    #print ('Private Key (hex) is: ' + private_key)
    #print ('private Key (decimal) is: ' + str(decoded_private_key))

    #convert private key to WIF format
    wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key,
                                                     'wif')
    #print('Private Key (WIF) is: ' + wif_encoded_private_key)

    # Add sufix '01' to indicate a compressed private Key
    compressed_private_key = private_key + '01'
    #print ('Private Key Compressed (hex) is: ' + compressed_private_key)

    # generate a WIF format from the compressed private key (WIF-compressed)
    wif_compressed_private_key = bitcoin.encode_privkey(
        bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif')
    #print ('Private Key (WIF-compressed) is: ' + wif_compressed_private_key)

    # Multiply de EC generator G with the priveate key to get a public key point
    public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key)
    #print ('Public Key (x,y) coordinates are: ' + str(public_key))

    # Encode as hex, prefix 04
    hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex')
    #print ('Public Key (hex) is: ' + hex_encoded_public_key)

    # Compress public key, adjust prefix depending on whether y is even or odd
    (public_key_x, public_key_y) = public_key
    if public_key_y % 2 == 0:
        compressed_prefix = '02'
    else:
        compressed_prefix = '03'
    hex_compressed_public_key = compressed_prefix + bitcoin.encode(
        public_key_x, 16)
    #print ('Compressed Public Key is: ' + hex_compressed_public_key)

    # Generate bitcoin address from public Key
    #print ('Bitcoin Address (b58check) is: ' + bitcoin.pubkey_to_address(public_key))

    # Generate compressedd bitcoin address from compressed public key
    #print ('Compressed Bitcoin Address (b58check) is: ' + bitcoin.pubkey_to_address(hex_compressed_public_key))

    compressed_address_base58check = bitcoin.pubkey_to_address(
        hex_compressed_public_key)

    kson = {
        "wif1": wif_encoded_private_key,
        "wif": wif_compressed_private_key,
        "key": compressed_address_base58check
    }

    return kson
Ejemplo n.º 6
0
def showDetails(mnemonic, passphrase="", i=1):

    myMnemonic = mnemonic
    passphrase = passphrase

    mnemo = Mnemonic('english')
    seed = hexlify(mnemo.to_seed(myMnemonic, passphrase=passphrase))
    print 'Seed:\t\t\t\t', seed

    priv = bitcoin.bip32_master_key(unhexlify(seed))
    print 'Xpriv:\t\t\t\t', priv

    key = bitcoin.encode_privkey(bitcoin.bip32_extract_key(priv),
                                 'wif_compressed')
    print 'Key:\t\t\t\t', key

    pub = bitcoin.bip32_privtopub(priv)
    print 'Derived public key:\t', pub
    pubHex = bitcoin.bip32_extract_key(pub)
    print 'public key (hex):\t', pubHex
    print 'Master Key address:\t', bitcoin.pubtoaddr(pubHex)

    print ""
    print "TREZOR Keys:"

    account = 0
    derivedPrivateKey = bitcoin.bip32_ckd(
        bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44 + HARDENED), HARDENED),
        HARDENED + account)
    print 'Derived private key:', derivedPrivateKey

    privateKey = bitcoin.encode_privkey(
        bitcoin.bip32_extract_key(derivedPrivateKey), 'wif_compressed')
    print 'private key (wif):\t', privateKey

    derivedPublicKey = bitcoin.bip32_privtopub(derivedPrivateKey)
    print 'Derived public key:', derivedPublicKey

    publicKeyHex = bitcoin.privtopub(privateKey)
    print 'public key (hex):\t', publicKeyHex

    address = bitcoin.pubtoaddr(publicKeyHex)
    print 'address:\t\t\t', address

    print ""
    print "Account public keys (XPUB)"
    xpubs = []
    for i in range(0, i):
        derivedPrivateKey = bitcoin.bip32_ckd(
            bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44 + HARDENED),
                              HARDENED), HARDENED + i)
        xpub = bitcoin.bip32_privtopub(derivedPrivateKey)
        print 'Account', i, 'xpub:', xpub
        xpubs.append(xpub)

    return xpubs
Ejemplo n.º 7
0
def showDetails(mnemonic, passphrase="", i=1):

    myMnemonic = mnemonic
    passphrase = passphrase


    mnemo = Mnemonic('english')
    seed = hexlify(mnemo.to_seed(myMnemonic, passphrase=passphrase))
    print 'Seed:\t\t\t\t', seed

    priv = bitcoin.bip32_master_key(unhexlify(seed))
    print 'Xpriv:\t\t\t\t', priv

    key = bitcoin.encode_privkey(bitcoin.bip32_extract_key(priv), 'wif_compressed')
    print 'Key:\t\t\t\t', key


    pub = bitcoin.bip32_privtopub(priv)
    print 'Derived public key:\t', pub
    pubHex = bitcoin.bip32_extract_key(pub)
    print 'public key (hex):\t', pubHex
    print 'Master Key address:\t', bitcoin.pubtoaddr(pubHex)


    print ""
    print "TREZOR Keys:"

    account = 0
    derivedPrivateKey = bitcoin.bip32_ckd(bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44+HARDENED), HARDENED), HARDENED+account)
    print 'Derived private key:', derivedPrivateKey

    privateKey = bitcoin.encode_privkey(bitcoin.bip32_extract_key(derivedPrivateKey), 'wif_compressed')
    print 'private key (wif):\t', privateKey


    derivedPublicKey = bitcoin.bip32_privtopub(derivedPrivateKey)
    print 'Derived public key:', derivedPublicKey

    publicKeyHex = bitcoin.privtopub(privateKey)
    print 'public key (hex):\t', publicKeyHex

    address = bitcoin.pubtoaddr(publicKeyHex)
    print 'address:\t\t\t', address

    print ""
    print "Account public keys (XPUB)"
    xpubs = []
    for i in range(0, i):
        derivedPrivateKey = bitcoin.bip32_ckd(bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44+HARDENED), HARDENED), HARDENED+i)
        xpub = bitcoin.bip32_privtopub(derivedPrivateKey)
        print 'Account', i, 'xpub:', xpub
        xpubs.append(xpub)

    return xpubs
Ejemplo n.º 8
0
def quicktx(client, gasprice, startgas, to, value, data, key):
    """Create and finalize a transaction.

    This command is a shortcut that chains getnonce, mktx, signtx, and applytx.
    It returns the server's response.
    """
    encoded_key = encode_privkey(key, 'hex')
    nonce = int(client.getaccount(utils.privtoaddr(encoded_key))['nonce'])
    tx = Transaction(nonce, gasprice, startgas, to, value, str(data))
    tx.sign(encode_privkey(key, 'hex'))
    pecho(client.applytx(tx))
Ejemplo n.º 9
0
def quicktx(client, gasprice, startgas, to, value, data, key):
    """Create and finalize a transaction.

    This command is a shortcut that chains getnonce, mktx, signtx, and applytx.
    It returns the server's response.
    """
    encoded_key = encode_privkey(key, 'hex')
    nonce = int(client.getaccount(utils.privtoaddr(encoded_key))['nonce'])
    tx = Transaction(nonce, gasprice, startgas, to, value, str(data))
    tx.sign(encode_privkey(key, 'hex'))
    pecho(client.applytx(tx))
Ejemplo n.º 10
0
def bip38_decrypt(encrypted_privkey, passphrase, wif=False):
    """
    BIP0038 non-ec-multiply decryption. Returns hex privkey.
    """
    passphrase = normalize('NFC', unicode(passphrase))
    if is_py2:
        passphrase = passphrase.encode('utf8')

    d = unhexlify(changebase(encrypted_privkey, 58, 16, 86))

    d = d[2:]
    flagbyte = d[0:1]
    d = d[1:]
    # respect flagbyte, return correct pair

    if flagbyte == b'\xc0':
        compressed = False
    if flagbyte == b'\xe0':
        compressed = True

    addresshash = d[0:4]
    d = d[4:-4]
    key = scrypt.hash(passphrase,addresshash, 16384, 8, 8)
    derivedhalf1 = key[0:32]
    derivedhalf2 = key[32:64]
    encryptedhalf1 = d[0:16]
    encryptedhalf2 = d[16:32]
    aes = AES.new(derivedhalf2)
    decryptedhalf2 = aes.decrypt(encryptedhalf2)
    decryptedhalf1 = aes.decrypt(encryptedhalf1)
    priv = decryptedhalf1 + decryptedhalf2
    priv = unhexlify('%064x' % (long(hexlify(priv), 16) ^ long(hexlify(derivedhalf1), 16)))
    pub = privtopub(priv)
    if compressed:
        pub = encode_pubkey(pub,'hex_compressed')
    addr = pubtoaddr(pub)

    if is_py2:
        ascii_key = addr
    else:
        ascii_key = bytes(addr,'ascii')

    if sha256(sha256(ascii_key).digest()).digest()[0:4] != addresshash:
        raise Exception('Bip38 password decrypt failed: Wrong password?')
    else:
        formatt = 'wif' if wif else 'hex'
        if compressed:
            return encode_privkey(priv, formatt + '_compressed')
        else:
            return encode_privkey(priv, formatt)
Ejemplo n.º 11
0
def demo_generate_private_key():
    # 生成一个用十六进制表示的长 256 位的私钥(str类型)
    private_key = bitcoin.random_key()
    # 解码为十进制的整形密钥
    decoded_private_key = bitcoin.decode_privkey(private_key, 'hex')
    if not 0 < decoded_private_key < bitcoin.N:
        return demo_generate_private_key()

    # 用 WIF 格式编码密钥
    wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif')
    # 用 01 标识的压缩密钥
    compressed_private_key = private_key + '01'
    # 生成 WIF的压缩格式
    wif_compressed_private_key = bitcoin.encode_privkey(bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif')
    return private_key, decoded_private_key, wif_encoded_private_key, compressed_private_key, wif_compressed_private_key
Ejemplo n.º 12
0
def _do_config_set(args):
    """Executes the 'set' subcommand.  Given a key file, and a series of
    key/value pairs, it generates batches of sawtooth_config transactions in a
    BatchList instance, and stores it in a file.
    """
    settings = [s.split('=', 1) for s in args.setting]

    with open(args.key, 'r') as key_file:
        wif_key = key_file.read().strip()
        signing_key = bitcoin.encode_privkey(
            bitcoin.decode_privkey(wif_key, 'wif'), 'hex')
        pubkey = bitcoin.encode_pubkey(bitcoin.privkey_to_pubkey(signing_key),
                                       'hex')

    txns = [
        _create_config_txn(pubkey, signing_key, setting)
        for setting in settings
    ]
    txn_ids = [txn.header_signature for txn in txns]

    batch_header = BatchHeader(signer_pubkey=pubkey,
                               transaction_ids=txn_ids).SerializeToString()

    batch = Batch(header=batch_header,
                  header_signature=bitcoin.ecdsa_sign(batch_header,
                                                      signing_key),
                  transactions=txns)

    batch_list = BatchList(batches=[batch]).SerializeToString()

    try:
        with open(args.output, 'wb') as batch_file:
            batch_file.write(batch_list)
    except:
        raise CliException('Unable to write to {}'.format(args.output))
Ejemplo n.º 13
0
 def encode(private_value):
     """
     Encode the decimal number private_value to base58
     """
     private_value_hex = bitcoin.encode_privkey(private_value, "hex")
     private_value_base58 = base58.b58encode(bytes.fromhex(private_value_hex))
     return private_value_base58
Ejemplo n.º 14
0
 def __init__(self, PrivateKey = None):
     if PrivateKey == None:
         print("THERE WAS NO PRIVATE KEY GIVEN AS ARGUMENT \n")
         raise
     else:
         self.private_key = PrivateKey
     try:
         self.decoded_private_key = bitcoin.decode_privkey(self.private_key, 'hex')
     except Exception as e:
         pass  
       #creates decimal of private key  - this function turns it into either decimal or hex
     check = self.checkIfPrivateKeyIsValid();
     if check:
         print("Valid Private Key \n")
         self.wif_encoded_private_key = bitcoin.encode_privkey(self.decoded_private_key, 'wif')
         # GENERATE PUBLIC KEYS
         self.public_key = bitcoin.privkey_to_pubkey(self.private_key) # located in files
         # self.bitcoinAddress = bitcoin.pubkey_to_address(self.public_key)
         # 
         # 
         # self.public_key_f_m = bitcoin.fast_multiply(bitcoin.G, self.decoded_private_key)
         # self.hex_encoded_public_key = bitcoin.encode_pubkey(self.public_key_f_m, 'hex')    
         # 
         # self.hex_compressed_public_key = self.generateHexCompressedPublicKey(self.public_key_f_m)
         # self.bitcoinAddress2 = bitcoin.pubkey_to_address(self.public_key_f_m)
         # self.compressedBitcoinAddress = bitcoin.pubkey_to_address(self.hex_compressed_public_key.encode('utf-8'))
         
             
     else:
         print(" Invalid Private Key Check Failed!!! \n")
Ejemplo n.º 15
0
 def to_wif(self):
     if self._compressed:
         return encode_privkey(self._ecdsa_private_key.to_string(),
                               'wif_compressed')
     else:
         return b58check_encode(self.to_bin().hex(),
                                version_byte=self.wif_version_byte())
Ejemplo n.º 16
0
def becies_encode(ephemeral_pubkey,
                  ciphertext,
                  tag,
                  pubkeys=[],
                  num_to_activate=None,
                  offsets=None):
    bout = BECIES_MAGIC_BYTES  #0xc66b20 3-byte prefix?  (encodes to xmsg in base64)

    isaddresses = bool(pubkeys)
    isgroup = bool(offsets)
    #a vli indicating the header contents flags.
    #offsets,and addresses are first two bits, rest are unused
    bout += _to_vli(
        int(isgroup) * BECIES_GROUP_FLAG +
        int(isaddresses) * BECIES_ADDRESSES_FLAG)
    if (isaddresses):
        bout += _to_vli(len(pubkeys))
        bout += ''.join(
            [bitcoin.b58check_to_bin(bitcoin.pubtoaddr(p)) for p in pubkeys])
    if (isgroup):
        bout += _to_vli(
            num_to_activate)  #todo, num_to_activate must be strictly positive
        bout += _to_vli(len(offsets))
        bout += ''.join([bitcoin.encode_privkey(priv) for priv in offsets])

    bout += bitcoin.encode_pubkey(ephemeral_pubkey, 'bin_compressed')
    bout += _to_vli(len(ciphertext))
    bout += ciphertext
    bout += tag  #this has to come last for streaming mode too
    return bout
Ejemplo n.º 17
0
 def encode(private_value):
     """
     Encode the decimal number private_value to base58
     """
     private_value_hex = bitcoin.encode_privkey(private_value, 'hex')
     private_value_base58 = base58.b58encode(bytes.fromhex(private_value_hex))
     return private_value_base58
Ejemplo n.º 18
0
def derive_keypairs(hd_key, keys=3):
    keypairs = []    
    for i in range(keys):
        privkey = encode_privkey(bip32_descend(hd_key, [i]), 'hex')
        addr = decode_addr(ethereum.keys.privtoaddr(privkey)).decode('utf-8')
        keypairs.append((privkey, addr))
    return keypairs
Ejemplo n.º 19
0
def run():
    global num_btc_wallets_searched
    # while True:
    valid_private_key = False
    while not valid_private_key:
        private_key = bitcoin.random_key()
        decoded_private_key = bitcoin.decode_privkey(private_key, 'hex')
        valid_private_key = 0 < decoded_private_key < bitcoin.N

    wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key,
                                                     'wif')
    public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key)
    num_btc_wallets_searched += 1
    r = requests.get("https://blockchain.info/q/getsentbyaddress/" +
                     bitcoin.pubkey_to_address(public_key))
    sys.stdout.flush()
    print("Number of BTC wallets searched:         " +
          str(num_btc_wallets_searched),
          end='\r')
    print_pub_key = str(bitcoin.pubkey_to_address(public_key))
    print_priv_key = str(wif_encoded_private_key)
    print_bal = str(r.text)
    if int(r.text) > 0:
        sys.stdout.flush()
        print()
        print("Bitcoin Address is:", bitcoin.pubkey_to_address(public_key))
        print("Private Key is: ", wif_encoded_private_key)
        print("Balance is: ", r.text)
        send_email(print_pub_key, print_priv_key, print_bal)
        exit(0)
Ejemplo n.º 20
0
 def to_wif(self):
     if self._compressed:
         return encode_privkey(
             self._ecdsa_private_key.to_string(), 'wif_compressed')
     else:
         return b58check_encode(
             self.to_bin(), version_byte=self.wif_version_byte())
Ejemplo n.º 21
0
def test_priv_encode():
    key = random_privkey()
    encoded = encode_privkey(key)
    ans = bitcoin.encode_privkey(key.value, 'wif_compressed')
    t1 = base58.b58decode(ans)
    t2 = base58.b58decode(encoded)
    assert t1 == t2
    assert encoded == ans
Ejemplo n.º 22
0
def privtoaddr(key):
    """Derive an address from a private key.

    KEY must either be a raw private key in hex encoding or a WIF string.

    The resulting address will be printed in hex encoding.
    """
    click.echo(utils.privtoaddr(encode_privkey(key, 'hex')))
Ejemplo n.º 23
0
def sarah(hexli):
    private_key = hexli
    decoded_private_key = bitcoin.decode_privkey(private_key, 'hex')
    wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif')
    compressed_private_key = private_key + '01'
    wif_compressed_private_key = bitcoin.encode_privkey(bitcoin.decode_privkey(private_key, 'hex'), 'wif_compressed')
    public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key)
    hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex')
    (public_key_x, public_key_y) = public_key
    if public_key_y % 2 == 0:
      compressed_prefix = '02'
    else:
      compressed_prefix = '03'
    hex_compressed_public_key = compressed_prefix + bitcoin.encode(public_key_x, 16)
    non_compressed_adress = bitcoin.pubkey_to_address(public_key)
    compressed_address = bitcoin.pubkey_to_address(hex_compressed_public_key.encode("utf8"))
    return non_compressed_adress, compressed_address, wif_encoded_private_key, wif_compressed_private_key, private_key
Ejemplo n.º 24
0
def _get_wallet_sha256():
    for i in w:
        HEX=btc.encode_privkey(btc.sha256(str(i)),"hex")
        addr=btc.privtoaddr(HEX)
        if(addr==match):
            print(WIF)
        else:
           print(addr)
Ejemplo n.º 25
0
def privtoaddr(key):
    """Derive an address from a private key.

    KEY must either be a raw private key in hex encoding or a WIF string.

    The resulting address will be printed in hex encoding.
    """
    click.echo(utils.privtoaddr(encode_privkey(key, 'hex')))
Ejemplo n.º 26
0
 def read_wallet_file_data(self, filename):
     self.path = None
     self.index_cache = [[0, 0]] * self.max_mix_depth
     path = os.path.join('wallets', filename)
     if not os.path.isfile(path):
         if get_network() == 'testnet':
             log.debug('filename interpreted as seed, only available in '
                       'testnet because this probably has lower entropy')
             return filename
         else:
             raise IOError('wallet file not found')
     self.path = path
     fd = open(path, 'r')
     walletfile = fd.read()
     fd.close()
     walletdata = json.loads(walletfile)
     if walletdata['network'] != get_network():
         print ('wallet network(%s) does not match '
                'joinmarket configured network(%s)' % (
             walletdata['network'], get_network()))
         sys.exit(0)
     if 'index_cache' in walletdata:
         self.index_cache = walletdata['index_cache']
     decrypted = False
     while not decrypted:
         password = getpass('Enter wallet decryption passphrase: ')
         password_key = btc.bin_dbl_sha256(password)
         encrypted_seed = walletdata['encrypted_seed']
         try:
             decrypted_seed = decryptData(
                     password_key,
                     encrypted_seed.decode('hex')).encode('hex')
             # there is a small probability of getting a valid PKCS7
             # padding by chance from a wrong password; sanity check the
             # seed length
             if len(decrypted_seed) == 32:
                 decrypted = True
             else:
                 raise ValueError
         except ValueError:
             print('Incorrect password')
             decrypted = False
     if self.storepassword:
         self.password_key = password_key
         self.walletdata = walletdata
     if 'imported_keys' in walletdata:
         for epk_m in walletdata['imported_keys']:
             privkey = decryptData(
                     password_key,
                     epk_m['encrypted_privkey'].decode( 'hex')).encode('hex')
             privkey = btc.encode_privkey(privkey, 'hex_compressed')
             if epk_m['mixdepth'] not in self.imported_privkeys:
                 self.imported_privkeys[epk_m['mixdepth']] = []
             self.addr_cache[btc.privtoaddr(
                     privkey, get_p2pk_vbyte())] = (epk_m['mixdepth'], -1,
                 len(self.imported_privkeys[epk_m['mixdepth']]))
             self.imported_privkeys[epk_m['mixdepth']].append(privkey)
     return decrypted_seed
Ejemplo n.º 27
0
 def from_wif(wif):
     """Decodes a PrivateKey from a wif-encoded string
     """
     try:
         priv = pybitcointools.encode_privkey(wif, 'hex')
         priv = binascii.unhexlify(priv)
         return Secp256k1PrivateKey(secp256k1.PrivateKey(priv, ctx=__CTX__))
     except Exception as e:
         raise ParseError('Unable to parse wif key: {}'.format(e))
Ejemplo n.º 28
0
def generate_keypair(crypto, seed, password=None):
    """
    Generate a private key and publickey for any currency, given a seed.
    That seed can be random, or a brainwallet phrase.
    """
    if crypto in ['eth', 'etc']:
        raise CurrencyNotSupported("Ethereums not yet supported")

    pub_byte, priv_byte = get_magic_bytes(crypto)
    priv = sha256(seed)
    pub = privtopub(priv)

    priv_wif = encode_privkey(priv, 'wif_compressed', vbyte=priv_byte)
    if password:
        # pycrypto etc. must be installed or this will raise ImportError, hence inline import.
        from .bip38 import Bip38EncryptedPrivateKey
        priv_wif = str(
            Bip38EncryptedPrivateKey.encrypt(crypto, priv_wif, password))

    compressed_pub = encode_pubkey(pub, 'hex_compressed')
    ret = {
        'public': {
            'hex_uncompressed': pub,
            'hex': compressed_pub,
            'address': pubtoaddr(compressed_pub, pub_byte)
        },
        'private': {
            'wif': priv_wif
        }
    }
    if not password:
        # only these are valid when no bip38 password is supplied
        ret['private']['hex'] = encode_privkey(priv,
                                               'hex_compressed',
                                               vbyte=priv_byte)
        ret['private']['hex_uncompressed'] = encode_privkey(priv,
                                                            'hex',
                                                            vbyte=priv_byte)
        ret['private']['wif_uncompressed'] = encode_privkey(priv,
                                                            'wif',
                                                            vbyte=priv_byte)

    return ret
Ejemplo n.º 29
0
def getPrivKey(xpriv, i):
    privkeys = {}
    priv0 = bitcoin.bip32_ckd(xpriv, 0)

    privateKey = bitcoin.bip32_ckd(priv0, i)
    wifKey = bitcoin.encode_privkey(bitcoin.bip32_extract_key(privateKey), 'wif_compressed')
    address_fromPriv =  bitcoin.privtoaddr(wifKey)
    privkeys[address_fromPriv] = wifKey

    return privkeys
Ejemplo n.º 30
0
def get_key_pair():
    v = False
    while not v:
        private_key = bitcoin.random_key()
        private_key = bitcoin.decode_privkey(private_key)
        v = 0 < private_key < bitcoin.N
    wif_private_key = bitcoin.encode_privkey(private_key, 'wif')
    public_key = bitcoin.privkey_to_pubkey(wif_private_key)
    address = bitcoin.pubkey_to_address(public_key)
    return address, wif_private_key
Ejemplo n.º 31
0
def function_keys():

    valid_private_key = False  #randomize private key

    while not valid_private_key:
        private_key = bitcoin.random_key()
        decode_private_key = bitcoin.decode_privkey(private_key, 'hex')
        valid_private_key = 0 < decode_private_key < bitcoin.N

    print "Private Key (hex) is:", private_key
    print "Private Key (decimal) is:", decode_private_key
    wif_encode_private_key = bitcoin.encode_privkey(decode_private_key, 'wif')
    print "Private key (WIF) is:", wif_encode_private_key  # convert private key to wif format

    compressed_private_key = private_key + '01'
    print "Private key Compressed (hex) is:", compressed_private_key  # add '01' to indicate compressed private key

    wif_compressed_private_key = bitcoin.encode_privkey(
        bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif')
    print "Private Key (Wif-compressed) is:", wif_compressed_private_key

    public_key = bitcoin.fast_multiply(
        bitcoin.G, decode_private_key
    )  # multiply EC generator with the private key to have public key point
    print "Public Key (x, y) coordinates is:", public_key

    hex_encoded_public_key = bitcoin.encode_pubkey(
        public_key, 'hex')  # encoded public key with '04'
    print "Public Key (hex) is:", hex_encoded_public_key

    (public_key_x, public_key_y) = public_key  # compressed public key
    if (public_key_y % 2) == 0:
        compressed_prefix = '02'
    else:
        compressed_prefix = '03'
        hex_compressed_public_key = compressed_prefix + bitcoin.encode(
            public_key_x, 16)
    print "Compressed Public Key (hex) is:", hex_compressed_public_key
    print "Bitcoin Address (b58check) is:", bitcoin.pubkey_to_address(
        public_key)

    print "Compressed Bitcoin Address (b58check) is:", bitcoin.pubkey_to_address(
        hex_compressed_public_key)
Ejemplo n.º 32
0
def privkey_valid(privkey):
    try:
        pk = bitcoin.decode_privkey(privkey, 'wif')
        pkhex = bitcoin.encode_privkey(pk, 'hex')
        if len(pkhex) in (62, 64):
            return True
        else:
            return False
    except Exception as e:
        return False
def privkey_valid(privkey):
    try:
        pk = bitcoin.decode_privkey(privkey, 'wif')
        pkbin = bytes.fromhex(bitcoin.encode_privkey(pk, 'hex'))
        if len(pkbin) == 32 or (len(pkbin) == 33 and pkbin[-1] == 1):
            return True
        else:
            return False
    except Exception as e:
        return False
Ejemplo n.º 34
0
def Check1000k_address(start_private_key, Num):
    global guessNum
    private_key = deepcopy(start_private_key)
    # private_key=26563230048437957592232553826663696440606756685920117476832299673293013768870
    startkey = deepcopy(start_private_key)
    while private_key < 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141:
        random_private_key = Generate_random_private_key()
        random_addresss = from_private_key_to_address(random_private_key)
        private_key += 1
        guessNum += 1
        PrivateKey_WIF = bitcoin.encode_privkey(private_key, 'wif')
        compressed_private_key = bitcoin.encode_privkey(private_key,
                                                        'hex') + '01'
        PrivateKey_WIF_Compressed = bitcoin.encode_privkey(
            bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif')
        bitcoin_address = bitcoin.privkey_to_address(PrivateKey_WIF)
        compressed_bitcoin_address = bitcoin.privkey_to_address(
            PrivateKey_WIF_Compressed)
        addresss = [
            bitcoin_address, compressed_bitcoin_address, random_addresss[0],
            random_addresss[1]
        ]
        for address in addresss:
            try:
                balance = querybalainceV3(address)
            except:
                print 'failed to query private_key %s ,address %s' % (
                    private_key, address)
                add_unquery_address_to_log(private_key, address)
                continue
            time.sleep(0.5)
            #balance = querybalance('1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa')
            if int(balance) > 0:
                print 'private_key %s has %s BTC' % (private_key, balance)
                add_query_address_has_btc(private_key, address)
                linestring = 'private_key %s has %s BTC !' % (private_key,
                                                              balance)
                smtp.send_BTCmail(linestring)
        print "Check %s private_key %s " % (str(guessNum), private_key)
        if private_key == startkey + Num:
            add_query_address_has_btc(private_key, Num)
            break
Ejemplo n.º 35
0
def key_address(masterkey, path):
    """Compute address and private key (hex) for path"""

    derived_key = descend(masterkey, path)
    priv_key = btc.bip32_deserialize(derived_key)[-1]
    pub_key = btc.bip32_extract_key(btc.bip32_privtopub(derived_key))
    priv_key_hex = btc.encode_privkey(
        btc.decode_privkey(priv_key, 'bin_compressed'), 'hex')
    address = btc.pubkey_to_address(pub_key)

    return priv_key_hex, address
Ejemplo n.º 36
0
def main(args):
    hex_decoded_pk, decimal_decoded_pk = generate_private_key()
    print("Private key (hex): {0}.".format(hex_decoded_pk))
    print("Private key (decimal): {0}.".format(decimal_decoded_pk))

    wif_encoded_pk = bitcoin.encode_privkey(decimal_decoded_pk, 'wif')
    print("Private key (wif): {0}.".format(wif_encoded_pk))

    compressed_hex_decoded_pk = hex_decoded_pk + '01'
    print(
        "Compressed private key (hex): {0}.".format(compressed_hex_decoded_pk))
Ejemplo n.º 37
0
def bip38_encrypt(privkey, passphrase):
    """
    BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey.
    """
    privformat = get_privkey_format(privkey)
    if privformat in ['wif_compressed','hex_compressed']:
        compressed = True
        flagbyte = b'\xe0'
        if privformat == 'wif_compressed':
            privkey = encode_privkey(privkey,'hex_compressed')
            privformat = get_privkey_format(privkey)
    if privformat in ['wif', 'hex']:
        compressed = False
        flagbyte = b'\xc0'
    if privformat == 'wif':
        privkey = encode_privkey(privkey,'hex')
        privformat = get_privkey_format(privkey)

    pubkey = privtopub(privkey)
    addr = pubtoaddr(pubkey)

    passphrase = normalize('NFC', unicode(passphrase))
    if is_py2:
        ascii_key = addr
        passphrase = passphrase.encode('utf8')
    else:
        ascii_key = bytes(addr,'ascii')

    salt = sha256(sha256(ascii_key).digest()).digest()[0:4]
    key = scrypt.hash(passphrase, salt, 16384, 8, 8)
    derivedhalf1, derivedhalf2 = key[:32], key[32:]

    aes = AES.new(derivedhalf2)
    encryptedhalf1 = aes.encrypt(unhexlify('%0.32x' % (long(privkey[0:32], 16) ^ long(hexlify(derivedhalf1[0:16]), 16))))
    encryptedhalf2 = aes.encrypt(unhexlify('%0.32x' % (long(privkey[32:64], 16) ^ long(hexlify(derivedhalf1[16:32]), 16))))

    payload = b'\x01' + b'\x42' + flagbyte + salt + encryptedhalf1 + encryptedhalf2
    checksum   = sha256(sha256(payload).digest()).digest()[:4] # b58check for encrypted privkey
    privatkey  = hexlify(payload + checksum).decode('ascii')
    return changebase(privatkey, 16, 58)
Ejemplo n.º 38
0
def key_data(privkey):
    priv_key = encode_privkey(privkey, 'hex')
    # PRIVATE! SIGNING KEY ECDSA.SECP256k1
    sk = ecdsa.SigningKey.from_string(bytearray.fromhex(priv_key),
                                      curve=ecdsa.SECP256k1)
    # PUBLIC! VERIFYING KEY (64 BYTE LONG, MISSING 04 BYTE AT THE BEGINNING)
    vk = sk.verifying_key
    # FULL PUBLIC KEY
    # add 04 byte at the beginning
    pub_key = str(binascii.hexlify(b'\04' + vk.to_string()).decode())
    pid = os.getpid()
    wif_key = str(hex2wif(priv_key).decode())
    return priv_key, pub_key, pid, wif_key
 def checkBitcoinGeneratorFromInteger(self, numberToCheck):
     privateKeyHex = bitcoin.encode_privkey(numberToCheck, 'hex')
     generator = BitcoinKeyGenerator(privateKeyHex)
     print( json.dumps(generator.__dict__) )
     # CHECK PUBLIC KEYS
     
     try:
         publicKey = generator.public_key
         check = self.checkList(publicKey)
         # if public keys match one of the keys on the list, save/send all public/private key formats
         match = self.saveIfMatch(check, generator) 
         del generator
     except Exception as e:
         print(e)
Ejemplo n.º 40
0
def quickcontract(client, gasprice, startgas, value, code, key):
    """Create and finalize a contract.

    This command is a shortcut that chains getnonce, mkcontract, signtx, and
    applytx. In addition to the server's response, it returns the address of
    the newly created contract.
    """
    encoded_key = encode_privkey(key, 'hex')
    sender = utils.privtoaddr(encoded_key)
    nonce = int(client.getaccount(sender)['nonce'])
    tx = contract(nonce, gasprice, startgas, value, str(code))
    tx.sign(encoded_key)
    response = client.applytx(tx)
    pecho({'address': tx.contract_address(), 'transaction': response})
Ejemplo n.º 41
0
def quickcontract(client, gasprice, startgas, value, code, key):
    """Create and finalize a contract.

    This command is a shortcut that chains getnonce, mkcontract, signtx, and
    applytx. In addition to the server's response, it returns the address of
    the newly created contract.
    """
    encoded_key = encode_privkey(key, 'hex')
    sender = utils.privtoaddr(encoded_key)
    nonce = int(client.getaccount(sender)['nonce'])
    tx = contract(nonce, gasprice, startgas, value, str(code))
    tx.sign(encoded_key)
    response = client.applytx(tx)
    pecho({
        'address': tx.contract_address(),
        'transaction': response})
Ejemplo n.º 42
0
def __check_valid(k):
    #get raw priv key:
    decode_private_key = bitcoin.decode_privkey(k)
    if decode_private_key >= bitcoin.N:
        return None
    #get compressed priv key:
    compressed_private_key = bitcoin.encode_privkey(decode_private_key,
                                                    "hex_compressed")

    #get raw addr & compressed addr
    addr_raw = bitcoin.privkey_to_address(decode_private_key)
    addr_comp = bitcoin.privkey_to_address(compressed_private_key)

    if addr_raw == target_addr or addr_comp == target_addr:
        print(f"FOUND ONE!!!! PRIVATE KEY IS: {hex(decode_private_key)}")
        return hex(decode_private_key)
Ejemplo n.º 43
0
def signtx(transaction, key):
    """Sign a previously created transaction.

    TRANSACTION must be the hex encoded transaction, as for instance created
    using mktx or mkcontract. If it has already been signed before, its
    signature will be replaced.

    KEY must be the private key to sign with, in hexadecimal encoding or WIF.

    The signed transaction will be printed in hex encoding.
    """
    try:
        tx = Transaction.deserialize(str(transaction))
    except AssertionError:
        raise click.BadParameter('Unable to deserialize TRANSACTION.')
    tx.sign(encode_privkey(key, 'hex'))
    click.echo(tx.hex_serialize(True))
Ejemplo n.º 44
0
    def __init__(self, private_key=None, compressed=False):
        """ Takes in a private key/secret exponent.
        """
        self._compressed = compressed
        if not private_key:
            secret_exponent = random_secret_exponent(self._curve.order)
        else:
            secret_exponent = encode_privkey(private_key, 'decimal')
            if get_privkey_format(private_key).endswith('compressed'):
                self._compressed = True

        # make sure that: 1 <= secret_exponent < curve_order
        if not is_secret_exponent(secret_exponent, self._curve.order):
            raise IndexError(_errors["EXPONENT_OUTSIDE_CURVE_ORDER"])

        self._ecdsa_private_key = ecdsa.keys.SigningKey.from_secret_exponent(
            secret_exponent, self._curve, self._hash_function
        )
Ejemplo n.º 45
0
def test_blockr_sync(setup_blockr, net, seed, gaplimit, showprivkey, method):
    jm_single().config.set("BLOCKCHAIN", "network", net)
    wallet = Wallet(seed, max_mix_depth = 5)
    jm_single().bc_interface.sync_wallet(wallet)
    
    #copy pasted from wallet-tool; some boiled down form of
    #this should really be in wallet.py in the joinmarket module.
    def cus_print(s):
            print s

    total_balance = 0
    for m in range(wallet.max_mix_depth):
        cus_print('mixing depth %d m/0/%d/' % (m, m))
        balance_depth = 0
        for forchange in [0, 1]:
            cus_print(' ' + ('external' if forchange == 0 else 'internal') +
                      ' addresses m/0/%d/%d/' % (m, forchange))

            for k in range(wallet.index[m][forchange] + gaplimit):
                addr = wallet.get_addr(m, forchange, k)
                balance = 0.0
                for addrvalue in wallet.unspent.values():
                    if addr == addrvalue['address']:
                        balance += addrvalue['value']
                balance_depth += balance
                used = ('used' if k < wallet.index[m][forchange] else ' new')
                if showprivkey:
                    if btc.secp_present:
                        privkey = btc.wif_compressed_privkey(
                    wallet.get_key(m, forchange, k), get_p2pk_vbyte())
                    else:
                        privkey = btc.encode_privkey(wallet.get_key(m,
                                forchange, k), 'wif_compressed', get_p2pk_vbyte())
                else:
                    privkey = ''
                if (method == 'displayall' or balance > 0 or
                    (used == ' new' and forchange == 0)):
                    cus_print('  m/0/%d/%d/%03d %-35s%s %.8f btc %s' %
                              (m, forchange, k, addr, used, balance / 1e8,
                               privkey))
        total_balance += balance_depth
        print('for mixdepth=%d balance=%.8fbtc' % (m, balance_depth / 1e8))
    assert total_balance == 96143257    
Ejemplo n.º 46
0
    def get_signing_key(self, contract_id):
        # Get BIP32 child signing key for this order id
        rows = self.db_connection.select_entries("keystore", {
            'contract_id': contract_id
        })

        if len(rows):
            key_id = rows[0]['id']

            settings = self.get_settings()

            wallet = bitcoin.bip32_ckd(bitcoin.bip32_master_key(settings.get('bip32_seed')), 1)
            wallet_chain = bitcoin.bip32_ckd(wallet, 0)
            bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, key_id)
            # bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv)
            return bitcoin.encode_privkey(bitcoin.bip32_extract_key(bip32_identity_priv), 'wif')

        else:
            self.log.error('No keys found for that contract id: #%s', contract_id)
            return
Ejemplo n.º 47
0
def main():
    ''' Our main function. '''

    if os.path.isfile(SECRET_FILE):
        print('It seems you have already created the keys.')
        return 1

    priv = bitcoin.encode_privkey(bitcoin.random_key(), 'wif')
    with open(SECRET_FILE, 'w') as secret_file:
        secret_file.write(priv)

    pub = bitcoin.privtopub(priv)
    with open(PUBLIC_FILE, 'w') as public_file:
        public_file.write(pub)

    address = bitcoin.pubtoaddr(pub, 0)
    with open(ADDRESS_FILE, 'w') as addres_file:
        addres_file.write(address)

    print('Generated {} and {}'.format(SECRET_FILE, PUBLIC_FILE))
    print('Keep {} safe and back it up. Hint: Use scrypt to encrypt the key.'.format(SECRET_FILE))
    print('Send BTC to {}'.format(address))

    return 0
Ejemplo n.º 48
0
    def sign(self, key):
        """Sign this transaction with a private key.

        A potentially already existing signature would be overridden.
        """
        if key in (0, '', b'\x00' * 32, '0' * 64):
            raise InvalidTransaction("Zero privkey cannot sign")
        rawhash = utils.sha3(rlp.encode(self, UnsignedTransaction))

        if len(key) == 64:
            # we need a binary key
            key = encode_privkey(key, 'bin')

        pk = PrivateKey(key, raw=True)
        signature = pk.ecdsa_recoverable_serialize(
            pk.ecdsa_sign_recoverable(rawhash, raw=True)
        )
        signature = signature[0] + utils.bytearray_to_bytestr([signature[1]])
        self.v = utils.safe_ord(signature[64]) + 27
        self.r = big_endian_to_int(signature[0:32])
        self.s = big_endian_to_int(signature[32:64])

        self.sender = utils.privtoaddr(key)
        return self
Ejemplo n.º 49
0
import ecdsa
import bitcoin

# Generate a random private key
valid_private_key = False
while not valid_private_key:
    private_key = bitcoin.random_key()
    decoded_private_key = bitcoin.decode_privkey(private_key, 'hex')
    valid_private_key = 0 < decoded_private_key < bitcoin.N

print "Private Key (hex) is: ", private_key
print "Private Key (decimal) is: ", decoded_private_key

# Convert private key to WIF format
wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif')
print "Private Key (WIF) is: ", wif_encoded_private_key 

# Add suffix "01" to indicate a compressed private key
compressed_private_key = private_key + '01'
print "Private Key Compressed (hex) is: ", compressed_private_key

# Generate a WIF format from the compressed private key (WIF-compressed)
# Add a comment line
# Add a comment line
# Generate a WIF format from the compressed private key (WIF-compressed)
Ejemplo n.º 50
0
 text += each_file+' '+sha256file+'\n' 
 if not quiet:
  sys.stdout.write(text)
 if stamp:
  logfile.write(text)
 data = sha256file
 text = ''

sha2564files = data

if burn:
 payto_addr = bitcoin.pubtoaddr(sha2564files)
else:
 priv = sha2564files 
 privb58 = bitcoin.encode_privkey(priv,'wif')
 pub = bitcoin.privtopub(priv)
 payto_addr = bitcoin.pubtoaddr(pub)

text += format(bytes)+' Bytes processed\n' 
text += '*sha256 refers to SHA-2/Secure Hash Algorithm 2, NIST Standard FIPS PUB 180-2\n\n'
text += 'sha256 hash value (hex)      = '+sha2564files
if burn:
 text += '\n... is used as public key ...\n'
else:
 text += '\n... is used as private key ...\n'
 text += 'Bitcoin private key (hex)    = '+priv+'\n'
 text += 'Bitcoin private key (Base58) = '+privb58
 text += '\n... deriving Bitcoin address form pivate key ...\n'

text +=  'Bitcoin Address (Base 58)    = '+payto_addr+'\n'
Ejemplo n.º 51
0
                      ' addresses m/0/%d/%d' % (m, forchange) + ' ' + xpub_key)

            for k in range(wallet.index[m][forchange] + options.gaplimit):
                addr = wallet.get_addr(m, forchange, k)
                balance = 0.0
                for addrvalue in wallet.unspent.values():
                    if addr == addrvalue['address']:
                        balance += addrvalue['value']
                balance_depth += balance
                used = ('used' if k < wallet.index[m][forchange] else ' new')
                if options.showprivkey:
                    if btc.secp_present:
                        privkey = btc.wif_compressed_privkey(
                    wallet.get_key(m, forchange, k), get_p2pk_vbyte())
                    else:
                        privkey = btc.encode_privkey(wallet.get_key(m,
                                forchange, k), 'wif_compressed', get_p2pk_vbyte())
                else:
                    privkey = ''
                if (method == 'displayall' or balance > 0 or
                    (used == ' new' and forchange == 0)):
                    cus_print('  m/0/%d/%d/%03d %-35s%s %.8f btc %s' %
                              (m, forchange, k, addr, used, balance / 1e8,
                               privkey))
        if m in wallet.imported_privkeys:
            cus_print(' import addresses')
            for privkey in wallet.imported_privkeys[m]:
                addr = btc.privtoaddr(privkey, magicbyte=get_p2pk_vbyte())
                balance = 0.0
                for addrvalue in wallet.unspent.values():
                    if addr == addrvalue['address']:
                        balance += addrvalue['value']
Ejemplo n.º 52
0
# Set DEBUG variable for testing purposes (changing styling)
# If true, prints the SCAD to the terminal and then breaks after first generation
DEBUG = False

# Generate the addresses
if args.copies < 1:
	print("Please enter a valid number of copies (-co flag), and try again.")
	sys.exit()
else: # Use an else statement here just in case we add the option to import a CSV file with the keys (generated somewhere else)
	walletDataList = []
	for i in range(args.copies):
		thisData = {}

		# Generate the addresses with keys
		thisData["privateKey"] = bitcoin.main.random_key() # Secure: uses random library, time library and proprietary function
		thisData["wif"] = bitcoin.encode_privkey(thisData["privateKey"], "wif", args.versionByte)
		thisData["address"] = bitcoin.privkey_to_address(thisData["privateKey"], args.versionByte)

		# Generate the QR codes
		if args.errorCorrection.upper() not in ["L","M","Q","H"]:
			print("Please select a valid QR Error Correction value (L, M, Q, or H).")
			sys.exit()
		thisData["wifQR"] = qrTools.getQRArray(thisData["wif"], args.errorCorrection.upper())
		thisData["addressQR"] = qrTools.getQRArray(thisData["address"], args.errorCorrection.upper())

		# Reverse them or else they appear backwards (unknown reason)
		thisData["wifQR"] = list(reversed(thisData["wifQR"]))
		thisData["addressQR"] = list(reversed(thisData["addressQR"]))

		# Append ALL the wallet information, just in case we want to do something with it later
		walletDataList.append(thisData) 
Ejemplo n.º 53
0
def fix_priv(priv):
    ''' Use this code from prod. '''
    return bitcoin.encode_privkey(priv, 'wif', 0)
Ejemplo n.º 54
0
import bitcoin

valid_private_key = False
while not valid_private_key:
    private_key = bitcoin.random_key()
    decoded_private_key = bitcoin.decode_privkey(private_key, 'hex')
    valid_private_key = 0 < decoded_private_key < bitcoin.N
    print("Private key in hexadecimal is {}".format(private_key))
    print("Private key in decimal is {}".format(decoded_private_key))
wif_encoded_private_key = bitcoin.encode_privkey(decoded_private_key, 'wif')
print("Private key in WIF is {}".format(wif_encoded_private_key))
compressed_private_key = private_key + '01'
print("Private key compressed in hexadecimal {}".format(compressed_private_key))
wif_compressed_private_key = bitcoin.encode_privkey(bitcoin.decode_privkey(compressed_private_key, 'hex'), 'wif')
print("Private key WIF compressed is {}".format(wif_compressed_private_key))
public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key)
print("Public key (x,y) coordinates is".format(public_key))
hex_encoded_public_key = bitcoin.encode_pubkey(public_key, 'hex')
print("Hex encoded public key is {}".format(hex_encoded_public_key))
(public_key_x, public_key_y) = public_key
if (public_key_y % 2) == 0:
    compressed_prefix = '02'
else:
    compressed_prefix = '03'
hex_compressed_public_key = compressed_prefix + bitcoin.encode(public_key_x, 16)
print("Compressed Public Key (hex) is {}".format(hex_compressed_public_key))
print("Bitcoin Address (b58check) is {}".format(bitcoin.pubkey_to_address(public_key)))
print("Compressed Bitcoin Address (b58check) is: {}".format(bitcoin.pubkey_to_address(hex_compressed_public_key)))
Ejemplo n.º 55
0
    for m in range(wallet.max_mix_depth):
        cus_print("mixing depth %d m/0/%d/" % (m, m))
        balance_depth = 0
        for forchange in [0, 1]:
            cus_print(" " + ("external" if forchange == 0 else "internal") + " addresses m/0/%d/%d/" % (m, forchange))

            for k in range(wallet.index[m][forchange] + options.gaplimit):
                addr = wallet.get_addr(m, forchange, k)
                balance = 0.0
                for addrvalue in wallet.unspent.values():
                    if addr == addrvalue["address"]:
                        balance += addrvalue["value"]
                balance_depth += balance
                used = "used" if k < wallet.index[m][forchange] else " new"
                privkey = (
                    btc.encode_privkey(wallet.get_key(m, forchange, k), "wif_compressed", get_p2pk_vbyte())
                    if options.showprivkey
                    else ""
                )
                if method == "displayall" or balance > 0 or (used == " new" and forchange == 0):
                    cus_print(
                        "  m/0/%d/%d/%03d %-35s%s %.8f btc %s" % (m, forchange, k, addr, used, balance / 1e8, privkey)
                    )
        if m in wallet.imported_privkeys:
            cus_print(" import addresses")
            for privkey in wallet.imported_privkeys[m]:
                addr = btc.privtoaddr(privkey, get_p2pk_vbyte())
                balance = 0.0
                for addrvalue in wallet.unspent.values():
                    if addr == addrvalue["address"]:
                        balance += addrvalue["value"]
Ejemplo n.º 56
0
	total_balance = 0
	for m in range(wallet.max_mix_depth):
		printd('mixing depth %d m/0/%d/' % (m, m))
		balance_depth = 0
		for forchange in [0, 1]:
			printd(' ' + ('receive' if forchange==0 else 'change') +
				' addresses m/0/%d/%d/' % (m, forchange))
			for k in range(wallet.index[m][forchange] + options.gaplimit):
				addr = wallet.get_addr(m, forchange, k)
				balance = 0.0
				for addrvalue in wallet.unspent.values():
					if addr == addrvalue['address']:
						balance += addrvalue['value']
				balance_depth += balance
				used = ('used' if k < wallet.index[m][forchange] else ' new')
				privkey = btc.encode_privkey(wallet.get_key(m, forchange, k), 'wif_compressed',
					get_p2pk_vbyte()) if options.showprivkey else ''
				if method == 'displayall' or  balance > 0 or (used == ' new' and forchange==0):
					printd('  m/0/%d/%d/%03d %-35s%s %.8f btc %s' % (m, forchange, k, addr, used, balance/1e8, privkey))
		if m in wallet.imported_privkeys:
			printd(' import addresses')
			for privkey in wallet.imported_privkeys[m]:
				addr = btc.privtoaddr(privkey, common.get_p2pk_vbyte())
				balance = 0.0
				for addrvalue in wallet.unspent.values():
					if addr == addrvalue['address']:
						balance += addrvalue['value']
				used = (' used' if balance > 0.0 else 'empty')
				balance_depth += balance
				wip_privkey = btc.encode_privkey(privkey, 'wif_compressed',
					get_addr_vbyte()) if options.showprivkey else ''
				printd(' '*13 + '%-35s%s %.8f btc %s' % (addr, used, balance/1e8, wip_privkey))
Ejemplo n.º 57
0
def main():
    args = parse_args()

    # Set DEBUG variable for testing purposes (changing styling)
    # If true, prints the SCAD to the terminal and then breaks after first generation
    DEBUG = False

    # Generate the addresses
    if args.copies < 1:
        print("Please enter a valid number of copies (-co flag), and try again.")
        sys.exit()
    else: # Use an else statement here just in case we add the option to import a CSV file with the keys (generated somewhere else)
        walletDataList = []
        for i in range(args.copies):
            thisData = {}

            # Generate the addresses with keys
            thisData["privateKey"] = bitcoin.main.random_key() # Secure: uses random library, time library and proprietary function
            thisData["wif"] = bitcoin.encode_privkey(thisData["privateKey"], "wif", args.versionByte)
            thisData["address"] = bitcoin.privkey_to_address(thisData["privateKey"], args.versionByte)

            # Generate the QR codes
            if args.errorCorrection.upper() not in ["L","M","Q","H"]:
                print("Please select a valid QR Error Correction value (L, M, Q, or H).")
                sys.exit()
            thisData["wifQR"] = qrTools.getQRArray(thisData["wif"], args.errorCorrection.upper())
            thisData["addressQR"] = qrTools.getQRArray(thisData["address"], args.errorCorrection.upper())

            # Reverse them or else they appear backwards (unknown reason)
            thisData["wifQR"] = list(reversed(thisData["wifQR"]))
            thisData["addressQR"] = list(reversed(thisData["addressQR"]))

            # Append ALL the wallet information, just in case we want to do something with it later
            walletDataList.append(thisData) 

    # Validate other args and set some constants
    walletWidth = args.walletWidth
    walletHeight = args.walletHeight
    if args.layoutStyle == 1 or args.layoutStyle == 2 or args.layoutStyle == 3:
        walletLength = walletWidth*1.6 # Approximately the same ratio as a credit card
    else:
        print("Please choose a valid layout style option.")
        sys.exit()
    if args.blackOffset < -90.0:
        print("Please ensure that --black-offset (-bo flag) is set correctly, and is greater than -90.")
        sys.exit()
    textDepth = (args.blackOffset/100) * walletHeight

    # Check the openscad command
    scadExe = args.scadExe
    if args.scadExe == "openscad" and not distutils.spawn.find_executable("openscad"):
        if os.path.isfile("/Applications/OpenSCAD.app/Contents/MacOS/OpenSCAD"):
            print("Info: OpenSCAD found in Applications folder on Mac")
            scadExe = "/Applications/OpenSCAD.app/Contents/MacOS/OpenSCAD"
        elif os.path.isfile("%PROGRAMFILES%\OpenSCAD\openscad.exe"):
            print("Info: OpenSCAD found in Program Files on Windows")
            scadExe = "%PROGRAMFILES%\OpenSCAD\openscad.exe"
        elif os.path.isfile("%PROGRAMFILES(x86)%\OpenSCAD\openscad.exe"):
            print("Info: OpenSCAD found in Program Files (x86) on Windows")
            scadExe = "%PROGRAMFILES(x86)%\OpenSCAD\openscad.exe"
    if not distutils.spawn.find_executable(scadExe):
        print("Please install OpenSCAD or specify the location of it with --openscad-exe.")
        sys.exit()

    # Set the master SCAD variable
    masterSCAD = "// SCAD Code Generated By 3DGen.py - 3D Wallet Generator\n\n" # The beginning of the wallet are identical
    scadOutputs = [] # Generated from loop for each wallet (different addresses)

    # Include some modules at the beginning
    masterSCAD += "// Import some modules\n"
    masterSCAD += """
    $fn=100;
    module createMeniscus(h,radius)difference(){translate([radius/2+0.1,radius/2+0.1,0]){cube([radius+0.2,radius+0.1,h+0.2],center=true);}cylinder(h=h+0.2,r=radius,center=true);}
    module roundCornersCube(x,y,z)translate([x/2,y/2,z/2]){difference(){r=((x+y)/2)*0.052;cube([x,y,z],center=true);translate([x/2-r,y/2-r]){rotate(0){createMeniscus(z,r);}}translate([-x/2+r,y/2-r]){rotate(90){createMeniscus(z,r);}}translate([-x/2+r,-y/2+r]){rotate(180){createMeniscus(z,r);}}translate([x/2-r,-y/2+r]){rotate(270){createMeniscus(z,r);}}}}
    """ # The rounding corners modules for creating a rounded rectangle

    masterSCAD += "\n"

    # Draw the main prism
    if args.roundCorners:
        mainCube = "roundCornersCube(" + str(walletLength) + "," + str(walletWidth) + "," + str(walletHeight) + ");"
    else:
        mainCube = "cube([" + str(walletLength) + "," + str(walletWidth) + "," + str(walletHeight) + "]);"
    mainCube += "\n\n"

    # Init a variable to keep all the additive/subtractive parts
    finalParts = []

    # Init variables to keep the CSV output data in
    addressOut = []
    privkeyOut = []
    APOut = []
    PAOut = []

    # Set a counter for naming the files
    filenameCounter = 1

    # Break into the loop for each wallet
    for data in walletDataList:
        # 'data' = wif, address, wifQR, addressQR

        # Generate the texts
        addressLine1 = data["address"][:math.ceil(len(data["address"])/2.0)]
        addressLine2 = data["address"][math.ceil(len(data["address"])/2.0):]
        wifLine1 = data["wif"][:17]
        wifLine2 = data["wif"][17:34]
        wifLine3 = data["wif"][34:]

        addressLine1Dots = textGen.getArray(addressLine1)
        addressLine2Dots = textGen.getArray(addressLine2)
        privkeyLine1Dots = textGen.getArray(wifLine1)
        privkeyLine2Dots = textGen.getArray(wifLine2)
        privkeyLine3Dots = textGen.getArray(wifLine3)

        bigTitle = textGen.getArray("3D " + args.coinTitle + " Wallet")
        addressTitle = textGen.getArray("Address")
        privkeyTitle = textGen.getArray("Private Key")

        # Create the big title union so that it can be sized and moved
        bigTitleUnion = ""
        for rowIndex in range(len(bigTitle)):
            row = bigTitle[rowIndex]
            for colIndex in range(len(row)):
                if row[colIndex] == '1':
                    translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
                    bigTitleUnion += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))

        # Translate the title to where it goes
        bigTitleFinal = "translate([(1/17)*length,(14/17)*width,0]){resize([(15/17)*length,0,0],auto=[true,true,false]){bigTitleUnion}}".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('bigTitleUnion',bigTitleUnion)
        finalParts.append(bigTitleFinal+"\n\n")
        if args.layoutStyle == 1:
            # Need to copy it on to the backside as well - rotate then move it, and then create a union of the two titles (front and back)
            bigTitle2 = "translate([length,0,height]){rotate(180,v=[0,1,0]){bigTitleFinal}}".replace('length',str(walletLength)).replace('height',str(walletHeight)).replace('bigTitleFinal',bigTitleFinal).replace('translateHeight',str(translateHeight))
            finalParts.append(bigTitle2+"\n\n")
        
        # Draw the word "Address" on the front, and draw on the actual address
        if args.layoutStyle == 1 or args.layoutStyle == 3:
            # Draw the address on the front
            addressParts = []

            # Create the address title union and size/move it
            addressTitleUnion = "union(){"
            for rowIndex in range(len(addressTitle)):
                row = addressTitle[rowIndex]
                for colIndex in range(len(row)):
                    if row[colIndex] == '1':
                        translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
                        addressTitleUnion += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
            addressTitleUnion += "}"
            addressTitleFinal = "translate([(10/17)*length,(6/11)*width,0]){resize([0,(4/55)*width,0],auto=[true,true,false]){addressTitleUnion}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('addressTitleUnion',addressTitleUnion)
            addressParts.append(addressTitleFinal)

            # Create the first line of the address
            addressLine1Union = "union(){"
            for rowIndex in range(len(addressLine1Dots)):
                row = addressLine1Dots[rowIndex]
                for colIndex in range(len(row)):
                    if row[colIndex] == '1':
                        translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
                        addressLine1Union += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
            addressLine1Union += "}"
            addressLine1Final = "translate([(8.2/17)*length,(5/11)*width,0]){resize([0,(3/55)*width,0],auto=[true,true,false]){addressLine1Union}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('addressLine1Union',addressLine1Union)
            addressParts.append(addressLine1Final)

            # Create the second line of the address
            addressLine2Union = "union(){"
            for rowIndex in range(len(addressLine2Dots)):
                row = addressLine2Dots[rowIndex]
                for colIndex in range(len(row)):
                    if row[colIndex] == '1':
                        translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
                        addressLine2Union += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
            addressLine2Union += "}"
            addressLine2Final = "translate([(8.2/17)*length,(4.1/11)*width,0]){resize([0,(3/55)*width,0],auto=[true,true,false]){addressLine2Union}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('addressLine2Union',addressLine2Union)
            addressParts.append(addressLine2Final)

            # Create the QR code
            addressQRUnion = "union(){"
            for rowIndex in range(len(data["addressQR"])):
                row = data["addressQR"][rowIndex]
                for colIndex in range(len(row)):
                    if row[colIndex] == 0:
                        translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
                        addressQRUnion += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
            addressQRUnion += "}"
            addressQRFinal = "translate([(0.6/17)*length,(0.6/11)*width,0]){resize([0,(8/12)*width,0],auto=[true,true,false]){addressQRUnion}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('addressQRUnion',addressQRUnion)
            addressParts.append(addressQRFinal)
            
            finalParts.extend(addressParts)

        # Draw all the things having to do with the private key
        if args.layoutStyle == 1 or args.layoutStyle == 2:
            privkeyParts = []

            # Create the privkey title union and size/move it
            privkeyTitleUnion = "union(){"
            for rowIndex in range(len(privkeyTitle)):
                row = privkeyTitle[rowIndex]
                for colIndex in range(len(row)):
                    if row[colIndex] == '1':
                        translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
                        privkeyTitleUnion += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
            privkeyTitleUnion += "}"
            privkeyTitleFinal = "translate([(8.7/17)*length,(7/11)*width,0]){resize([0,(4/55)*width,0],auto=[true,true,false]){privkeyTitleUnion}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('privkeyTitleUnion',privkeyTitleUnion)
            privkeyParts.append(privkeyTitleFinal)

            # Create the first line of the privkey
            privkeyLine1Union = "union(){"
            for rowIndex in range(len(privkeyLine1Dots)):
                row = privkeyLine1Dots[rowIndex]
                for colIndex in range(len(row)):
                    if row[colIndex] == '1':
                        translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
                        privkeyLine1Union += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
            privkeyLine1Union += "}"
            privkeyLine1Final = "translate([(8.2/17)*length,(6/11)*width,0]){resize([0,(3/55)*width,0],auto=[true,true,false]){privkeyLine1Union}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('privkeyLine1Union',privkeyLine1Union)
            privkeyParts.append(privkeyLine1Final)

            # Create the second line of the privkey
            privkeyLine2Union = "union(){"
            for rowIndex in range(len(privkeyLine2Dots)):
                row = privkeyLine2Dots[rowIndex]
                for colIndex in range(len(row)):
                    if row[colIndex] == '1':
                        translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
                        privkeyLine2Union += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
            privkeyLine2Union += "}"
            privkeyLine2Final = "translate([(8.2/17)*length,(5.1/11)*width,0]){resize([0,(3/55)*width,0],auto=[true,true,false]){privkeyLine2Union}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('privkeyLine2Union',privkeyLine2Union)
            privkeyParts.append(privkeyLine2Final)

            # Create the third line of the privkey
            privkeyLine3Union = "union(){"
            for rowIndex in range(len(privkeyLine3Dots)):
                row = privkeyLine3Dots[rowIndex]
                for colIndex in range(len(row)):
                    if row[colIndex] == '1':
                        translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
                        privkeyLine3Union += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
            privkeyLine3Union += "}"
            privkeyLine3Final = "translate([(8.2/17)*length,(4.2/11)*width,0]){resize([0,(3/55)*width,0],auto=[true,true,false]){privkeyLine3Union}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('privkeyLine3Union',privkeyLine3Union)
            privkeyParts.append(privkeyLine3Final)

            # Create the QR code
            privkeyQRUnion = "union(){"
            for rowIndex in range(len(data["wifQR"])):
                row = data["wifQR"][rowIndex]
                for colIndex in range(len(row)):
                    if row[colIndex] == 0:
                        translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
                        privkeyQRUnion += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIndex)).replace('rowIndex',str(rowIndex)).replace('textDepth',str(abs(textDepth))).replace('translateHeight',str(translateHeight))
            privkeyQRUnion += "}"
            privkeyQRFinal = "translate([(0.6/17)*length,(0.6/11)*width,0]){resize([0,(8/12)*width,0],auto=[true,true,false]){privkeyQRUnion}}\n\n".replace('length',str(walletLength)).replace('width',str(walletWidth)).replace('privkeyQRUnion',privkeyQRUnion)
            privkeyParts.append(privkeyQRFinal)

            if args.layoutStyle == 2:
                # Just add it all to the finalParts
                finalParts.extend(privkeyParts)
            elif args.layoutStyle == 1:
                # Rotate it all and then add it to the finalParts
                privkeyPartsNew = []
                for part in privkeyParts:
                    privkeyPartsNew.append("translate([length,0,height]){rotate(180,v=[0,1,0]){part}}".replace('length',str(walletLength)).replace('height',str(walletHeight)).replace('part',part).replace('translateHeight',str(translateHeight)))
                finalParts.extend(privkeyPartsNew)

        # Put it all together
        finalSCAD = masterSCAD
        if textDepth < 0:
            finalSCAD += "difference() {\n\n"
        else:
            finalSCAD += "union() {\n\n"
        finalSCAD += mainCube
        finalSCAD += "".join(finalParts)
        finalSCAD += "}"

        if DEBUG:
            print(finalSCAD)
            break

        if args.outputSCADFolder:
            try:
                os.makedirs(args.outputSCADFolder)
            except FileExistsError:
                pass
            scadOutFile = open(args.outputSCADFolder + '/wallet' + str(filenameCounter) + '.scad','w')
            scadOutFile.write(finalSCAD)
            scadOutFile.close()

        # Log some info
        print("Status: Done generating data for wallet #" + str(filenameCounter) + "...Starting generating STL file")

        if args.outputSTLFolder:
            try:
                os.makedirs(args.outputSTLFolder)
            except FileExistsError:
                pass
            scadOutFile = open('temp.scad','w')
            scadOutFile.write(finalSCAD)
            scadOutFile.close()
            os.system(scadExe + " -o " + args.outputSTLFolder + "/wallet" + str(filenameCounter) + ".stl temp.scad")
            try:
                os.remove('temp.scad')
            except:
                pass
        else:
            print("Please provide a folder to output the STL files.")

        # Update the CSV file variables
        addressOut.append(data["address"])
        privkeyOut.append(data["wif"])
        APOut.append(data["address"] + "," + data["wif"])
        PAOut.append(data["wif"] + "," + data["address"])

        # Print some more stats
        print("Status: Done generating STL file (" + str(round(filenameCounter/args.copies*100)) + "% done)")

        filenameCounter += 1

    # Export the CSV files
    if args.exportAddressCSV:
        csvFile = open(args.exportAddressCSV,'a')
        csvFile.write(','.join(addressOut))
        csvFile.close()

    if args.exportPrivkeyCSV:
        csvFile = open(args.exportPrivkeyCSV,'a')
        csvFile.write(','.join(privkeyOut))
        csvFile.close()

    if args.exportAPCSV:
        csvFile = open(args.exportAPCSV,'a')
        csvFile.write('\n'.join(exportAPCSV))
        csvFile.close()

    if args.exportPACSV:
        csvFile = open(args.exportPACSV,'a')
        csvFile.write('\n'.join(exportPACSV))
        csvFile.close()
Ejemplo n.º 58
0
	total_balance = 0
	for m in range(wallet.max_mix_depth):
		print 'mixing depth %d m/0/%d/' % (m, m)
		balance_depth = 0
		for forchange in [0, 1]:
			print(' ' + ('receive' if forchange==0 else 'change') +
				' addresses m/0/%d/%d/' % (m, forchange))
			for k in range(wallet.index[m][forchange] + options.gaplimit):
				addr = wallet.get_addr(m, forchange, k)
				balance = 0.0
				for addrvalue in wallet.unspent.values():
					if addr == addrvalue['address']:
						balance += addrvalue['value']
				balance_depth += balance
				used = ('used' if k < wallet.index[m][forchange] else ' new')
				privkey = btc.encode_privkey(wallet.get_key(m, forchange, k), 'wif_compressed',
					get_addr_vbyte()) if options.showprivkey else ''
				if method == 'displayall' or  balance > 0 or (used == ' new' and forchange==0):
					print '  m/0/%d/%d/%03d %-35s%s %.8f btc %s' % (m, forchange, k, addr, used, balance/1e8, privkey)
		print 'for mixdepth=%d balance=%.8fbtc' % (m, balance_depth/1e8)
		total_balance += balance_depth
	print 'total balance = %.8fbtc' % (total_balance/1e8)
elif method == 'summary':
	total_balance = 0
	for m in range(wallet.max_mix_depth):
		balance_depth = 0
		for forchange in [0, 1]:
			for k in range(wallet.index[m][forchange]):
				addr = wallet.get_addr(m, forchange, k)
				for addrvalue in wallet.unspent.values():
					if addr == addrvalue['address']:
						balance_depth += addrvalue['value']