示例#1
0
def test_wif_privkeys_valid(setup_keys):
    with open("test/base58_keys_valid.json", "r") as f:
        json_data = f.read()
    valid_keys_list = json.loads(json_data)
    for a in valid_keys_list:
        key, hex_key, prop_dict = a
        if prop_dict["isPrivkey"]:
            netval = "testnet" if prop_dict["isTestnet"] else "mainnet"
            jm_single().config.set("BLOCKCHAIN", "network", netval)
            print 'testing this key: ' + key
            assert chr(btc.get_version_byte(
                key)) in '\x80\xef', "not valid network byte"
            if "decode_privkey" in dir(btc):
                from_wif_key = btc.decode_privkey(key)
                expected_key = btc.decode_privkey(hex_key)
            else:
                comp = prop_dict["isCompressed"]
                from_wif_key = btc.from_wif_privkey(
                    key,
                    compressed=comp,
                    vbyte=btc.get_version_byte(key) - 128)
                expected_key = hex_key
                if comp: expected_key += '01'
            assert from_wif_key == expected_key, "Incorrect key decoding: " + \
                   str(from_wif_key) + ", should be: " + str(expected_key)
示例#2
0
def test_wif_privkeys_valid(setup_keys):
    with open("test/base58_keys_valid.json", "r") as f:
        json_data = f.read()
    valid_keys_list = json.loads(json_data)
    for a in valid_keys_list:
        key, hex_key, prop_dict = a
        if prop_dict["isPrivkey"]:
            netval = "testnet" if prop_dict["isTestnet"] else "mainnet"
            jm_single().config.set("BLOCKCHAIN", "network", netval)
            print 'testing this key: ' + key
            assert chr(btc.get_version_byte(
                key)) in '\x80\xef', "not valid network byte"
            if "decode_privkey" in dir(btc):
                from_wif_key = btc.decode_privkey(key)
                expected_key = btc.decode_privkey(hex_key)
            else:
                comp = prop_dict["isCompressed"]
                from_wif_key = btc.from_wif_privkey(
                    key,
                    compressed=comp,
                    vbyte=btc.get_version_byte(key)-128)
                expected_key = hex_key
                if comp: expected_key += '01'
            assert from_wif_key == expected_key, "Incorrect key decoding: " + \
                   str(from_wif_key) + ", should be: " + str(expected_key)
示例#3
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
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
示例#5
0
 def decode(key):
     """
     Decode the base58 private_value to decimale
     """
     private_value_hex = binascii.hexlify(base58.b58decode(key))
     private_value = bitcoin.decode_privkey(private_value_hex)
     return private_value
def generate_bls_privkey() -> str:
    """
    :return: Generated BLS private key as a hex string.
    """
    max_iterations = 2000
    for i in range(0, max_iterations):
        privkey = bitcoin.random_key()
        pk_bytes = bytes.fromhex(privkey)
        num_pk = bitcoin.decode_privkey(privkey, 'hex')
        if 0 < num_pk < bitcoin.N:
            if pk_bytes[0] >= 0x74:
                if i == max_iterations - 1:  # BLS restriction: the first byte is less than 0x74
                    # after 'limit' iterations we couldn't get the first byte "compatible" with BLS so
                    # the last resort is to change it to a random value < 0x73
                    tmp_pk_bytes = bytearray(pk_bytes)
                    tmp_pk_bytes[0] = randint(0, 0x73)
                    logging.warning(
                        'Changing the first byte of the generated BLS key from %s to %s to meet '
                        'the requirements', str(pk_bytes[0]),
                        str(tmp_pk_bytes[0]))
                    pk_bytes = bytes(tmp_pk_bytes)
                else:
                    continue

            try:
                pk = bls.PrivateKey.from_bytes(pk_bytes)
                pk_bin = pk.serialize()
                return pk_bin.hex()
            except Exception as e:
                logging.warning(
                    'Could not process "%s" as a BLS private key. Error details: %s',
                    pk_bytes.hex(), str(e))
        else:
            logging.warning('Skipping the generated key: %s', pk_bytes.hex())
    raise Exception("Could not generate BLS private key")
示例#7
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")
示例#8
0
 def genPrivateKey_(self):
     valid_key = False
     while not valid_key:
         priv_key = bitcoin.random_key()
         decoded_priv_key = bitcoin.decode_privkey(priv_key, 'hex')
         valid_key = 0 < decoded_priv_key < bitcoin.N
     return priv_key, decoded_priv_key
示例#9
0
 def decode(key):
     """
     Decode the base58 private_value to decimale
     """
     private_value_hex = binascii.hexlify(base58.b58decode(key))
     private_value = bitcoin.decode_privkey(private_value_hex)
     return private_value
示例#10
0
文件: AntiBTC.py 项目: zming/Learn
def Generate_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
    return private_key
示例#11
0
文件: AntiBTC.py 项目: zming/Learn
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
示例#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))
示例#13
0
文件: AntiBTC.py 项目: zming/Learn
def Generate_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
    return private_key
def generate_bls_privkey() -> str:
    """
    :return: Generated BLS private key as a hex string.
    """
    max_iterations = 2
    for i in range(0, max_iterations):
        privkey = bitcoin.random_key()
        pk_bytes = bytes.fromhex(privkey)
        num_pk = bitcoin.decode_privkey(privkey, 'hex')
        if 0 < num_pk < bitcoin.N:
            if pk_bytes[0] >= 0x74:
                if i == max_iterations - 1:  # BLS restriction: the first byte is less than 0x74
                    # after 'limit' iterations we couldn't get the first byte "compatible" with BLS so
                    # the last resort is to change it to a random value < 0x73
                    tmp_pk_bytes = bytearray(pk_bytes)
                    tmp_pk_bytes[0] = randint(0, 0x73)
                    pk_bytes = bytes(tmp_pk_bytes)
                else:
                    continue

            try:
                pk = blspy.PrivateKey.from_bytes(pk_bytes)
                pk_bin = pk.serialize()
                return pk_bin.hex()
            except Exception as e:
                logging.exception(str(e))
    raise Exception("Could not generate BLS private key")
示例#15
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)
示例#16
0
文件: in.py 项目: thearthouse/emerald
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
示例#17
0
 def convert(self, value, param, ctx):
     """Convert the given private key to its integer representation."""
     try:
         return decode_privkey(value)
     except Exception:
         # unfortunately pybitcointools raises no more specific exception
         self.fail('{} is not a valid private key'.format(value),
                   param, ctx)
示例#18
0
def createPriKey(wifKey):
    wif_encoding_private_key = wifKey
    wifUNCompressed = bitcoin.decode_privkey(wif_encoding_private_key,
                                             'wif_compressed')
    decimalToHex = bitcoin.encode(wifUNCompressed, 16)  # return str
    cv = Curve.get_curve('secp256k1')
    pv_key = ECPrivateKey(int("0x" + decimalToHex, 16), cv)  # 16进制str 转为 int
    return pv_key
示例#19
0
def ecdsa_raw_sign_one_to_one(msghash, sender_priv, receiver_pub):
    z = bitcoin.hash_to_int(msghash)
    k = bitcoin.deterministic_generate_k(msghash, sender_priv)
    r, y = bitcoin.fast_multiply(bitcoin.decode_pubkey(receiver_pub), k)
    s = bitcoin.inv(k, N) * (z + r * bitcoin.decode_privkey(sender_priv)) % N
    v, r, s = 27 + ((y % 2) ^
                    (0 if s * 2 < N else 1)), r, s if s * 2 < N else N - s
    return v, r, s
示例#20
0
 def convert(self, value, param, ctx):
     """Convert the given private key to its integer representation."""
     try:
         return decode_privkey(value)
     except Exception:
         # unfortunately pybitcointools raises no more specific exception
         self.fail('{} is not a valid private key'.format(value), param,
                   ctx)
示例#21
0
def create_bitcoin_public_key(private_key):
  decoded_private_key = bitcoin.decode_privkey(private_key, "hex")
  public_key = bitcoin.fast_multiply(bitcoin.G, decoded_private_key)
  (public_key_x, public_key_y) = public_key
  compressed_prefix = "02" if (public_key_y % 2) == 0 else "03"
  # 64 represents the minimum length of the string required returned back.
  # Zeros will be prepended to a string until it meets the length requirement.
  # Less characters than 64 will result in an invalid public key.
  return compressed_prefix + bitcoin.encode(public_key_x, 16, 64)
示例#22
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
示例#23
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)
示例#24
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
示例#26
0
def test_wif_privkeys_invalid(setup_keys):
    #first try to create wif privkey from key of wrong length
    bad_privs = ['\x01\x02'*17] #some silly private key but > 33 bytes

    #next try to create wif with correct length but wrong compression byte
    bad_privs.append('\x07'*32 + '\x02')
    
    for priv in bad_privs:
        with pytest.raises(Exception) as e_info:
            fake_wif = btc.wif_compressed_privkey(binascii.hexlify(priv))

    #Create a wif with wrong length
    bad_wif1 = btc.bin_to_b58check('\x01\x02'*34, 128)
    #Create a wif with wrong compression byte
    bad_wif2 = btc.bin_to_b58check('\x07'*33, 128)
    for bw in [bad_wif1, bad_wif2]:
        with pytest.raises(Exception) as e_info:
            fake_priv = btc.from_wif_privkey(bw)

    #Some invalid b58 from bitcoin repo;
    #none of these are valid as any kind of key or address
    with open("test/base58_keys_invalid.json", "r") as f:
        json_data = f.read()
    invalid_key_list = json.loads(json_data)
    for k in invalid_key_list:
        bad_key = k[0]
        for netval in ["mainnet", "testnet"]:
            jm_single().config.set("BLOCKCHAIN", "network", netval)
            #if using py.test -s ; sanity check to see what's actually being tested
            print 'testing this key: ' + bad_key
            if "decode_privkey" in dir(btc):
                try:
                    bad_key_format = btc.get_privkey_format(bad_key)
                    print 'has correct format: ' + bad_key_format
                except:
                    pass
            #should throw exception
            with pytest.raises(Exception) as e_info:
                if "decode_privkey" in dir(btc):
                    from_wif_key = btc.decode_privkey(bad_key)
                else:
                    from_wif_key = btc.from_wif_compressed_privkey(
                        bad_key, btc.get_version_byte(bad_key))
                #in case the b58 check encoding is valid, we should
                #also check if the leading version byte is in the
                #expected set, and throw an error if not.
                if chr(btc.get_version_byte(bad_key)) not in '\x80\xef':
                    raise Exception("Invalid version byte")
                #the bitcoin library should throw
                #if the compression byte is not there (test not needed
                #for secp256k1 branch since the wif_compressed function checks)
                if "decode_privkey" in dir(btc):
                    if "compressed" in btc.get_privkey_format(bad_key) and \
                   btc.b58check_to_bin(x)[-1] != '\x01':
                        raise Exception("Invalid compression byte")
示例#27
0
def test_wif_privkeys_invalid(setup_keys):
    #first try to create wif privkey from key of wrong length
    bad_privs = ['\x01\x02' * 17]  #some silly private key but > 33 bytes

    #next try to create wif with correct length but wrong compression byte
    bad_privs.append('\x07' * 32 + '\x02')

    for priv in bad_privs:
        with pytest.raises(Exception) as e_info:
            fake_wif = btc.wif_compressed_privkey(binascii.hexlify(priv))

    #Create a wif with wrong length
    bad_wif1 = btc.bin_to_b58check('\x01\x02' * 34, 128)
    #Create a wif with wrong compression byte
    bad_wif2 = btc.bin_to_b58check('\x07' * 33, 128)
    for bw in [bad_wif1, bad_wif2]:
        with pytest.raises(Exception) as e_info:
            fake_priv = btc.from_wif_privkey(bw)

    #Some invalid b58 from bitcoin repo;
    #none of these are valid as any kind of key or address
    with open("test/base58_keys_invalid.json", "r") as f:
        json_data = f.read()
    invalid_key_list = json.loads(json_data)
    for k in invalid_key_list:
        bad_key = k[0]
        for netval in ["mainnet", "testnet"]:
            jm_single().config.set("BLOCKCHAIN", "network", netval)
            #if using py.test -s ; sanity check to see what's actually being tested
            print 'testing this key: ' + bad_key
            if "decode_privkey" in dir(btc):
                try:
                    bad_key_format = btc.get_privkey_format(bad_key)
                    print 'has correct format: ' + bad_key_format
                except:
                    pass
            #should throw exception
            with pytest.raises(Exception) as e_info:
                if "decode_privkey" in dir(btc):
                    from_wif_key = btc.decode_privkey(bad_key)
                else:
                    from_wif_key = btc.from_wif_compressed_privkey(
                        bad_key, btc.get_version_byte(bad_key))
                #in case the b58 check encoding is valid, we should
                #also check if the leading version byte is in the
                #expected set, and throw an error if not.
                if chr(btc.get_version_byte(bad_key)) not in '\x80\xef':
                    raise Exception("Invalid version byte")
                #the bitcoin library should throw
                #if the compression byte is not there (test not needed
                #for secp256k1 branch since the wif_compressed function checks)
                if "decode_privkey" in dir(btc):
                    if "compressed" in btc.get_privkey_format(bad_key) and \
                   btc.b58check_to_bin(x)[-1] != '\x01':
                        raise Exception("Invalid compression byte")
示例#28
0
def generate_privkey(isTestnet=False):
    """
    Based on Andreas Antonopolous work from 'Mastering Bitcoin'.
    """
    valid = False
    privkey = 0
    while not valid:
        privkey = bitcoin.random_key()
        decoded_private_key = bitcoin.decode_privkey(privkey, 'hex')
        valid = 0 < decoded_private_key < bitcoin.N
    return base58fromhex(privkey, isTestnet)
示例#29
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
示例#30
0
def generate_privkey(dash_network: str):
    """
    Based on Andreas Antonopolous work from 'Mastering Bitcoin'.
    """
    valid = False
    privkey = 0
    while not valid:
        privkey = bitcoin.random_key()
        decoded_private_key = bitcoin.decode_privkey(privkey, 'hex')
        valid = 0 < decoded_private_key < bitcoin.N
    data = bytes([get_chain_params(dash_network).PREFIX_SECRET_KEY]) + bytes.fromhex(privkey)
    checksum = bitcoin.bin_dbl_sha256(data)[0:4]
    return base58.b58encode(data + checksum)
示例#31
0
def generate_privkey():
    """
    Based on Andreas Antonopolous work from 'Mastering Bitcoin'.
    """
    valid = False
    privkey = 0
    while not valid:
        privkey = bitcoin.random_key()
        decoded_private_key = bitcoin.decode_privkey(privkey, 'hex')
        valid = 0 < decoded_private_key < bitcoin.N
    data = bytes([204]) + bytes.fromhex(privkey)
    checksum = bitcoin.bin_dbl_sha256(data)[0:4]
    return base58.b58encode(data + checksum)
示例#32
0
def ecdsa_raw_verify_one_to_one(msghash, vrs, sender_pub, receiver_priv):
    v, r, s = vrs
    w = bitcoin.inv(s, N)
    z = bitcoin.hash_to_int(msghash)
    u1, u2 = z * w % N, r * w % N
    receiver_pub = bitcoin.decode_pubkey(bitcoin.privtopub(receiver_priv))
    receiver_sender_shared = bitcoin.fast_multiply(
        bitcoin.decode_pubkey(sender_pub),
        bitcoin.decode_privkey(receiver_priv))
    u1Qr = bitcoin.fast_multiply(receiver_pub, u1)
    u2Qs = bitcoin.fast_multiply(receiver_sender_shared, u2)
    x, y = bitcoin.fast_add(u1Qr, u2Qs)
    return bool(r == x and (r % N) and (s % N))
示例#33
0
def generate_privkey(isTestnet=False):
    """
    Based on Andreas Antonopolous work from 'Mastering Bitcoin'.
    """
    base58_secret = TESTNET_WIF_PREFIX if isTestnet else WIF_PREFIX
    valid = False
    privkey = 0
    while not valid:
        privkey = bitcoin.random_key()
        decoded_private_key = bitcoin.decode_privkey(privkey, 'hex')
        valid = 0 < decoded_private_key < bitcoin.N
    data = bytes([base58_secret]) + bytes.fromhex(privkey)
    checksum = bitcoin.bin_dbl_sha256(data)[0:4]
    return b58encode(data + checksum)
示例#34
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)
def run():
    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)
        r = requests.get("https://blockchain.info/q/getsentbyaddress/" +
                         bitcoin.pubkey_to_address(public_key))
        if int(r.text) > 0:
            print("Bitcoin Address is:", bitcoin.pubkey_to_address(public_key))
            print("Private Key is: ", wif_encoded_private_key)
            print("Balance is: ", r.text)
def add_transaction():
    res = "The upcoming transaction is added to next block"
    if 'loggedin' in session:
        if request.method == "POST":
            receiver = request.form["receiver"]
            amount = request.form["amount"]
            private_key = request.form["private_key"]
            purpose = request.form["purpose"]
            detail = request.form["detail"]
            (temp_public_key_x,
             temp_public_key_y) = public_key_gen(private_key)
            cursor.execute('SELECT * FROM accounts WHERE id = %s',
                           (session['id'], ))
            account = cursor.fetchone()
            sender = account['public_key_comp']
            cursor.execute('SELECT * FROM accounts WHERE username = %s',
                           (receiver, ))
            rec_account = cursor.fetchone()
            if (rec_account):
                receiver = rec_account['public_key_comp']
                msg = {
                    'sender': sender,
                    'receiver': receiver,
                    'amount': amount
                }
                if (sender and receiver and amount and purpose and detail):
                    # checking if private key is true or not
                    if (str(temp_public_key_x) == account['public_key_x'] and
                            str(temp_public_key_y) == account['public_key_y']):
                        # adding signature to the transaction
                        signature = signECDSAsecp256k1(
                            msg, bitcoin.decode_privkey(private_key, 'hex'))
                        index = blockchain.add_transaction(
                            sender, receiver, amount, signature, purpose,
                            detail)
                        res = f"This transaction will be added to Block {index}"
                    else:
                        res = "Incorrect private key!!!"
            else:
                res = "Reciever Username Not found!!!"
        return render_template('addtransaction.html', response=res)
    else:
        return redirect(url_for('home'))
示例#37
0
def sign_donation_tx(tx, i, priv):
	k = sign_k
	hashcode = btc.SIGHASH_ALL
	i = int(i)
	if len(priv) <= 33:
		priv = btc.safe_hexlify(priv)
	pub = btc.privkey_to_pubkey(priv)
	address = btc.pubkey_to_address(pub)
	signing_tx = btc.signature_form(tx, i, btc.mk_pubkey_script(address), hashcode)

	msghash = btc.bin_txhash(signing_tx, hashcode)
	z = btc.hash_to_int(msghash)
	#k = deterministic_generate_k(msghash, priv)
	r, y = btc.fast_multiply(btc.G, k)
	s = btc.inv(k, btc.N) * (z + r*btc.decode_privkey(priv)) % btc.N
	rawsig = 27+(y % 2), r, s

	sig =  btc.der_encode_sig(*rawsig)+btc.encode(hashcode, 16, 2)
	#sig = ecdsa_tx_sign(signing_tx, priv, hashcode)
	txobj = btc.deserialize(tx)
	txobj["ins"][i]["script"] = btc.serialize_script([sig, pub])
	return btc.serialize(txobj)
示例#38
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)
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)))