commit 56cd2a3f3f5ddee09d25f3266bf4e6e9cac46fae Author: kalzu Date: Sat Dec 17 22:39:21 2022 +0200 initial save of my chatGPT coding diff --git a/async-rsa-encryption.py b/async-rsa-encryption.py new file mode 100644 index 0000000..6e8f685 --- /dev/null +++ b/async-rsa-encryption.py @@ -0,0 +1,51 @@ +#!/usr/bin/python3 +import json +import base64 +import asyncio +from cryptography.fernet import Fernet +from cryptography.hazmat.primitives.asymmetric import rsa + + +# Generate a new RSA key pair +private_key = rsa.generate_private_key() +public_key = private_key.public_key() + + +# Asynchronously encrypt and decrypt a JSON document +async def encrypt_decrypt_json(json_data: dict) -> dict: + # Convert the JSON data to a string + json_str = json.dumps(json_data) + + # Encode the JSON string as bytes + json_bytes = json_str.encode() + + # Encrypt the JSON bytes using Fernet + fernet = Fernet(base64.urlsafe_b64encode(public_key.public_bytes( + encoding=rsa.Encoding.DER, + format=rsa.PublicFormat.SubjectPublicKeyInfo + ))) + encrypted_json_bytes = fernet.encrypt(json_bytes) + + # Decrypt the encrypted JSON bytes using Fernet + decrypted_json_bytes = fernet.decrypt(encrypted_json_bytes) + + # Decode the decrypted JSON bytes back to a string + decrypted_json_str = decrypted_json_bytes.decode() + + # Convert the decrypted JSON string back to a dictionary + decrypted_json_data = json.loads(decrypted_json_str) + + return decrypted_json_data + + +# Example usage +json_data = { + "user": "johnsmith", + "password": "correcthorsebatterystaple" +} + +# Asynchronously encrypt and decrypt the JSON data +decrypted_json_data = asyncio.run(encrypt_decrypt_json(json_data)) + +# Print the decrypted JSON + diff --git a/bitcoin-price-database.py b/bitcoin-price-database.py new file mode 100755 index 0000000..9b9a026 --- /dev/null +++ b/bitcoin-price-database.py @@ -0,0 +1,104 @@ +#!/usr/bin/python3 + +import os +import json +import sqlite3 +import requests +import matplotlib +import matplotlib.pyplot as plt +import matplotlib.animation as animation +import matplotlib.style as style + +def Checkthedatabase(): + ## Some sanity for the database + # check if btc_timeseries.db database file exists + if not os.path.exists("btc_timeseries.db"): + db = sqlite3.connect("btc_timeseries.db") + db.execute("CREATE TABLE timeseries (timestamp INTEGER, value REAL)") + db.commit() + db.close() + + db = sqlite3.connect("btc_timeseries.db") + + # Check if the table exists + table_exists = False + cursor = db.execute("PRAGMA table_info(timeseries)") + for row in cursor: + table_exists = True + + # Create the table if it doesn't exist + if not table_exists: + db.execute("CREATE TABLE timeseries (timestamp INTEGER, value REAL)") + db.commit() + +def Getdata(): + #fetch the price data + payload = {'symbol': 'BTCUSDT'} + response = requests.get('https://api.binance.com/api/v3/avgPrice', params=payload) + + #get the usd_value + json_data = response.json() + usd_value = json_data['price'] + + ### Insert the USD value into the database + db.execute("INSERT INTO timeseries (timestamp, value) VALUES (datetime('now'), ?)", (usd_value,)) + + ## Save the changes to the database + db.commit() + #print(db.execute("SELECT * FROM timeseries")) + +#update the graph +def Updategraph(num): + cursor.execute("SELECT timestamp, value FROM timeseries WHERE timestamp > datetime('now', '-10 second')") + stuff = cursor.fetchall() + + timestamps = [row[0] for row in stuff] + values = [row[1] for row in stuff] + + line.set_data(timestamps, values) + ax.relim() + ax.autoscale_view() + Getdata() + +Checkthedatabase() + +db = sqlite3.connect("btc_timeseries.db") +Getdata() + +##some styling for the plot +style.use('dark_background') + +colors = { + 'figure.facecolor': '#222222', + 'axes.facecolor': '#222222', + 'axes.edgecolor': '#FFFFFF', + 'axes.labelcolor': '#FFFFFF', + 'grid.color': '#444444', + 'grid.linestyle': 'dotted', + 'lines.color': '#FFFFFF' +} +matplotlib.rcParams.update(colors) + +# Create a figure and axes for the plot +fig, ax = plt.subplots() + +#query database for the data +cursor = db.execute("SELECT timestamp, value FROM timeseries") + +stuff = cursor.fetchall() +# Extract the timestamp and value columns from the query result +timestamps = [row[0] for row in stuff] +values = [row[1] for row in stuff] + +# Create a line plot using the time series data +line, = ax.plot(timestamps, values) +plt.plot(timestamps, values) + +# Create an animation using the update function +ani = animation.FuncAnimation(fig, Updategraph, interval=60000) + +# Show the plot +plt.show() + +db.close() +exit(0) diff --git a/btc_timeseries.db b/btc_timeseries.db new file mode 100644 index 0000000..7100493 Binary files /dev/null and b/btc_timeseries.db differ diff --git a/btc_tracker/fetch_data.py b/btc_tracker/fetch_data.py new file mode 100755 index 0000000..314744a --- /dev/null +++ b/btc_tracker/fetch_data.py @@ -0,0 +1,16 @@ +#!/usr/bin/python3 +import json, time + +# Load the JSON file +with open('sources.json', 'r') as f: + data = json.load(f) + +# Iterate over the exchanges +for exchange in data['exchanges']: + # Print the name and URL of the exchange + if exchange['name'] == "Kraken": + current_time = int(time.time()) - 300 + exchange['url'] += f"&since={current_time}" + print(exchange['name'], exchange['url']) + else: + print(exchange['name'], exchange['url']) diff --git a/btc_tracker/sources.json b/btc_tracker/sources.json new file mode 100644 index 0000000..d3c3aab --- /dev/null +++ b/btc_tracker/sources.json @@ -0,0 +1,24 @@ +{ + "exchanges": [ + { + "name": "Bitstamp", + "url": "https://www.bitstamp.net/api/v2/ohlc/btcusd/?step=300&limit=1", + "freq": "5" + }, + { + "name": "Kraken", + "url": "https://api.kraken.com/0/public/OHLC?pair=XBTUSD&interval=240", + "freq": "5" + }, + { + "name": "Bitfinex", + "url": "https://api-pub.bitfinex.com/v2/candles/trade:5m:tBTCUSD/last", + "freq": "5" + }, + { + "name": "Gemini", + "url": "https://api.gemini.com/v2/candles/btcusd/5m", + "freg": "5" + } + ] +} diff --git a/data-arbiter-todo b/data-arbiter-todo new file mode 100644 index 0000000..d68b0b6 --- /dev/null +++ b/data-arbiter-todo @@ -0,0 +1,25 @@ +from flask import Flask +import sqlite3 + +app = Flask(__name__) + +# Create a route for the web server +@app.route('/') +def serve_data(): + # Connect to the database + db = sqlite3.connect("btc_timeseries.db") + + # Fetch the data from the database + cursor = db.execute("SELECT * FROM timeseries") + data = cursor.fetchall() + + # Convert the data to JSON format + data_json = json.dumps(data) + + # Return the data as a response to the request + return data_json + +if __name__ == '__main__': + # Run the web server + app.run() + diff --git a/data-arbiter.py b/data-arbiter.py new file mode 100755 index 0000000..6e47df6 --- /dev/null +++ b/data-arbiter.py @@ -0,0 +1,88 @@ +#!/usr/bin/python3 + +import os, time +import json, math +import sqlite3 +import requests +from datetime import datetime, timezone + +def Checkthedatabase(): + ## Some sanity for the database + # check if btc_timeseries.db database file exists + if not os.path.exists("btc_timeseries.db"): + db = sqlite3.connect("btc_timeseries.db") + db.execute("CREATE TABLE timeseries (timestamp INTEGER, value REAL, mins INTEGER, source TEXT)") + db.commit() + + db = sqlite3.connect("btc_timeseries.db") + + # Check if the table exists + table_exists = False + cursor = db.execute("PRAGMA table_info(timeseries)") + for row in cursor: + table_exists = True + + # Create the table if it doesn't exist + if not table_exists: + db.execute("CREATE TABLE timeseries (timestamp INTEGER, value REAL, mins INTEGER, source TEXT)") + db.commit() + + db.close() + +def Getdata(): + #fetch the price data + source = 'http://api.binance.com/api/v3/avgPrice' + payload = {'symbol': 'BTCUSDT'} + response = requests.get(source, params=payload) + + #get the usd_value + json_data = response.json() + usd_value = json_data['price'] + mins = json_data['mins'] + + ### Insert the USD value into the database + db.execute("INSERT INTO timeseries (timestamp, value, mins, source) VALUES (datetime('now'), ?, ?, ?)", (usd_value, mins, source)) + + ## Save the changes to the database + db.commit() + #print(db.execute("SELECT * FROM timeseries")) + +def Calculatetimesince(): + cursor = db.execute("SELECT * FROM timeseries ORDER BY timestamp DESC LIMIT 1") + stuff = cursor.fetchall() + + timestamp = stuff[0][0] + mins = stuff[0][2] + + timenow = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") + dt1 = datetime.strptime(timenow, "%Y-%m-%d %H:%M:%S") + dt2 = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S") + delta = dt1 - dt2 + minutedelta = divmod(delta.total_seconds(), 60) + minutessince = math.trunc(minutedelta[0]) + + + # if minutes since last run is larger than mins we should get new data + print(minutessince, ' - ', mins) + if minutessince <= mins: + return 0 + else: + return 1 + +Checkthedatabase() + +db = sqlite3.connect("btc_timeseries.db") +Getdata() + +while True: + # Check if it's time to run again + mayberun = Calculatetimesince() + # we go on 1 + print(datetime.now(), 'We go on 1, should we go:', mayberun) + if mayberun == 1: + Getdata() + + time.sleep(20) + +db.close() +exit(0) diff --git a/demo-client.py b/demo-client.py new file mode 100755 index 0000000..ea7c6f8 --- /dev/null +++ b/demo-client.py @@ -0,0 +1,60 @@ +#!/usr/bin/python3 + +import requests +from hashlib import sha256 +import ecdsa + +private_key = '03486537091ceb021fb313e5cf3eb04d44ca2f19f72112a1' +# we need to send server: +# the question: domain.tld/get/ +# the checksum: ?sum=sha256 +# the signed data: header 'auth' + +id = 123 +url = 'localhost:5000/get/' +url_id = url + str(id) +sum = sha256(url_id.encode('ascii')).hexdigest() +reg_url = 'http://' + url_id + '?sum=' + sum + +unsigned_data = url_id + '?' + 'sum=' + sum + +# Generate SK from the private key +private_key_int = int(private_key, 16) +sk = ecdsa.SigningKey.from_secret_exponent(private_key_int, curve=ecdsa.SECP256k1) + +# sign the message +signature = sk.sign(unsigned_data.encode('utf-8')) +signature_hex = signature.hex() + +print('we signed: ', unsigned_data) +print('We will send:') +print('to: ', reg_url) +print('sum: ', sum) +print('auth: ', signature_hex) +print('------------------------') + +response = requests.get(reg_url, headers={"auth":signature_hex}) +print('>>> ', response.status_code) +print('>>> ', response.content) + +#ecdsa_public_key = '8716c78c09a4e4571a3112eca1c7ddce41289e20da446894b621f2a11ba91bc963f2e9fb9ddd5552c26faf814bc582b4' +ecdsa_public_key = '068716c78c09a4e4571a3112eca1c7ddce41289e20da446894b621f2a11ba91bc963f2e9fb9ddd5552c26faf814bc582b4' + +bytes_public_key = bytes.fromhex(ecdsa_public_key) + +bytes_signed_data = signature_hex.encode('utf-8') + + +vk = ecdsa.VerifyingKey.from_string(bytes_public_key, curve=ecdsa.SECP256k1) + +if vk.verify(signature_hex, unsigned_data): + response = "YES" +else: + response = "NO" + + + + + + +exit(0) diff --git a/encryption-on-apis/ecdsa-example-test.py b/encryption-on-apis/ecdsa-example-test.py new file mode 100755 index 0000000..375fd52 --- /dev/null +++ b/encryption-on-apis/ecdsa-example-test.py @@ -0,0 +1,49 @@ +#!/usr/bin/python3 + +import ecdsa, binascii, sys +from hashlib import sha256 + +message = 'Hello public/private key world!' +hashed_message = sha256(message.encode('utf-8')).hexdigest() + +m = message + hashed_message +print('') +print('to be signed: ', m) +to_be_signed = binascii.hexlify(m.encode('utf-8')) + +# Get the keys in their raw format +signing_key = ecdsa.SigningKey.generate() +public_key = signing_key.verifying_key + +signature = signing_key.sign(to_be_signed) +signature_hex = signature.hex() + +# deform_signature if deform argument is given +if len(sys.argv) > 1: + if sys.argv[1] == 'deform': + max_id = len(signature) + for i in range(max_id): + if i + 2 <= max_id: + mess_id = i + 2 + mess = signature[mess_id].to_bytes(4, 'big') + replace_me = signature[i].to_bytes(4, 'big') + #print('>>> replacing ', replace_me, ' with ', mess ) + print('>>> ', i, 'to', mess_id, ', max is: ', max_id) + signature = signature.replace(replace_me, mess ) + +print('signed: ', signature_hex) +print('') + +try: + is_valid = public_key.verify(signature, to_be_signed) +except ecdsa.keys.BadSignatureError: + is_valid = False + print('Something bad is on foot') + +if is_valid: + print('This is COOL') +else: + print('Something bad is on foot') + +exit(0) + diff --git a/encryption-on-apis/flask-encrypted-api.py b/encryption-on-apis/flask-encrypted-api.py new file mode 100755 index 0000000..3f4db85 --- /dev/null +++ b/encryption-on-apis/flask-encrypted-api.py @@ -0,0 +1,60 @@ +#!/usr/bin/python3 + +from flask import Flask +from flask import request +import ecdsa +import codecs + +ecdsa_public_key = '8716c78c09a4e4571a3112eca1c7ddce41289e20da446894b621f2a11ba91bc963f2e9fb9ddd5552c26faf814bc582b4' +#ecdsa_public_key = '048716c78c09a4e4571a3112eca1c7ddce41289e20da446894b621f2a11ba91bc963f2e9fb9ddd5552c26faf814bc582b4' +app = Flask(__name__) + +@app.route("/get/", methods=['get']) +def get(id): + + r_id = id + r_sum = request.args.get('sum') + r_auth = request.headers.get('auth') + + + print('---------------------------') + print('host: ', request.host) + print('full_path: ', request.full_path) + print('---------------------------') + print('id: ', r_id) + print('sum: ', r_sum) + print('header, auth:', r_auth) + + signed_data = request.host + request.full_path + + print('might have been signed: ', signed_data) + r_auth_bytes = bytes.fromhex(str(r_auth)) + + #x_coord = ecdsa_public_key[:64] + #y_coord = ecdsa_public_key[64:] + # + #if int(y_coord, 16) % 2 == 0: + # prefix = b'\x02' + #else: + # prefix = b'\x03' + # + #bytes_public_key = prefix + codecs.decode(x_coord, 'hex') + + bytes_public_key = bytes.fromhex(ecdsa_public_key) + + + bytes_signed_data = signed_data.encode('utf-8') + + + vk = ecdsa.VerifyingKey.from_string(bytes_public_key, curve=ecdsa.SECP256k1) + + if vk.verify(r_auth_bytes, bytes_signed_data): + response = "YES" + else: + response = "NO" + + return response + +if __name__== "__main__": + app.run() + diff --git a/encryption-on-apis/gen-ecdsa-private-key-v2.py b/encryption-on-apis/gen-ecdsa-private-key-v2.py new file mode 100644 index 0000000..4413428 --- /dev/null +++ b/encryption-on-apis/gen-ecdsa-private-key-v2.py @@ -0,0 +1,13 @@ +#!/usr/bin/python3 + +import ecdsa + +sk = ecdsa.SigningKey.generate(curve=ecdsa.SECP256k1) + +# Get the private key as a byte string +private_key_bytes = sk.to_string() + +# Convert the private key byte string to a hexadecimal string +private_key_hex = private_key_bytes.hex() + +print('private_key: ', private_key_hex) diff --git a/encryption-on-apis/gen-ecdsa-private-key.py b/encryption-on-apis/gen-ecdsa-private-key.py new file mode 100755 index 0000000..9ec6e92 --- /dev/null +++ b/encryption-on-apis/gen-ecdsa-private-key.py @@ -0,0 +1,15 @@ +#!/usr/bin/python3 + +import ecdsa + +# Generate a new random private key +signing_key = ecdsa.SigningKey.generate() + +# Get the private key as a byte string +private_key_bytes = signing_key.to_string() + +# Convert the private key byte string to a hexadecimal string +private_key_hex = private_key_bytes.hex() + +# Print the private key +print(private_key_hex) diff --git a/encryption-on-apis/gen-private-key.py b/encryption-on-apis/gen-private-key.py new file mode 100755 index 0000000..5901425 --- /dev/null +++ b/encryption-on-apis/gen-private-key.py @@ -0,0 +1,20 @@ +#!/usr/bin/python3 + +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives import serialization + + +def gen_key(): + private_key = ec.generate_private_key( + ec.SECP256K1(), default_backend() + ) + return private_key + + +if __name__ == '__main__': + + key = gen_key() + hexkey = key.private_numbers().private_value.to_bytes(32, 'big').hex() + + print(hexkey) diff --git a/encryption-on-apis/gen-public-key.py b/encryption-on-apis/gen-public-key.py new file mode 100755 index 0000000..5594d6e --- /dev/null +++ b/encryption-on-apis/gen-public-key.py @@ -0,0 +1,21 @@ +#!/usr/bin/python3 + +import sys +import ecdsa + +# read in the first argument that should be ecdsa key in hex form +private_key_hex = sys.argv[1] + +# Convert the private key from hexadecimal to an integer +private_key_int = int(private_key_hex, 16) + +#print(private_key_int) +## Create a signing key object from the private key +signing_key = ecdsa.SigningKey.from_secret_exponent(private_key_int) + +# Get the public key from the signing key object +public_key = signing_key.verifying_key + +# Print the public key in hexadecimal format +##print(public_key.to_string("uncompressed").hex()) +print(public_key.to_string("hybrid").hex()) diff --git a/encryption-on-apis/get-random-signed-string.py b/encryption-on-apis/get-random-signed-string.py new file mode 100755 index 0000000..3ed809a --- /dev/null +++ b/encryption-on-apis/get-random-signed-string.py @@ -0,0 +1,33 @@ +#!/usr/bin/python3 +import ecdsa +import os, sys +import hashlib + + +# check if the private key was provided as a command-line argument +if len(sys.argv) < 2: + print("Error: Private key not provided") + sys.exit(1) + +# generate a random byte string +random_bytes = os.urandom(32) + +# compute the SHA-512 hash of the random bytes +#sha512 = hashlib.sha512(random_bytes).hexdigest() +sha512 = 'http://localhost:5000/get/1' + +# read in the first argument that should be ecdsa key in hex form +private_key_hex = sys.argv[1] + +# Convert the private key from hexadecimal to an integer +private_key_int = int(private_key_hex, 16) + +# Generate SK from the private key +sk = ecdsa.SigningKey.from_secret_exponent(private_key_int, curve=ecdsa.SECP256k1) + +# sign the message +signature = sk.sign(sha512.encode()) + +# print the signature +print(signature) + diff --git a/encryption-on-apis/singe-endpoint-api.py b/encryption-on-apis/singe-endpoint-api.py new file mode 100755 index 0000000..8cba2d2 --- /dev/null +++ b/encryption-on-apis/singe-endpoint-api.py @@ -0,0 +1,39 @@ +#!/usr/bin/python3 + +## Single endpoint encrypted api + +from flask import Flask +from flask import request +from hashlib import sha256 + + +keys = { + 'key1': 'user1', + 'key2': 'user2' + } + +app = Flask(__name__) + +@app.route("/", methods=['post']) +def endpoint(hex_hash): + content_type = request.headers.get('content_type') + if content_type == 'application/json': + body = request.json + enc_data = body['foo'] + + ## decrypt the enc_data + dec_data = enc_data + + ## Get checksum to compare against + dec_data_hash = sha256(dec_data.encode('utf-8')).hexdigest() + r_hash = hex_hash.encode('utf-8') + print('if', r_hash, '==', dec_data_hash) + + response = "message: ", enc_data, "checksum: ", dec_data_hash + print(response) + return "YES" + else: + return 'Content-Type not supported' + +if __name__ == "__main__": + app.run() diff --git a/encryption-on-apis/stackoverflow-example.py b/encryption-on-apis/stackoverflow-example.py new file mode 100755 index 0000000..6c1d0b0 --- /dev/null +++ b/encryption-on-apis/stackoverflow-example.py @@ -0,0 +1,90 @@ +#!/usr/bin/python3 + +import ecdsa +import binascii +import requests +from hashlib import sha256 +from flask import Flask +from flask import request + + +##Generate them keys +# Generate private key (signing key) +sk = ecdsa.SigningKey.generate(curve=ecdsa.SECP256k1) +private_key_hex = sk.to_string().hex() + +public_key = sk.verifying_key +public_key_hex = binascii.hexlify(public_key.to_string()).decode('utf-8') + +keys = { + "private_key": private_key_hex, + "public_key": public_key_hex + } + +app = Flask(__name__) +line = '---------------------------------------' + +@app.route('/send') +def send(): + message = b"localhost:5000/get/123?sum=5f944f849124d36621d5f0708c7752a84fa9caa90bba629b8db93eea44cd0d1a" + + print(line) + print('private_key: ', keys['private_key']) + print(line) + + private_key_hex = keys['private_key'] + private_key = ecdsa.SigningKey.from_string(bytes.fromhex(private_key_hex), curve=ecdsa.SECP256k1) + + sig_hex = binascii.hexlify(private_key.sign(message)).decode('utf-8') + #print('sig:', sig_hex) + + reply = requests.get('http://localhost:5000/get', headers={"auth": sig_hex}) + + output_status = str(reply.status_code) + output_content = str(reply.content) + + return output_content, output_status + +@app.route('/get') +def get(): + #vk = sk.get_verifying_key() + # Get the public key from the signing key object + public_key = keys['public_key'] + print("public_key:", public_key) + print(line) + + # Get the sig from auth header + sig = request.headers.get('auth') + #print("vk2 - sig: ", sig) + + # Get sig to bytes format, from str + sig_bytes = bytes.fromhex(sig) + + ## BUILD THE "message" + message = b"localhost:5000/get/123?sum=5f944f849124d36621d5f0708c7752a84fa9caa90bba629b8db93eea44cd0d1a" + + vk = ecdsa.VerifyingKey.from_string(bytes.fromhex(public_key_hex), curve=ecdsa.SECP256k1) + + reply = '{' + if vk.verify(sig_bytes, message): + # print('vk1 # True ') + reply = reply + 'vk1: OK' + else: + # print('vk1 # False ') + reply = reply + 'vk1: ERROR' + + + vk2 = ecdsa.VerifyingKey.from_string(bytes.fromhex(public_key_hex), curve=ecdsa.SECP256k1) # the default is sha1 + if vk2.verify(sig_bytes, message): + # print('vk2 # True ') + reply = reply + ', vk2: OK' + else: + # print('vk2 # False ') + reply = reply + ', vk2: ERROR' + + reply = reply + '}' + #print(reply) + return reply + +if __name__ == "__main__": + app.run() diff --git a/encryption-on-apis/verify.py b/encryption-on-apis/verify.py new file mode 100755 index 0000000..f5b7619 --- /dev/null +++ b/encryption-on-apis/verify.py @@ -0,0 +1,25 @@ +#!/usr/bin/python3 + +import ecdsa +import sys + +# read the original message from the first command-line argument +message = sys.argv[1] + +# read the signature from standard input +signature = sys.stdin.read() + +# read the public key from the second command-line argument +public_key = sys.argv[2] + +print('message: ', message) +print('signature: ', signature) +print('public key: ', public_key) + + +# generate a verifying key from the public key +vk = ecdsa.VerifyingKey.from_string(public_key, curve=ecdsa.SECP256k1) + +# verify the signature +#assert vk.verify(signature, message.encode()) + diff --git a/graph-scatter.py b/graph-scatter.py new file mode 100644 index 0000000..6ab83b7 --- /dev/null +++ b/graph-scatter.py @@ -0,0 +1,15 @@ +import matplotlib.pyplot as plt + +# Create some sample data +x = [1, 2, 3, 4, 5] +y = [2, 4, 6, 8, 10] + +# Plot the data as points +plt.scatter(x, y) + +# Add labels to the axes +plt.xlabel('Time') +plt.ylabel('Value') + +# Show the plot +plt.show() diff --git a/letter-to-GPT.memo b/letter-to-GPT.memo new file mode 100644 index 0000000..ab29b7c --- /dev/null +++ b/letter-to-GPT.memo @@ -0,0 +1,49 @@ +I would like to have a program that contors to these rules: + +1. written in python3 +2. singe file + +And then makes these things: + +1. record the bitcoin price + + 1.1. by fetching: + source = 'http://api.binance.com/api/v3/avgPrice' + payload = {'symbol': 'BTCUSDT'} + response = requests.get(source, params=payload) + + binance api response is like: + { + "mins": 5, + "price: "170.20" + } + + 1.2. and storing it in sqlite3 or other embedded database + The database should hold these informations: + * timestamp as unix timestamp + * value of the symbol + * name of the symbol + * source of the symbol + + 1.3 + Fetch the price every "mins" minutes, something like: + time_delta = time.now() - timestamp_of_last_record + if time_delta <= mins_from_last_record + fetch_new_price_data() + +2. serve a http/json api to send the gathered price data forward + + Every response from this api should contain sha256 checksum as last element it is json document. + This api should be accessible by token authentication. + + 2.1 allow full dump of the database as json document + + 2.2 allow partial dump by getting limiting timestamp as of attribure from the http get reqeust + +3. Hold the sice of the files under control + + The database that holds the price data should be rotated every midnight. + So that we dont end up with large database files on the server. + +Can you generate this? +I think to make this work there needs to be threading. One thread for the data gathering and another for the api serving. diff --git a/letters/chatGPT-on-howto-send-and-receive-encrypted-post-body-with-python.memo b/letters/chatGPT-on-howto-send-and-receive-encrypted-post-body-with-python.memo new file mode 100644 index 0000000..2b59df3 --- /dev/null +++ b/letters/chatGPT-on-howto-send-and-receive-encrypted-post-body-with-python.memo @@ -0,0 +1,87 @@ +- how to send and receive encrypted http post body in python? + +To send and receive encrypted HTTP POST body data in Python, you can use the cryptography package to encrypt the data before sending it and to decrypt the data after receiving it. Here is an example of how this can be done: + +# Import the necessary modules +from cryptography.fernet import Fernet +from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC +from cryptography.hazmat.primitives import hashes +import base64 +import requests + +# Generate a secure key using PBKDF2 +password = "my_secret_password" +salt = b"my_secret_salt" +kdf = PBKDF2HMAC( + algorithm=hashes.SHA256(), + length=32, + salt=salt, + iterations=100000 +) +key = base64.urlsafe_b64encode(kdf.derive(password.encode())) + +# Initialize Fernet +fernet = Fernet(key) + +# Define the URL and the data to be sent +url = "https://www.example.com/post" +data = { + "username": "my_username", + "password": "my_password" +} + +# Encrypt the data +encrypted_data = fernet.encrypt(str(data).encode()) + +# Send the encrypted data as the POST body +response = requests.post(url, data=encrypted_data) + +# Decrypt the response data +decrypted_data = fernet.decrypt(response.content) + +# Print the decrypted data +print(decrypted_data) + +In this example, we first use the PBKDF2HMAC class from the cryptography package to generate a secure key that we will use to encrypt and decrypt the data. Then, we initialize a Fernet object with this key, and we define the URL and the data that we want to send as an encrypted HTTP POST request. + +Next, we use the encrypt() method of the Fernet object to encrypt the data, and we use the requests library to send the encrypted data as the POST body to the specified URL. + +Finally, we use the decrypt() method of the Fernet object to decrypt the response data, and we print it to verify that it matches the original data. + +This is just one way to send and receive encrypted HTTP POST body data in Python. There are many other encryption algorithms and libraries that you can use to achieve the same result. + + +- What is this Fernet? + +Fernet is a symmetric encryption algorithm that is part of the cryptography package in Python. It uses a secure key to encrypt and decrypt data, and it guarantees that the encrypted data cannot be altered or read without the key. + +Fernet is based on the Advanced Encryption Standard (AES) algorithm and uses a combination of symmetric encryption, a message authentication code (MAC), and a secure key derivation function (KDF) to provide strong encryption and integrity protection. It is considered to be very secure when used properly. + +In Python, Fernet is easy to use and can be integrated into a wide variety of applications that need to securely encrypt and decrypt data. Here is a simple example of how to use Fernet in Python: + +from cryptography.fernet import Fernet + +# Generate a secure key +key = Fernet.generate_key() + +# Initialize Fernet with the key +fernet = Fernet(key) + +# Define the data that we want to encrypt +data = "my_secret_message" + +# Encrypt the data +encrypted_data = fernet.encrypt(data.encode()) + +# Decrypt the data +decrypted_data = fernet.decrypt(encrypted_data) + +# Print the decrypted data to verify that it matches the original data +print(decrypted_data.decode()) + + +In this example, we first generate a secure key using the generate_key() method of the Fernet class. Then, we initialize a Fernet object with this key, and we define the data that we want to encrypt. + +Next, we use the encrypt() method of the Fernet object to encrypt the data, and we use the decrypt() method to decrypt the encrypted data. Finally, we print the decrypted data to verify that it matches the original data. + +This is just a simple example of how Fernet can be used in Python. In practice, you would need to securely store and manage the key, and you may want to use other methods or options provided by the cryptography package to customize the encryption and decryption process. diff --git a/letters/openGPT-btc-price-fetch.py b/letters/openGPT-btc-price-fetch.py new file mode 100644 index 0000000..76da8c6 --- /dev/null +++ b/letters/openGPT-btc-price-fetch.py @@ -0,0 +1,21 @@ +import requests + +def fetch_price_data(): + # Set up the URL and payload for the API request + source = 'http://api.binance.com/api/v3/avgPrice' + payload = {'symbol': 'BTCUSDT'} + + # Send the API request and parse the response + response = requests.get(source, params=payload) + data = response.json() + mins = data['mins'] + price = data['price'] + + # Store the data in the SQLite database + conn = sqlite3.connect('database.db') + cursor = conn.cursor() + cursor.execute('INSERT INTO price_data (timestamp, value, symbol, source) VALUES (?, ?, ?, ?)', (time.time(), price, 'BTCUSDT', 'Binance')) + conn.commit() + conn.close() + + return mins diff --git a/letters/openGPT-example-on-thread-locks.py b/letters/openGPT-example-on-thread-locks.py new file mode 100644 index 0000000..86ba83a --- /dev/null +++ b/letters/openGPT-example-on-thread-locks.py @@ -0,0 +1,19 @@ +import threading + +# Create a thread lock for the database +database_lock = threading.Lock() + +def write_to_database(data): + # Acquire the thread lock before accessing the database + with database_lock: + # Write data to the database + # (database logic goes here) + print('Wrote to the database') + +def rotate_database(): + # Acquire the thread lock before rotating the database + with database_lock: + # Rotate the database + # (database rotation logic goes here) + print('Rotated the database') + diff --git a/letters/openGPT-flask-api.py b/letters/openGPT-flask-api.py new file mode 100644 index 0000000..4ff9357 --- /dev/null +++ b/letters/openGPT-flask-api.py @@ -0,0 +1,37 @@ +from flask import Flask, request +import sqlite3 + +# Create a Flask app and set up the API endpoint +app = Flask(__name__) + +@app.route('/dump_db', methods=['GET']) +def dump_db(): + # Connect to the SQLite database + conn = sqlite3.connect('database.db') + cursor = conn.cursor() + + # Retrieve the data from the database + cursor.execute('SELECT * FROM price_data') + rows = cursor.fetchall() + + # Format the data as a JSON document + data = { + 'timestamp': [row[0] for row in rows], + 'value': [row[1] for row in rows], + 'symbol': [row[2] for row in rows], + 'source': [row[3] for row in rows], + } + + # Check if a timestamp was provided in the request + timestamp = request.args.get('timestamp') + if timestamp: + # Filter the data to only include rows with a timestamp greater than or equal to the provided value + data = {k: [v for i, v in enumerate(v) if data['timestamp'][i] >= timestamp] for k, v in data.items()} + + # Return the data as a JSON response + return data + +# Run the app +if __name__ == '__main__': + app.run() + diff --git a/letters/openGPT-python-threads.py b/letters/openGPT-python-threads.py new file mode 100644 index 0000000..6d7204c --- /dev/null +++ b/letters/openGPT-python-threads.py @@ -0,0 +1,22 @@ +from threading import Thread +from flask import Flask + +app = Flask(__name__) + +@app.route('/api') +def api(): + # API logic here + return 'API response' + +def data_request_task(): + # Data requesting logic here + print('Data request task finished') + +if __name__ == '__main__': + # Start the Flask API in a separate thread + api_thread = Thread(target=app.run) + api_thread.start() + + # Run the data requesting task + data_request_task() + diff --git a/letters/python-by-chatGPT.py b/letters/python-by-chatGPT.py new file mode 100644 index 0000000..13810ff --- /dev/null +++ b/letters/python-by-chatGPT.py @@ -0,0 +1,49 @@ +import http.server +import json + +from ecdsa import VerifyingKey, NIST384p + +user_and_tokens = { + "user1": ecdsa_public_key_from_user1 + } + +class RequestHandler(http.server.BaseHTTPRequestHandler): + + def do_POST(self): + if self.path == '/auth': + content_length = int(self.headers['Content-Length']) + request_data = json.loads(self.rfile.read(content_length)) + + # Check the JSON post data for the required fields + if 'person' not in request_data or 'signature' not in request_data: + self.send_response(400) + self.end_headers() + return + + person = request_data['person'] + signature = request_data['signature'] + + # Check the person data for the required fields + if 'user' not in person or 'token' not in person: + self.send_response(400) + self.end_headers() + return + + user = person['user'] + token = person['token'] + + # Check the signature data for the required fields + if 'signature' not in signature or 'curve' not in signature: + self.send_response(400) + self.end_headers() + return + + sig = signature['signature'] + curve = signature['curve'] + + # Verify the signature using the provided public key + vk = VerifyingKey.from_string(pre_delivered_public_key, curve=getattr(NIST384p, curve)) + if vk.verify(sig, user + token): + print("allow") + self.send_response(200) + diff --git a/letters/response-1.memo b/letters/response-1.memo new file mode 100644 index 0000000..5607135 --- /dev/null +++ b/letters/response-1.memo @@ -0,0 +1,15 @@ +Yes, it is possible to create a program in Python that satisfies the requirements you have outlined. Here is a rough outline of how such a program might work: + +The program will be written in Python 3 and be contained in a single file. + +To record the Bitcoin price, the program will use the requests module to fetch the price data from the Binance API. The response from the API will be parsed to extract the mins and price values, which will be stored in an SQLite database along with the current timestamp, the symbol name, and the source of the data. + +To ensure that the program fetches the price data at regular intervals, it will use a timer to check the time since the last data was fetched. If the time since the last fetch is greater than the mins value from the API response, the program will fetch new data. + +To serve the price data via an HTTP/JSON API, the program will use the flask module to create a server that listens for incoming HTTP requests. The server will be configured to require token authentication, and will provide two endpoints: one for dumping the entire database as a JSON document, and another for dumping a subset of the data based on a provided timestamp. + +To control the size of the database, the program will use a daily timer to rotate the database at midnight each day. This will involve creating a new database file and copying the data from the old database into the new one, then deleting the old database file. + +To implement the program, you will need to use Python's threading module to create separate threads for the data gathering and API serving processes. This will allow the program to fetch data and serve requests concurrently, ensuring that the API is always available and up-to-date. + +I hope this helps! Let me know if you have any other questions. diff --git a/pseudo-code b/pseudo-code new file mode 100644 index 0000000..7b3cb95 --- /dev/null +++ b/pseudo-code @@ -0,0 +1,27 @@ +my-web-auth-part.code + +open http listerner + +pre_delivered_public_key = 123456789 + +if reguest get to /auth + check for json post data + post data: + { + person: { + user: username + token: token + }, + signature: { + signature: ecdsa_signature + curve: curve + } + } + + if ecdsa.verify( username+token, pre_delivered_public_key ) + then + print "allow" + return "{ status: success }" + else + print "deny from: ", user + return "{ status: ", failure }" diff --git a/python-check-point.py b/python-check-point.py new file mode 100644 index 0000000..0035643 --- /dev/null +++ b/python-check-point.py @@ -0,0 +1,21 @@ +import matplotlib.pyplot as plt +import numpy as np + +# Create some sample data +x = [1, 5] +y = [2, 10] + +# Fit a line to the data using numpy +coefficients = np.polyfit(x, y, 1) +line = np.poly1d(coefficients) + +# Check if the point (3, 6) is above or below the line +point = (3, 2) +if point[1] > line(point[0]): + print('The point is above the line.') +else: + print('The point is below the line.') + +plt.plot(x, y) +plt.scatter(point[0], point[1], color='r') +plt.show() diff --git a/python-graph.py b/python-graph.py new file mode 100644 index 0000000..99497eb --- /dev/null +++ b/python-graph.py @@ -0,0 +1,19 @@ +import matplotlib.pyplot as plt + +# Create some sample data +x = [1, 5] +y = [2, 10] + +# Plot the data +plt.plot(x, y) + +# Add a point to the plot +plt.scatter([2], [6], color='r') + +# Add labels to the axes +plt.xlabel('Time') +plt.ylabel('Value') + +# Show the plot +plt.show() + diff --git a/shared-secret/chatgpt-example.py b/shared-secret/chatgpt-example.py new file mode 100755 index 0000000..4daec78 --- /dev/null +++ b/shared-secret/chatgpt-example.py @@ -0,0 +1,30 @@ +#!/usr/bin/python3 + +from secretsharing import PlaintextToHexSecretSharer + +# The secret that we want to split +secret = "my_secret_password" + +# The number of shares that we want to generate +n_shares = 5 + +# The threshold (i.e., the minimum number of shares required to reconstruct the secret) +threshold = 3 + +# Generate the shares +shares = PlaintextToHexSecretSharer.split_secret(secret, n_shares, threshold) + +# Print the shares +for share in shares: + print(share) + +# To reconstruct the secret, we need at least the threshold number of shares +# Let's say we have these three shares: +shares_to_reconstruct = [shares[0], shares[2], shares[4]] + +# Reconstruct the secret +secret = PlaintextToHexSecretSharer.recover_secret(shares_to_reconstruct) + +# Print the secret +print(secret) + diff --git a/test.price.json b/test.price.json new file mode 100644 index 0000000..24c8306 --- /dev/null +++ b/test.price.json @@ -0,0 +1 @@ +{"data":{"BTCAED":{"AED":63042.54,"BTC":0.00001586,"currency":"United Arab Emirates dirham"},"BTCAFN":{"AFN":1493268.24,"BTC":6.7e-7,"currency":"Afgan afghani"},"BTCALL":{"ALL":1881303.01,"BTC":5.3e-7,"currency":"Albanian lek"},"BTCAMD":{"AMD":6784931.61,"BTC":1.5e-7,"currency":"Armenian dram"},"BTCANG":{"ANG":30929.23,"BTC":0.00003233,"currency":"Netherlands Antillean guilder"},"BTCAOA":{"AOA":8653552.92,"BTC":1.2e-7,"currency":"Angolan kwanza"},"BTCARS":{"ARS":5398602.06,"BTC":1.85233e-7,"currency":"Argentine peso"},"BTCAUD":{"AUD":25261.23,"BTC":0.00003959,"currency":"Australian dollar"},"BTCAWG":{"AWG":30916.67,"BTC":0.00003235,"currency":"Aruban floring"},"BTCAZN":{"AZN":29178.81,"BTC":0.00003427,"currency":"Azerbaijani manat"},"BTCBAM":{"BAM":31804.71,"BTC":0.00003144,"currency":"Bosnia and Herzegovina convertible mark"},"BTCBBD":{"BBD":34328.01,"BTC":0.00002913,"currency":"Barbados dollar"},"BTCBDT":{"BDT":1773657.21,"BTC":5.6e-7,"currency":"Bangladeshi taka"},"BTCBGN":{"BGN":31865.06,"BTC":0.00003138,"currency":"Bulgarian Iev"},"BTCBHD":{"BHD":6471.05,"BTC":0.00015453,"currency":"Bahraini dinar"},"BTCBIF":{"BIF":35357852.55,"BTC":3e-8,"currency":"Burundian franc"},"BTCBMD":{"BMD":17164.01,"BTC":0.00005826,"currency":"Bermudian dollar"},"BTCBND":{"BND":23178.91,"BTC":0.00004314,"currency":"Brunei dollar"},"BTCBOB":{"BOB":118586.82,"BTC":0.00000843,"currency":"Boliviano"},"BTCBRL":{"BRL":89700.81,"BTC":0.00001115,"currency":"Brazilian real"},"BTCBSD":{"BSD":17164.01,"BTC":0.00005826,"currency":"Bahamian dollar"},"BTCBTN":{"BTN":1413153.39,"BTC":7.1e-7,"currency":"Bhutanese ngultrum"},"BTCBWP":{"BWP":221152.81,"BTC":0.00000452,"currency":"Botswana pula"},"BTCBYN":{"BYN":43315.51,"BTC":0.00002309,"currency":"Belarusian ruble"},"BTCBZD":{"BZD":34592.1,"BTC":0.00002891,"currency":"Belize dollar"},"BTCCAD":{"CAD":23401.27,"BTC":0.00004273,"currency":"Canadian dollar"},"BTCCDF":{"CDF":35266427.58,"BTC":3e-8,"currency":"Congolese franc"},"BTCCHF":{"CHF":16013.73,"BTC":0.00006245,"currency":"Swisse franc"},"BTCCLF":{"CLF":534.64,"BTC":0.00187042,"currency":"Unidad de Fomento"},"BTCCLP":{"CLP":14755209.48,"BTC":7e-8,"currency":"Chilean peso"},"BTCCNH":{"CNH":119601.21,"BTC":0.00000836},"BTCCNY":{"CNY":119423.72,"BTC":0.00000837,"currency":"Renminbi yuan"},"BTCCOP":{"COP":82875862.88,"BTC":1e-8,"currency":"Colombian peso"},"BTCCRC":{"CRC":10060076.33,"BTC":1e-7,"currency":"Costa Rican colon"},"BTCCUC":{"CUC":17164.01,"BTC":0.00005826,"currency":"Cuban convertible peso"},"BTCCUP":{"CUP":441973.16,"BTC":0.00000226,"currency":"Cuban peso"},"BTCCVE":{"CVE":1792988.36,"BTC":5.6e-7,"currency":"Cape Verdean escudo"},"BTCCZK":{"CZK":395619.77,"BTC":0.00000253,"currency":"Czech koruna"},"BTCDJF":{"DJF":3055064.27,"BTC":3.3e-7,"currency":"Djiboutian franc"},"BTCDKK":{"DKK":121110.62,"BTC":0.00000826,"currency":"Danish krone"},"BTCDOP":{"DOP":943627.57,"BTC":0.00000106,"currency":"Dominican peso"},"BTCDZD":{"DZD":2371419.86,"BTC":4.2e-7,"currency":"Algerian dinar"},"BTCEGP":{"EGP":422110.97,"BTC":0.00000237,"currency":"Egyptian pound"},"BTCERN":{"ERN":257460.09,"BTC":0.00000388,"currency":"Eritran nakfa"},"BTCETB":{"ETB":917967.66,"BTC":0.00000109,"currency":"Ethiopian birr"},"BTCEUR":{"EUR":16283.87,"BTC":0.00006141,"currency":"Euro"},"BTCFJD":{"FJD":37716.19,"BTC":0.00002651,"currency":"Fiji dollar"},"BTCFKP":{"FKP":13960.43,"BTC":0.00007163,"currency":"Falklan Island pound"},"BTCGBP":{"GBP":13960.43,"BTC":0.00007163,"currency":"Pound sterling"},"BTCGEL":{"GEL":45999.54,"BTC":0.00002174,"currency":"Georgian Iari"},"BTCGGP":{"GGP":13960.43,"BTC":0.00007163},"BTCGHS":{"GHS":222662.56,"BTC":0.00000449,"currency":"Ghanaian cedi"},"BTCGIP":{"GIP":13960.43,"BTC":0.00007163,"currency":"Gibraltar pound"},"BTCGMD":{"GMD":1070175.78,"BTC":9.3e-7,"currency":"Gambian dalasi"},"BTCGNF":{"GNF":147903939.91,"BTC":1e-8,"currency":"Guinean franc"},"BTCGTQ":{"GTQ":135726.97,"BTC":0.00000737,"currency":"Guatemalan quetzal"},"BTCGYD":{"GYD":3592386.24,"BTC":2.8e-7,"currency":"Guyanese dollar"},"BTCHKD":{"HKD":133605.16,"BTC":0.00000748,"currency":"Hong Kong dollar"},"BTCHNL":{"HNL":423648.62,"BTC":0.00000236,"currency":"Honduran lempira"},"BTCHRK":{"HRK":123021.3,"BTC":0.00000813,"currency":"Croatian kuna"},"BTCHTG":{"HTG":2438043.43,"BTC":4.1e-7,"currency":"Haitian gourde"},"BTCHUF":{"HUF":6806855.71,"BTC":1.5e-7,"currency":"Hungarian forint"},"BTCIDR":{"IDR":267523699.74,"BTC":0,"currency":"Indonesian rupiah"},"BTCILS":{"ILS":58678.59,"BTC":0.00001704,"currency":"Israeli new shekel"},"BTCIMP":{"IMP":13960.43,"BTC":0.00007163},"BTCINR":{"INR":1415412.5,"BTC":7.1e-7,"currency":"Indian rupee"},"BTCIQD":{"IQD":25047615.13,"BTC":4e-8,"currency":"Iraqi dinar"},"BTCIRR":{"IRR":718742755.05,"BTC":0},"BTCISK":{"ISK":2434370.98,"BTC":4.1e-7,"currency":"Icelandic króna"},"BTCJEP":{"JEP":13960.43,"BTC":0.00007163},"BTCJMD":{"JMD":2640793.61,"BTC":3.8e-7,"currency":"Jamaican dollar"},"BTCJOD":{"JOD":12174.43,"BTC":0.00008214,"currency":"Jordanian dinar"},"BTCJPY":{"JPY":2344549.29,"BTC":4.3e-7,"currency":"Japanese yen"},"BTCKES":{"KES":2108254.87,"BTC":4.7e-7,"currency":"Kenyan shilling"},"BTCKGS":{"KGS":1458082.32,"BTC":6.9e-7,"currency":"Kyrgyzstani som"},"BTCKHR":{"KHR":70775161.83,"BTC":1e-8,"currency":"Cambodian riel"},"BTCKMF":{"KMF":8004870.15,"BTC":1.2e-7,"currency":"Comoro franc"},"BTCKPW":{"KPW":15447605.48,"BTC":6e-8,"currency":"North Korean won"},"BTCKRW":{"KRW":22356317.24,"BTC":4e-8,"currency":"South Korean won"},"BTCKWD":{"KWD":5265.06,"BTC":0.00018993,"currency":"Kuwaiti dinar"},"BTCKYD":{"KYD":14301.58,"BTC":0.00006992,"currency":"Cayman Islands dollar"},"BTCKZT":{"KZT":8071985.5,"BTC":1.2e-7,"currency":"Kazakhstani tenge"},"BTCLAK":{"LAK":296778494.49,"BTC":0,"currency":"Lao kip"},"BTCLBP":{"LBP":25947723.02,"BTC":4e-8,"currency":"Lebanese pound"},"BTCLKR":{"LKR":6306911.15,"BTC":1.6e-7,"currency":"Sri Lankan rupee"},"BTCLRD":{"LRD":2643257.01,"BTC":3.8e-7,"currency":"Liberian dollar"},"BTCLSL":{"LSL":296758.63,"BTC":0.00000337,"currency":"Lesotho loti"},"BTCLYD":{"LYD":83193.01,"BTC":0.00001202,"currency":"Libyan dinar"},"BTCMAD":{"MAD":181122.2,"BTC":0.00000552,"currency":"Moroccan dirham"},"BTCMDL":{"MDL":331961.64,"BTC":0.00000301,"currency":"Moldovan leu"},"BTCMGA":{"MGA":75852972.03,"BTC":1e-8,"currency":"Malagasy ariary"},"BTCMKD":{"MKD":1002897.65,"BTC":0.000001,"currency":"Macedonian denar"},"BTCMMK":{"MMK":36039571.55,"BTC":3e-8,"currency":"Myanmar kyat"},"BTCMNT":{"MNT":58477172.56,"BTC":2e-8,"currency":"Mongolian tögrög"},"BTCMOP":{"MOP":137556.29,"BTC":0.00000727,"currency":"Macanese pataca"},"BTCMRO":{"MRO":6127547.22,"BTC":1.6e-7},"BTCMUR":{"MUR":749221.19,"BTC":0.00000133,"currency":"Mauritian rupee"},"BTCMVR":{"MVR":263467.49,"BTC":0.0000038,"currency":"Maldivian rufiyaa"},"BTCMWK":{"MWK":17615296.85,"BTC":6e-8,"currency":"Malawian kwache"},"BTCMXN":{"MXN":340276.78,"BTC":0.00000294,"currency":"Mexican peso"},"BTCMYR":{"MYR":75607.45,"BTC":0.00001323,"currency":"Malaysian ringgit"},"BTCMZN":{"MZN":1095921.81,"BTC":9.1e-7,"currency":"Mozamican metical"},"BTCNAD":{"NAD":294534.34,"BTC":0.0000034,"currency":"Namiian dollar"},"BTCNGN":{"NGN":7637467.79,"BTC":1.3e-7,"currency":"Nigerian naira"},"BTCNIO":{"NIO":626570.09,"BTC":0.0000016,"currency":"Nicaraguan córdoba"},"BTCNOK":{"NOK":171280.32,"BTC":0.00000584,"currency":"Norwegian krone"},"BTCNPR":{"NPR":2261048.2,"BTC":4.4e-7,"currency":"Nepalese rupee"},"BTCNZD":{"NZD":26783.25,"BTC":0.00003734,"currency":"New Zealand dollar"},"BTCOMR":{"OMR":6607.82,"BTC":0.00015134,"currency":"Omani rial"},"BTCPAB":{"PAB":17164.01,"BTC":0.00005826,"currency":"Panamanian balboa"},"BTCPEN":{"PEN":65952.69,"BTC":0.00001516,"currency":"Peruvian sol"},"BTCPGK":{"PGK":60471.04,"BTC":0.00001654,"currency":"Papua New Guinean kina"},"BTCPHP":{"PHP":950688.53,"BTC":0.00000105,"currency":"Philippine peso"},"BTCPKR":{"PKR":3857610.37,"BTC":2.6e-7,"currency":"Pakistan rupee"},"BTCPLN":{"PLN":76422.34,"BTC":0.00001309,"currency":"Polish złoty"},"BTCPYG":{"PYG":122557808.48,"BTC":1e-8,"currency":"Paraguayan guaraní"},"BTCQAR":{"QAR":62795.96,"BTC":0.00001592,"currency":"Qatari riyal"},"BTCRON":{"RON":80155.57,"BTC":0.00001248,"currency":"Romanian leu"},"BTCRSD":{"RSD":1909383.32,"BTC":5.2e-7,"currency":"Serbian dinar"},"BTCRUB":{"RUB":1073007.88,"BTC":9.3e-7,"currency":"Russian ruble"},"BTCRWF":{"RWF":18399026.67,"BTC":5e-8,"currency":"Rwandan franc"},"BTCSAR":{"SAR":64544.7,"BTC":0.00001549,"currency":"Saudi riyal"},"BTCSBD":{"SBD":140690.94,"BTC":0.00000711,"currency":"Solomon Islands dollar"},"BTCSCR":{"SCR":227596.95,"BTC":0.00000439,"currency":"Seychelles rupee"},"BTCSDG":{"SDG":9809229.48,"BTC":1e-7,"currency":"Sudanese pound"},"BTCSEK":{"SEK":177388.9,"BTC":0.00000564,"currency":"Swediss krona"},"BTCSGD":{"SGD":23206.77,"BTC":0.00004309,"currency":"Singapore dollar"},"BTCSHP":{"SHP":13960.43,"BTC":0.00007163,"currency":"Saint Helena leone"},"BTCSLL":{"SLL":303202167.59,"BTC":0,"currency":"Sierra Leonean leone"},"BTCSOS":{"SOS":9756533.39,"BTC":1e-7,"currency":"Somali shilling"},"BTCSRD":{"SRD":542245.28,"BTC":0.00000184,"currency":"Surinamese dollar"},"BTCSSP":{"SSP":2235783.43,"BTC":4.5e-7,"currency":"South Sudanese pound"},"BTCSTD":{"STD":391751112.03,"BTC":0},"BTCSVC":{"SVC":150170.62,"BTC":0.00000666,"currency":"Salvadoran colón"},"BTCSYP":{"SYP":43125080.22,"BTC":2e-8,"currency":"Syrian pound"},"BTCSZL":{"SZL":296758.65,"BTC":0.00000337,"currency":"Swazi lilangeni"},"BTCTHB":{"THB":595668.25,"BTC":0.00000168,"currency":"Thai baht"},"BTCTJS":{"TJS":173329.55,"BTC":0.00000577,"currency":"Tajikistani somoni"},"BTCTMT":{"TMT":60159.84,"BTC":0.00001662,"currency":"Turkmenistan manat"},"BTCTND":{"TND":55053.55,"BTC":0.00001816,"currency":"Tunisian dinar"},"BTCTOP":{"TOP":40203.9,"BTC":0.00002487,"currency":"Tongan pa'anga"},"BTCTRY":{"TRY":319976.76,"BTC":0.00000313,"currency":"Turkish lira"},"BTCTTD":{"TTD":116451.74,"BTC":0.00000859,"currency":"Trinid and Tobago dollar"},"BTCTWD":{"TWD":526222.7,"BTC":0.0000019,"currency":"New Taiwan dollar"},"BTCTZS":{"TZS":40041274.74,"BTC":2e-8,"currency":"Tanzanian shilling"},"BTCUAH":{"UAH":630571.53,"BTC":0.00000159,"currency":"Ukrainian hryvnia"},"BTCUGX":{"UGX":63325513.01,"BTC":2e-8,"currency":"Ugandan shilling"},"BTCUSD":{"USD":17164.01,"BTC":0.00005826,"currency":"United States dollar"},"BTCUYU":{"UYU":670184.25,"BTC":0.00000149,"currency":"Uruguyan peso"},"BTCUZS":{"UZS":193096822.03,"BTC":1e-8,"currency":"Uzbekistan som"},"BTCVES":{"VES":217050.01,"BTC":0.00000461,"currency":"Venezuelan bolívar soberano"},"BTCVND":{"VND":404668758.94,"BTC":0,"currency":"Vietnamese đồng"},"BTCVUV":{"VUV":2026107.93,"BTC":4.9e-7,"currency":"Vanuatu vatu"},"BTCWST":{"WST":46300.76,"BTC":0.0000216,"currency":"Samoan tala"},"BTCXAF":{"XAF":10681520.89,"BTC":9e-8},"BTCXAG":{"XAG":735.6,"BTC":0.00135943,"currency":"Silver"},"BTCXAU":{"XAU":9.55,"BTC":0.10471204,"currency":"Gold"},"BTCXCD":{"XCD":46386.58,"BTC":0.00002156,"currency":"East Caribbean dollar"},"BTCXDR":{"XDR":12948.9,"BTC":0.00007723},"BTCXOF":{"XOF":10681520.89,"BTC":9e-8,"currency":"CFA franc BCEAO"},"BTCXPD":{"XPD":8.83,"BTC":0.11325028},"BTCXPF":{"XPF":1943183.01,"BTC":5.1e-7},"BTCXPT":{"XPT":17.02,"BTC":0.05875441},"BTCYER":{"YER":4295291.44,"BTC":2.3e-7,"currency":"Yemen rial"},"BTCZAR":{"ZAR":298008.85,"BTC":0.00000336,"currency":"South African rand"},"BTCZMW":{"ZMW":298526.52,"BTC":0.00000335,"currency":"Zambian kwacha"},"BTCZWL":{"ZWL":5526809.96,"BTC":1.8e-7,"currency":"Zimabwean dollar"}}} \ No newline at end of file diff --git a/testing.py b/testing.py new file mode 100644 index 0000000..968f2b0 --- /dev/null +++ b/testing.py @@ -0,0 +1,59 @@ +#!/usr/bin/python3 + +import ecdsa +import binascii +import requests +from hashlib import sha256 +from flask import Flask +from flask import request + + +##Generate them keys +# Generate private key (signing key) +sk = ecdsa.SigningKey.generate(curve=ecdsa.SECP256k1) +private_key_hex = sk.to_string().hex() + +public_key = sk.verifying_key +public_key_hex = binascii.hexlify(public_key.to_string()).decode('utf-8') + +keys = { + "private_key": private_key_hex, + "public_key": public_key_hex + } + +app = Flask(__name__) + +@app.route('/send') +def send(): + message = b"localhost:5000/get/123?sum=5f944f849124d36621d5f0708c7752a84fa9caa90bba629b8db93eea44cd0d1a" + + print('private_key: ', private_key_hex) + sig = sk.sign(message) + + + reply = requests.get('http://localhost:5000/get/', headers={"auth": sig}) + return reply.str() + +@app.route('/get') +def get(): + #vk = sk.get_verifying_key() + # Get the public key from the signing key object + print("vk2 - public_key:", keys['public_key']) + + # Get the sig from auth header + sig = request.headers.get('auth') + + vk = ecdsa.VerifyingKey.from_string(bytes.fromhex(public_key_hex), curve=ecdsa.SECP256k1) + print('sig: ', binascii.hexlify(sig).decode('utf-8')) + if vk.verify(sig, message): + print('vk1 # True ') + else: + print('vk1 # False ') + + + vk2 = ecdsa.VerifyingKey.from_string(bytes.fromhex(public_key_hex), curve=ecdsa.SECP256k1) # the default is sha1 + if vk2.verify(sig, message): + print('vk2 # True ') + else: + print('vk2 # False ') + diff --git a/timeseries.db b/timeseries.db new file mode 100644 index 0000000..e69de29 diff --git a/webapp/celery-test.py b/webapp/celery-test.py new file mode 100755 index 0000000..d0ff549 --- /dev/null +++ b/webapp/celery-test.py @@ -0,0 +1,37 @@ +#!/usr/bin/python3 + +from celery import Celery +from celery.backends import sqlalchemy +from flask import Flask +import requests + +# create Flask app +app = Flask(__name__) + +# create a Celery app +celery_app = Celery('tasks') + +# configure the app to use the sqlalchemy backend and specify the SQLite database URL as the broker +app.conf.update( + result_backend='sqlalchemy', + broker_url='sqlite:///celery.db', + task_serializer='json', + result_serializer='json', +) + +@celery_app.task +def get_public_ip(): + response = requests.get('https://ifconfig.me/ip') + return response.text + +# define a Flask route that returns the current public IP address +@app.route('/public_ip') +def public_ip(): + # call the get_public_ip task and wait for it to complete + result = get_public_ip.delay().get() + + # return the task result as the response + return result + +if __name__ == '__main__': + app.run() diff --git a/webapp/flask-dump.py b/webapp/flask-dump.py new file mode 100755 index 0000000..7d03f22 --- /dev/null +++ b/webapp/flask-dump.py @@ -0,0 +1,70 @@ +#!/usr/bin/python3 +import json +import sqlite3 +import requests +import time +from flask import Flask + +# Initialize the Flask app +app = Flask(__name__) + +# Dump the contents of a SQLite database to the response +@app.route("/dump/") +def dump(ask_timestamp): + # Open the database connection + con = sqlite3.connect("../btc_timeseries.db") + + + # Create a cursor to navigate the database + cur = con.cursor() + + # Fetch all rows from the table + rows = cur.execute("SELECT * FROM timeseries").fetchall() + + data = { + "parameter": ask_timestamp, + "rows": rows + } + + # Build the response as a string + response = json.dumps(data) + + con.close() + + for row in rows: + old_timestamp = time.strptime(row[0], "%Y-%m-%d %H:%M:%S") + unix_timestamp = time.mktime(old_timestamp) + if int(ask_timestamp) < int(unix_timestamp): + print('EQUALS: ', ask_timestamp, ' AND ', unix_timestamp) + else: + print('NOPE ', row[0], ' AS ', unix_timestamp) + + return response + +#@app.route("/dump/timestamp") +#def dump(timestamp): +# # Open the database connection +# con = sqlite3.connect("../btc_timeseries.db") +# +# print(timestamp) +# +# # Create a cursor to navigate the database +# cur = con.cursor() +# +# # Fetch all rows from the table +# rows = cur.execute("SELECT * FROM timeseries").fetchall() +# +# # Build the response as a string +# response = "" +# for row in rows: +# response += ", ".join(row) + "\n" +# +# # Close the database connection +# con.close() +# +# # Return the response +# return response + +# Run the app +if __name__ == "__main__": + app.run() diff --git a/webapp/test.py b/webapp/test.py new file mode 100755 index 0000000..d713567 --- /dev/null +++ b/webapp/test.py @@ -0,0 +1,65 @@ +#!/usr/bin/python3 + +from celery import Celery +from celery.backends import sqlalchemy +from datetime import datetime +from flask import Flask +import requests +from sqlalchemy import create_engine, Column, Integer, String, DateTime +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker + +# create a Flask app +app = Flask(__name__) + +# create a Celery app and configure it to use the sqlalchemy backend and the SQLite database specified by the broker_url +celery_app = Celery('tasks') +celery_app.conf.update( + result_backend='sqlalchemy', + broker_url='sqlite:///celery.db', + task_serializer='json', + result_serializer='json', +) + +# define the get_public_ip Celery task (as in the previous example) +@celery_app.task +def get_public_ip(): + response = requests.get('https://ifconfig.me/ip') + return response.text + +# create an SQLAlchemy base class +Base = declarative_base() + +# define an IPHistory model that will be used to store IP addresses and timestamps in the database +class IPHistory(Base): + __tablename__ = 'ip_history' + + id = Column(Integer, primary_key=True) + ip_address = Column(String) + timestamp = Column(DateTime, default=datetime.now) + +# create a database engine and connect to the ip_history.db database +engine = create_engine('sqlite:///ip_history.db') +Base.metadata.create_all(engine) + +# create a session object that will be used to add records to the database +Session = sessionmaker(bind=engine) +session = Session() + +# define a Flask route that returns the current public IP address +@app.route('/public_ip') +def public_ip(): + # call the get_public_ip task and wait for it to complete + ip_address = get_public_ip.delay().get() + + # create a new IPHistory record and add it to the database + record = IPHistory(ip_address=ip_address) + session.add(record) + session.commit() + + # return the current IP address as the response + return ip_address + +if __name__ == '__main__': + app.run() +