os.urandom (n) set n value to bits rather than bytes - python

how do i input bits rather than bytes in os.urandom(n) function? I want to set the n value to 66 bits that is 8.25 bytes and floating numbers are not supported in it? or is there any other function that help me set the value of n to 66 bits?
import time
import datetime as dt
import smtplib
import os
import multiprocessing
from multiprocessing import Pool
import binascii, hashlib, base58, ecdsa
import pandas as pd
def ripemd160(x):
d = hashlib.new('ripemd160')
d.update(x)
return d
r = 0
cores=6
def seek(r, df_handler):
global num_threads
LOG_EVERY_N = 1000
start_time = dt.datetime.today().timestamp()
i = 0
print("Core " + str(r) +": Searching Private Key..")
while True:
i=i+1
# generate private key , uncompressed WIF starts with "5"
priv_key = os.urandom(32)
fullkey = '80' + binascii.hexlify(priv_key).decode()
sha256a = hashlib.sha256(binascii.unhexlify(fullkey)).hexdigest()
sha256b = hashlib.sha256(binascii.unhexlify(sha256a)).hexdigest()
WIF = base58.b58encode(binascii.unhexlify(fullkey+sha256b[:8]))
# get public key , uncompressed address starts with "1"
sk = ecdsa.SigningKey.from_string(priv_key, curve=ecdsa.SECP256k1)
vk = sk.get_verifying_key()
publ_key = '04' + binascii.hexlify(vk.to_string()).decode()
hash160 = ripemd160(hashlib.sha256(binascii.unhexlify(publ_key)).digest()).digest()
publ_addr_a = b"\x00" + hash160
checksum = hashlib.sha256(hashlib.sha256(publ_addr_a).digest()).digest()[:4]
publ_addr_b = base58.b58encode(publ_addr_a + checksum)
priv = WIF.decode()
pub = publ_addr_b.decode()
time_diff = dt.datetime.today().timestamp() - start_time
if (i % LOG_EVERY_N) == 0:
print('Core :'+str(r)+" K/s = "+ str(i / time_diff))
#print ('Worker '+str(r)+':'+ str(i) + '.- # '+pub + ' # -------- # '+ priv+' # ')
pub = pub + '\n'
filename = 'bit.txt'
with open(filename) as f:
for line in f:
if pub in line:
msg = "\nPublic:
" + str(pub) + " ---- Private: " + str(priv) + "YEI"
text = msg
#UNCOMMENT IF 2FA from gmail is activated, or risk missing your winning ticket;)
#server = smtplib.SMTP("smtp.gmail.com", 587)
#server.ehlo()
#server.starttls()
#server.login("example#gmail.com", "password")
#fromaddr = "example#gmail.com"
#toaddr = "example#gmail.com"
#server.sendmail(fromaddr, toaddr, text)
print(text)
with open('Wallets.txt','a') as f:
f.write(priv)
f.write(' ')
f.write(pub)
f.write('\n')
f.close()
time.sleep(30)
print ('WINNER WINNER CHICKEN DINNER!!! ---- ' +dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), pub, priv)
break
contador=0
if __name__ == '__main__':
jobs = []
df_handler = pd.read_csv(open('bit.txt', 'r'))
for r in range(cores):
p = multiprocessing.Process(target=seek, args=(r,df_handler))
jobs.append(p)
p.start()
this is the code and i want the os.urandom(32) to be 8.25 bytes (66 bit)

If you want an integer with 66 random bits using the same random source as os.urandom() uses,
>>> import random
>>> x = random.SystemRandom().getrandbits(66)
46111822109486537585
If you want that integer as a "binary string" of length 66,
>>> bin(x)[2:].rjust(66, '0')
'100111111111101110000110011110010111001101111100101101101101110001'
(bin()'s output has a 0b prefix, so we slice that off. In case any of the high-order bits are zero, they wouldn't be in the bin() output, so we pad the string to the desired length with zeroes.)

Related

Telnyx in python

Hi I want to get numbers from a txt document let's say numbers.txt, than I want to get the message from a txt doc, let's say message.txt and send automatic sms to the numbers from numbers.txt, and if a number is not valid to skip/ignore it and show an error on terminal then go to the next number
import telnyx
telnyx.api_key = "YOUR_API_KEY"
your_telnyx_number = "+13115552368"
destination_number = "+13115552367"
telnyx.Message.create(
from_=your_telnyx_number,
to=destination_number,
text="Hello, world!",
)
and how can I include it in this code so can work properly in next code?
from pathlib import Path
import telnyx
import configparser
import time
import random
config = configparser.ConfigParser()
config.read('config.ini')
with open(config['sender']['numbersFile'], "r") as numbersFile: numbers = numbersFile.read().splitlines()
message = Path(config['sender']['messageFile']).read_text().rstrip()
outputFile = open(config['sender']['outputFile'], 'a')
your_telnyx_number = config['api']['your_telnyx_number']
telnyx.api_key = config['api']['telnyx.api_key']
telnyx.api_Public = config['api']['telnyx.api_Public']
senderBuild = telnyx.Client(key=telnyx.api_key, public=telnyx.api_Public)
senderClient = telnyx.Sms(senderBuild)
totalSent = 0
for number in numbers:
if config['sender'].getboolean('specialMode'):
messageToSend = message.replace('<pagename>', number.split('|')[1][0:int(config['sender']['maxCharsName'])])
messageToSend = messageToSend.replace('<pagelink>',
number.split('|')[2][0:int(config['sender']['maxCharsLink'])])
sendToNumber = number.split('|')[0]
else:
messageToSend = message
sendToNumber = number
messageToSend = messageToSend.replace('<randint>', str(random.randint(9999,99999)))
responseData = senderClient.send_message(
{
"from": your_telnyx_number,
"to": sendToNumber.strip(),
"text": messageToSend
}
)
totalSent += 1
if responseData["messages"][0]["status"] == "0":
print('Message was sent to : ' + sendToNumber)
print(messageToSend)
print(str(totalSent) + "/" + str(len(numbers)) + ' of messages sent!')
print('---------------------------------------------------------')
else:
print('Message not sent to : ' + sendToNumber)
print('We\'ve had an error!')
print({responseData['messages'][0]['error-text']})
input('To continue sending please press ENTER | To abort, simply close the software.')
time.sleep(1)
the config.ini contain:
[sender]
numbersFile = data/numbers.txt
outputFile = data/sent.txt
messageFile = data/message.txt
maxCharsName = 190
maxCharsLink = 10
specialMode = True
[api]
your_telnyx_number = 12014739061
telnyx.api_key = 6cdb5009
telnyx.api_Public = s2fmQ6CWu5vq9bdW

How to get Steam ID by username using Python?

I want to get steam ID by user name
using Python.
I tried the following code, but it prints only user names.
and i read the docs -> python-valve.readthedocs.io/en/latest/steamid.html
but i cant understand.
import valve.source.a2s
import valve.steam.id
import steam
import valve
import time
import a2s
import pymysql
Server_IP = ""
ServerPort = 0
Server_IP = input("Server IP : ")
ServerPort = input("Server PORT :")
SERVER_ADDRESS = (Server_IP, int(ServerPort))
while(1):
player_count = 1
with valve.source.a2s.ServerQuerier(SERVER_ADDRESS) as server:
info = server.info()
players = server.players()
steamUserid = server.__str__()
print("{player_count}/{max_players} {server_name}".format(**info))
for player in sorted(players["players"],
key=lambda p: p["score"], reverse=True):
user_name = ("{name}".format(**player))
if user_name == "":
duration = "{duration}".format(**player)
print("{:>2}".format(str(player_count)) + " | duration(sec) = " + "{: <20}".format(duration) + " EpicGames")
player_count += 1
else:
steam_name = "{name}".format(**player)
duration = "{duration}".format(**player)
print("{:>2}".format(str(player_count)) + " | duration(sec) = " + "{: <20}".format(duration) + " Steam" + steam_name)
player_count += 1
time.sleep(1)

Select return empty object (socket programing in python)

I'm currently writing a relatively basic Socket program in python which is a Ping application using ICMP request and reply messages. i am getting a error that select.select() in receiveOnePing() function return empty object . How can i fix it?
This is what I currently get as output:
([], [], [])
RTT: 0: Destination Network Unreachable,
Package Lose Rate: 0
this is my code
import os
import sys
import struct
import time
import select
import binascii
import socket
ICMP_ECHO_REQUEST = 8
timeRTT = []
packageSent =0
packageRev = 0
def checksum(string):
csum = 0
countTo = (len(string) // 2) * 2
count = 0
while count < countTo:
thisVal = ord(string[count+1]) * 256 + ord(string[count])
csum = csum + thisVal
csum = csum & 0xffffffff
count = count + 2
if countTo < len(string):
csum = csum + ord(string[len(string) - 1])
csum = csum & 0xffffffff
csum = (csum >> 16) + (csum & 0xffff)
csum = csum + (csum >> 16)
answer = ~csum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def receiveOnePing(mySocket, ID, timeout, destAddr):
global packageRev,timeRTT
timeLeft = timeout
while 1:
startedSelect = time.time()
whatReady = select.select([mySocket], [], [], timeLeft)
print(whatReady)
howLongInSelect = (time.time() - startedSelect)
if whatReady[0] == []: # Timeout
return "0: Destination Network Unreachable,"
timeReceived = time.time()
recPacket, addr = mySocket.recvfrom(1024)
#Fill in start
#Fetch the ICMP header from the IP packet
icmpHeader = recPacket[20:28]
requestType, code, revChecksum, revId, revSequence = struct.unpack('bbHHh',icmpHeader)
if ID == revId:
bytesInDouble = struct.calcsize('d')
timeData = struct.unpack('d',recPacket[28:28 + bytesInDouble])[0]
timeRTT.append(timeReceived - timeData)
packageRev += 1
return timeReceived - timeData
else:
return "ID is not the same!"
#Fill in end
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
return "1: Destination Host Unreachable."
def sendOnePing(mySocket, destAddr, ID):
global packageSent
# Header is type (😎, code (😎, checksum (16), id (16), sequence (16)
myChecksum = 0
# Make a dummy header with a 0 checksum.
# struct -- Interpret strings as packed binary data
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
data = struct.pack("d", time.time())
# Calculate the checksum on the data and the dummy header.
myChecksum = checksum(str(header + data))
# Get the right checksum, and put in the header
if sys.platform == 'darwin':
myChecksum = socket.htons(myChecksum) & 0xffff
#Convert 16-bit integers from host to network byte order.
else:
myChecksum = socket.htons(myChecksum)
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
packet = header + data
mySocket.sendto(packet, (destAddr, 1))
packageSent += 1
# AF_INET address must be tuple, not str
#Both LISTS and TUPLES consist of a number of objects
#which can be referenced by their position number within the object
def doOnePing(destAddr, timeout):
icmp = socket.getprotobyname("icmp")
#SOCK_RAW is a powerful socket type. For more details see:http://sock-raw.org/papers/sock_raw
#Fill in start
#Create Socket here
try:
mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
# conn, addr = mySocket.accept()
except socket.error (errno, msg):
if errno == 1:
raise socket.error(msg)
#Fill in end
myID = os.getpid() & 0xFFFF #Return the current process i
sendOnePing(mySocket, destAddr, myID)
delay = receiveOnePing(mySocket, myID, timeout, destAddr)
mySocket.close()
return delay
def ping(host, timeout=1):
#timeout=1 means: If one second goes by without a reply from the server,
dest = socket.gethostbyname(host)
print("Pinging " + dest + " using Python:")
print("")
#Send ping requests to a server separated by approximately one second
while 1 :
delay = doOnePing(dest, timeout)
print("RTT:",delay)
print("Package Lose Rate:", ((packageSent - packageRev)/packageSent if packageRev > 0 else 0))
time.sleep(1)# one second
return delay
ping("www.google.com") ```

Changing Bitcoin Wallet Address Range for Plutus.py

I am working with the following script from https://github.com/Isaacdelly/Plutus/blob/master/plutus.py
The script works for wallet addresses in the 2^160 range. I am curious where in the script I can change this to look at the 2^128 range or 2^n range. Would it be possible to even have a window? Like 2^0 - 2^100?
Not trying to do anything malicious, just trying to get data to show that even selecting ranges is futile due to the large number of addresses.
# Plutus Bitcoin Brute Forcer
# Made by Isaac Delly
# https://github.com/Isaacdelly/Plutus
try:
import sys
import os
import time
import hashlib
import binascii
import multiprocessing
from multiprocessing import Process, Queue
from multiprocessing.pool import ThreadPool
import threading
import base58
import ecdsa
import requests
except ImportError:
import subprocess
subprocess.check_call(["python", '-m', 'pip', 'install', 'base58==1.0.0'])
subprocess.check_call(["python", '-m', 'pip', 'install', 'ecdsa==0.13'])
subprocess.check_call(["python", '-m', 'pip', 'install', 'requests==2.19.1'])
import base58
import ecdsa
import requests
def generate_private_key():
return binascii.hexlify(os.urandom(32)).decode('utf-8')
def private_key_to_WIF(private_key):
var80 = "80" + str(private_key)
var = hashlib.sha256(binascii.unhexlify(hashlib.sha256(binascii.unhexlify(var80)).hexdigest())).hexdigest()
return str(base58.b58encode(binascii.unhexlify(str(var80) + str(var[0:8]))), 'utf-8')
def private_key_to_public_key(private_key):
sign = ecdsa.SigningKey.from_string(binascii.unhexlify(private_key), curve = ecdsa.SECP256k1)
return ('04' + binascii.hexlify(sign.verifying_key.to_string()).decode('utf-8'))
def public_key_to_address(public_key):
alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
count = 0; val = 0
var = hashlib.new('ripemd160')
var.update(hashlib.sha256(binascii.unhexlify(public_key.encode())).digest())
doublehash = hashlib.sha256(hashlib.sha256(binascii.unhexlify(('00' + var.hexdigest()).encode())).digest()).hexdigest()
address = '00' + var.hexdigest() + doublehash[0:8]
for char in address:
if (char != '0'):
break
count += 1
count = count // 2
n = int(address, 16)
output = []
while (n > 0):
n, remainder = divmod (n, 58)
output.append(alphabet[remainder])
while (val < count):
output.append(alphabet[0])
val += 1
return ''.join(output[::-1])
def get_balance(address):
try:
response = requests.get("https://bitaps.com/api/address/" + str(address))
return int(response.json()['balance'])
except:
return -1
def data_export(queue):
while True:
private_key = generate_private_key()
public_key = private_key_to_public_key(private_key)
address = public_key_to_address(public_key)
data = (private_key, address)
queue.put(data, block = False)
def worker(queue):
while True:
if not queue.empty():
data = queue.get(block = True)
balance = get_balance(data[1])
process(data, balance)
def process(data, balance):
private_key = data[0]
address = data[1]
if (balance == 0):
print("{:<34}".format(str(address)) + ": " + str(balance))
if (balance > 0):
file = open("plutus.txt","a")
file.write("address: " + str(address) + "\n" +
"private key: " + str(private_key) + "\n" +
"WIF private key: " + str(private_key_to_WIF(private_key)) + "\n" +
"public key: " + str(private_key_to_public_key(private_key)).upper() + "\n" +
"balance: " + str(balance) + "\n\n")
file.close()
def thread(iterator):
processes = []
data = Queue()
data_factory = Process(target = data_export, args = (data,))
data_factory.daemon = True
processes.append(data_factory)
data_factory.start()
work = Process(target = worker, args = (data,))
work.daemon = True
processes.append(work)
work.start()
data_factory.join()
if __name__ == '__main__':
try:
pool = ThreadPool(processes = multiprocessing.cpu_count()*2)
pool.map(thread, range(0, 10))
except:
pool.close()
exit()
Thank you
You seem to be misunderstanding the purpose of the 2^160 bit range.
Each standard bitcoin address is tied to the HASH160 of the public key. A HASH160 is 160 bits long, which is why your search space is 2^160. If you are able to find two private keys for which the HASH160 of the public keys are equal, any of those two private keys can spend coins sent to that address.
Searching a smaller space does not make sense since you are no longer searching for bitcoin addresses. If you just want to search random hash functions, then you simply need to replace RIPEMD160 hash function with another one that has an output in whatever bitsize you wish to search.
Note that if you do that, the rest of the code talking about checking balances etc. will be of no use, since your output will no longer be a bitcoin address.

Asynchronous data through Bloomberg's new data API (COM v3) with Python?

Does anyone know how to get asynchronous data through Bloomberg's new data API (COM v3) with Python? I found this code below on wilmott.com and it works just fine, but it's for the old API version.
Does anyone know the corresponding code for the new version?
from win32com.client import DispatchWithEvents
from pythoncom import PumpWaitingMessages, Empty, Missing
from time import time
class BBCommEvent:
def OnData(self, Security, cookie, Fields, Data, Status):
print 'OnData: ' + `Data`
def OnStatus(self, Status, SubStatus, StatusDescription):
print 'OnStatus'
class TestAsync:
def __init__(self):
clsid = '{F2303261-4969-11D1-B305-00805F815CBF}'
progid = 'Bloomberg.Data.1'
print 'connecting to BBComm'
blp = DispatchWithEvents(clsid, BBCommEvent)
blp.AutoRelease = False
blp.Subscribe('EUR Curncy', 1, 'LAST_PRICE', Results = Empty)
blp.Flush()
end_time = time() + 5
while 1:
PumpWaitingMessages()
if end_time < time():
print 'timed out'
break
if __name__ == "__main__":
ta = TestAsync()
I finally figured it out. I did a fair bit of combrowse.py detective work, and I compared with the JAVA, C, C++, and .NET examples in the BBG API download. Interestingly enough the Bloomberg Helpdesk people knew pretty much null when it came to these things, or perhaps I was just talking to the wrong person.
Here is my code.
asynchronousHandler.py:
import win32com.client
from pythoncom import PumpWaitingMessages
from time import time, strftime
import constants
class EventHandler:
def OnProcessEvent(self, result):
event = win32com.client.gencache.EnsureDispatch(result)
if event.EventType == constants.SUBSCRIPTION_DATA:
self.getData(event)
elif event.EventType == constants.SUBSCRIPTION_STATUS:
self.getStatus(event)
else:
self.getMisc(event)
def getData(self, event):
iterator = event.CreateMessageIterator()
while iterator.Next():
message = iterator.Message
dataString = ''
for fieldIndex, field in enumerate(constants.fields):
if message.AsElement.HasElement(field):
element = message.GetElement(field)
if element.IsNull:
theValue = ''
else:
theValue = ', Value: ' + str(element.Value)
dataString = dataString + ', (Type: ' + element.Name + theValue + ')'
print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + dataString
def getMisc(self, event):
iterator = event.CreateMessageIterator()
while iterator.Next():
message = iterator.Message
print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString
def getStatus(self, event):
iterator = event.CreateMessageIterator()
while iterator.Next():
message = iterator.Message
if message.AsElement.HasElement('reason'):
element = message.AsElement.GetElement('reason')
print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + ', Category: ' + element.GetElement('category').Value + ', Description: ' + element.GetElement('description').Value
if message.AsElement.HasElement('exceptions'):
element = message.AsElement.GetElement('exceptions')
exceptionString = ''
for n in range(element.NumValues):
exceptionInfo = element.GetValue(n)
fieldId = exceptionInfo.GetElement('fieldId')
reason = exceptionInfo.GetElement('reason')
exceptionString = exceptionString + ', (Field: ' + fieldId.Value + ', Category: ' + reason.GetElement('category').Value + ', Description: ' + reason.GetElement('description').Value + ') '
print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + exceptionString
class bloombergSource:
def __init__(self):
session = win32com.client.DispatchWithEvents('blpapicom.Session' , EventHandler)
session.Start()
started = session.OpenService('//blp/mktdata')
subscriptions = session.CreateSubscriptionList()
for tickerIndex, ticker in enumerate(constants.tickers):
if len(constants.interval) > 0:
subscriptions.AddEx(ticker, constants.fields, constants.interval, session.CreateCorrelationId(tickerIndex))
else:
subscriptions.Add(ticker, constants.fields, session.CreateCorrelationId(tickerIndex))
session.Subscribe(subscriptions)
endTime = time() + 2
while True:
PumpWaitingMessages()
if endTime < time():
break
if __name__ == "__main__":
aBloombergSource = bloombergSource()
constants.py:
ADMIN = 1
AUTHORIZATION_STATUS = 11
BLPSERVICE_STATUS = 9
PARTIAL_RESPONSE = 6
PUBLISHING_DATA = 13
REQUEST_STATUS = 4
RESOLUTION_STATUS = 12
RESPONSE = 5
SESSION_STATUS = 2
SUBSCRIPTION_DATA = 8
SUBSCRIPTION_STATUS = 3
TIMEOUT = 10
TOKEN_STATUS = 15
TOPIC_STATUS = 14
UNKNOWN = -1
fields = ['BID']
tickers = ['AUD Curncy']
interval = '' #'interval=5.0'
For historical data I used this simple script:
import win32com.client
session = win32com.client.Dispatch('blpapicom.Session')
session.QueueEvents = True
session.Start()
started = session.OpenService('//blp/refdata')
dataService = session.GetService('//blp/refdata')
request = dataService.CreateRequest('HistoricalDataRequest')
request.GetElement('securities').AppendValue('5 HK Equity')
request.GetElement('fields').AppendValue('PX_LAST')
request.Set('periodicitySelection', 'DAILY')
request.Set('startDate', '20090119')
request.Set('endDate', '20090130')
cid = session.SendRequest(request)
ADMIN = 1
AUTHORIZATION_STATUS = 11
BLPSERVICE_STATUS = 9
PARTIAL_RESPONSE = 6
PUBLISHING_DATA = 13
REQUEST_STATUS = 4
RESOLUTION_STATUS = 12
RESPONSE = 5
SESSION_STATUS = 2
SUBSCRIPTION_DATA = 8
SUBSCRIPTION_STATUS = 3
TIMEOUT = 10
TOKEN_STATUS = 15
TOPIC_STATUS = 14
UNKNOWN = -1
stayHere = True
while stayHere:
event = session.NextEvent();
if event.EventType == PARTIAL_RESPONSE or event.EventType == RESPONSE:
iterator = event.CreateMessageIterator()
iterator.Next()
message = iterator.Message
securityData = message.GetElement('securityData')
securityName = securityData.GetElement('security')
fieldData = securityData.GetElement('fieldData')
returnList = [[0 for col in range(fieldData.GetValue(row).NumValues+1)] for row in range(fieldData.NumValues)]
for row in range(fieldData.NumValues):
rowField = fieldData.GetValue(row)
for col in range(rowField.NumValues+1):
colField = rowField.GetElement(col)
returnList[row][col] = colField.Value
stayHere = False
break
element = None
iterator = None
message = None
event = None
session = None
print returnList
For it to work you need to install Bloomberg Desktop v3 API SDK, I did that, restarted my machine, seems to work. Without the restart it just crashed.
If you use Com explorer, you will see the bloomberg elements are now present

Categories