Giter Site home page Giter Site logo

omgbbqhaxx / cloudbankproject Goto Github PK

View Code? Open in Web Editor NEW
31.0 7.0 11.0 593 KB

Cloudbank project p2p digital currency with python3

Python 6.79% HTML 2.05% JavaScript 82.78% CSS 8.21% Shell 0.17%
ethereum blockchain bitcoin sha-256 rsa digital-signature kripto cryptography digital currency

cloudbankproject's People

Contributors

dependabot[bot] avatar omgbbqhaxx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

cloudbankproject's Issues

Incorrect Blockchain Usage

Hello, firstly your work is great, thank you for your open source contribution.

The logic of this project is basic and work but this is not suitable for today and future blockchain systems structure. You are using the transaction as blocks, this decrease the speed and scalability, also in the bigger network (ex: 10 transaction in a second) this usage is very problematic because everyone in the network wants the add transactions, but in your design winner is only 1 user and 1 transaction. The others transactions can not approve. Also the other nodes may have a problems. Lastly the new nodes should check the entire chain.

Contact me:
[email protected]

Onur Atakan ULUSOY | CTO of Decentra Network Community

ValueError: RSA key format is not supported

import uuid , json , string , random, urllib, base64, os, sys, time, pickle, collections
from django.utils.encoding import smart_str
from django.http import *
from django import template
from django.shortcuts import *
from django.http import HttpResponse
from django.contrib.auth import logout
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.decorators.csrf import csrf_protect, csrf_exempt
from django.conf import settings
#from cloudbank.myrsa import *
from django.db.models import Avg, Sum, Count
import base64, bson, websocket, hashlib
from core.models import transaction
from django.template.defaultfilters import stringfilter
#import netifaces as ni
from Crypto.PublicKey import RSA
#ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']
from Crypto.Cipher import PKCS1_v1_5

def landing(request):
try:
pubkey = request.session['pubkey'].encode('utf-8')
prikey = request.session['prikey'].encode('utf-8')
wallet_id = hashlib.sha256(pubkey).hexdigest() #SHA256.new(pubkey).hexdigest()
balance = getbalance(wallet_id)
if balance is None:
balance = 0
return render(request, "ok.html", locals())
except KeyError:
return render(request, "index.html", locals())

def login(request):
try:
pubkey = request.session['pubkey']
prikey = request.session['prikey']
return HttpResponseRedirect('/')
except KeyError:
return render(request, "login.html", locals())

def logout(request):
request.session.clear()
return HttpResponseRedirect('/')

def getbalance(wallet_id):
outgoing = transaction.objects.filter(senderhexdigest=wallet_id).aggregate(Sum('amount'))['amount__sum']
income = transaction.objects.filter(receiverhexdigest=wallet_id).aggregate(Sum('amount'))['amount__sum']
# print(outgoing)
# print(income)

if income and outgoing:
    # print("user have both")
    return(income - outgoing)
elif outgoing is None:
    # print("user dont have  outgoing")
    return income
elif income is None:
    return 0
else:
    return 0

def createnewwallet(request):
data = {}
mykey = RSA.generate(1024)
public_key = mykey.publickey().exportKey('PEM')
private_key = mykey.exportKey('PEM')
wallet_id = hashlib.sha256(public_key).hexdigest()
data["public_key"] = base64.b64encode(public_key).decode('utf-8')
data["private_key"] = base64.b64encode(private_key).decode('utf-8')
data["wallet_id"] = wallet_id
return HttpResponse(json.dumps(data), content_type="application/json")

@csrf_exempt
def checkwallet(request):
data = {}
if request.method == 'POST':
pubkey = request.POST.get('pubkey').strip()
prikey = request.POST.get('prikey').strip()
# print(pubkey)
try:
key = RSA.importKey(base64.b64decode(pubkey))
public_key = key.publickey()
enc_data = public_key.encrypt('cloudbank'.encode('utf-8'), 32)
pass_hex = base64.b64encode(enc_data[0])
enc_data = base64.b64decode(pass_hex)
newkey = RSA.importKey(base64.b64decode(prikey))
x = newkey.decrypt(enc_data)
except UnicodeDecodeError:
data["response"] = "Check your wallet details UnicodeDecodeError"
return HttpResponse(json.dumps(data), content_type = "application/json")
except TypeError:
data["response"] = "Check your wallet details"
return HttpResponse(json.dumps(data), content_type = "application/json")
except ValueError:
data["response"] = "Check your wallet details ValueError"
return HttpResponse(json.dumps(data), content_type = "application/json")
if x == "cloudbank".encode('utf-8'):
request.session['pubkey'] = base64.b64decode(pubkey).decode('utf-8')
request.session['prikey'] = base64.b64decode(prikey).decode('utf-8')
data["response"] = "access_approved"
return HttpResponse(json.dumps(data), content_type = "application/json")
else:
data["response"] = "access_denied"
return HttpResponse(json.dumps(data), content_type = "application/json")
else:
data["response"] = "ONLY POST"
return HttpResponse(json.dumps(data), content_type = "application/json")

def miner(first_timestamp, senderwalletid, receiverhex,amount):
data = {}
for nonce in range(0,10000000):
data['senderpublickey'] = str(senderwalletid) #1
data['receiverhex'] = str(receiverhex) #2
data['previous_hash'] = str(transaction.objects.all().last().blockhash) #3
data['amount'] = str(amount) #4
data['timestamp'] = str(first_timestamp) #5
data["nonce"] = str(nonce)
data = collections.OrderedDict(sorted(data.items()))
datashash = hashlib.sha256(json.dumps(data).encode('utf-8')).hexdigest()
last2char = datashash[-2:]
if last2char == "01":
return(nonce)
else:
# print(nonce)
continue

@csrf_exempt
def sendcloudcoin(request):
allify = {}
data = {}
if request.method == 'POST':
senderpubkey = request.POST.get('spubkey')
senderprivatekey = request.POST.get('sprikey').strip()
senderwalletid = request.POST.get('swid')
receiver = request.POST.get('pubkey').strip()
receiverhex = hashlib.sha256(base64.b64decode(receiver)).hexdigest()
amount = request.POST.get('amount').strip()

    if int(amount) <= 0:
        allify['response'] = "fail"
        return HttpResponse(json.dumps(allify), content_type = "application/json")

    balance = getbalance(senderwalletid)
    if balance is None:
        balance = 0
    if int(amount) > int(balance):
        allify['response'] = "fail"
        return HttpResponse(json.dumps(allify), content_type = "application/json")
    else:
        first_timestamp = time.time()
        data['senderpublickey'] = str(senderwalletid) #1
        data['receiverhex'] = str(receiverhex)      #2
        data['previous_hash'] = str(transaction.objects.all().last().blockhash) #3
        data['amount'] = str(amount) #4
        data['timestamp'] = str(first_timestamp) #5
        perfect =  miner(first_timestamp, senderwalletid, receiverhex, amount)
        data["nonce"] = str(perfect)
        data = collections.OrderedDict(sorted(data.items()))


        datashash  = hashlib.sha256(json.dumps(data).encode('utf-8')).hexdigest()
        # print(datashash)
        # print(datashash.encode('utf-8'))

        rsakey = RSA.importKey(senderprivatekey)
        digitalSignature = rsakey.sign(datashash.encode('utf-8'),'')
        digitalSignature = json.dumps(digitalSignature)

        newtrans = transaction(sender=base64.b64encode(senderpubkey.encode('utf-8')),
        senderhexdigest=senderwalletid,
        receiver=receiver,
        receiverhexdigest=receiverhex,
        prevblockhash=transaction.objects.all().last().blockhash,
        blockhash=datashash,
        amount=amount,
        nonce=perfect,
        first_timestamp=first_timestamp,
        P2PKH=digitalSignature,
        verification=True
        )
        newtrans.save()

        ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']

        # print("okasodkaod", newtrans.id)
        geturl = "http://{}/gettransaction/{}/".format(ip,newtrans.id)

        # print("gettypeprepe", type(receiverhex))
        test = {"server":False,
        "sender":base64.b64encode(senderpubkey.encode('utf-8')).decode('utf-8'),
        "senderhexdigest":senderwalletid,
        "receiver":receiver,
        "receiverhexdigest":receiverhex,
        "prevblockhash":transaction.objects.all().last().blockhash,
        "blockhash":datashash,
        "amount":amount,
        "nonce":perfect,
        "first_timestamp":first_timestamp,
        "P2PKH":digitalSignature,
        "verification":True,
        "block" : transaction.objects.all().last().id + 1,
        "message":"new_transaction",
        "url":geturl}

        payload = json.dumps(test)

        ws = websocket.WebSocket()
        wsip = "ws://{}:9000".format(ip)
        ws.connect(wsip)
        ws.send(payload)

        allify['response'] = "ok"
        allify['datashash'] = datashash
        allify['datastring'] = json.dumps(allify)
        return HttpResponse(json.dumps(allify), content_type = "application/json")

File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/opt/venv/cloudbank/cloudbank/views.py", line 168, in sendcloudcoin
rsakey = RSA.importKey(senderprivatekey)
File "/usr/local/lib/python3.5/dist-packages/Crypto/PublicKey/RSA.py", line 682, in importKey
raise ValueError("RSA key format is not supported")
ValueError: RSA key format is not supported

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.