├── PyChain ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── settings.cpython-36.pyc │ ├── urls.cpython-36.pyc │ └── wsgi.cpython-36.pyc ├── settings.py ├── urls.py └── wsgi.py ├── blockchain ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── admin.cpython-36.pyc │ ├── models.cpython-36.pyc │ └── views.cpython-36.pyc ├── admin.py ├── apps.py ├── migrations │ ├── __init__.py │ └── __pycache__ │ │ └── __init__.cpython-36.pyc ├── models.py ├── tests.py └── views.py ├── db.sqlite3 ├── frontend ├── .gitignore ├── README.md ├── package-lock.json ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt └── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── components │ ├── send.js │ ├── status.js │ └── transactions.js │ ├── index.css │ ├── index.js │ ├── logo.svg │ └── serviceWorker.js ├── instructions.md ├── manage.py └── requirements.txt /PyChain/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kemoszn/PyChain/fd958db3be619adb9093f1c1a7de67726b0e2cc2/PyChain/__init__.py -------------------------------------------------------------------------------- /PyChain/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kemoszn/PyChain/fd958db3be619adb9093f1c1a7de67726b0e2cc2/PyChain/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /PyChain/__pycache__/settings.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kemoszn/PyChain/fd958db3be619adb9093f1c1a7de67726b0e2cc2/PyChain/__pycache__/settings.cpython-36.pyc -------------------------------------------------------------------------------- /PyChain/__pycache__/urls.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kemoszn/PyChain/fd958db3be619adb9093f1c1a7de67726b0e2cc2/PyChain/__pycache__/urls.cpython-36.pyc -------------------------------------------------------------------------------- /PyChain/__pycache__/wsgi.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kemoszn/PyChain/fd958db3be619adb9093f1c1a7de67726b0e2cc2/PyChain/__pycache__/wsgi.cpython-36.pyc -------------------------------------------------------------------------------- /PyChain/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for PyChain project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.2.6. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.2/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '^s)o14p$auv!401k(2(kv5=+ma*lajaab@rr%ksddaff-%7ug)' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'blockchain', 41 | 'corsheaders', 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'corsheaders.middleware.CorsMiddleware', 46 | 'django.middleware.security.SecurityMiddleware', 47 | 'django.contrib.sessions.middleware.SessionMiddleware', 48 | 'django.middleware.common.CommonMiddleware', 49 | 'django.middleware.csrf.CsrfViewMiddleware', 50 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 51 | 'django.contrib.messages.middleware.MessageMiddleware', 52 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 53 | ] 54 | 55 | ROOT_URLCONF = 'PyChain.urls' 56 | 57 | TEMPLATES = [ 58 | { 59 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 60 | 'DIRS': [], 61 | 'APP_DIRS': True, 62 | 'OPTIONS': { 63 | 'context_processors': [ 64 | 'django.template.context_processors.debug', 65 | 'django.template.context_processors.request', 66 | 'django.contrib.auth.context_processors.auth', 67 | 'django.contrib.messages.context_processors.messages', 68 | ], 69 | }, 70 | }, 71 | ] 72 | 73 | WSGI_APPLICATION = 'PyChain.wsgi.application' 74 | 75 | 76 | # Database 77 | # https://docs.djangoproject.com/en/2.2/ref/settings/#databases 78 | 79 | DATABASES = { 80 | 'default': { 81 | 'ENGINE': 'django.db.backends.sqlite3', 82 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 83 | } 84 | } 85 | 86 | 87 | # Password validation 88 | # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators 89 | 90 | AUTH_PASSWORD_VALIDATORS = [ 91 | { 92 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 93 | }, 94 | { 95 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 96 | }, 97 | { 98 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 99 | }, 100 | { 101 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 102 | }, 103 | ] 104 | 105 | 106 | # Internationalization 107 | # https://docs.djangoproject.com/en/2.2/topics/i18n/ 108 | 109 | LANGUAGE_CODE = 'en-us' 110 | 111 | TIME_ZONE = 'UTC' 112 | 113 | USE_I18N = True 114 | 115 | USE_L10N = True 116 | 117 | USE_TZ = True 118 | 119 | 120 | # Static files (CSS, JavaScript, Images) 121 | # https://docs.djangoproject.com/en/2.2/howto/static-files/ 122 | 123 | STATIC_URL = '/static/' 124 | 125 | CORS_ORIGIN_ALLOW_ALL = True 126 | CORS_ALLOW_CREDENTIALS = True 127 | #CORS_ORIGIN_WHITELIST = [ 128 | #'http://127.0.0.1:3000', 129 | #] 130 | #CORS_ORIGIN_REGEX_WHITELIST = [ 131 | # 'http://127.0.0.1:3000', 132 | #] 133 | -------------------------------------------------------------------------------- /PyChain/urls.py: -------------------------------------------------------------------------------- 1 | """PyChain URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from django.conf.urls import url 19 | from blockchain import views 20 | from blockchain.views import * 21 | 22 | urlpatterns = [ 23 | path('admin/', admin.site.urls), 24 | url('^get_chain$', views.get_chain, name="get_chain"), 25 | url('^mine_block$', views.mine_block, name="mine_block"), 26 | url('^add_transaction$', views.add_transaction, name="add_transaction"), 27 | url('^is_valid$', views.is_valid, name="is_valid"), 28 | url('^connect_node$', views.connect_node, name="connect_node"), 29 | url('^replace_chain$', views.replace_chain, name="replace_chain"), 30 | ] 31 | -------------------------------------------------------------------------------- /PyChain/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for PyChain project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PyChain.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /blockchain/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kemoszn/PyChain/fd958db3be619adb9093f1c1a7de67726b0e2cc2/blockchain/__init__.py -------------------------------------------------------------------------------- /blockchain/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kemoszn/PyChain/fd958db3be619adb9093f1c1a7de67726b0e2cc2/blockchain/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /blockchain/__pycache__/admin.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kemoszn/PyChain/fd958db3be619adb9093f1c1a7de67726b0e2cc2/blockchain/__pycache__/admin.cpython-36.pyc -------------------------------------------------------------------------------- /blockchain/__pycache__/models.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kemoszn/PyChain/fd958db3be619adb9093f1c1a7de67726b0e2cc2/blockchain/__pycache__/models.cpython-36.pyc -------------------------------------------------------------------------------- /blockchain/__pycache__/views.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kemoszn/PyChain/fd958db3be619adb9093f1c1a7de67726b0e2cc2/blockchain/__pycache__/views.cpython-36.pyc -------------------------------------------------------------------------------- /blockchain/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /blockchain/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class BlockchainConfig(AppConfig): 5 | name = 'blockchain' 6 | -------------------------------------------------------------------------------- /blockchain/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kemoszn/PyChain/fd958db3be619adb9093f1c1a7de67726b0e2cc2/blockchain/migrations/__init__.py -------------------------------------------------------------------------------- /blockchain/migrations/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kemoszn/PyChain/fd958db3be619adb9093f1c1a7de67726b0e2cc2/blockchain/migrations/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /blockchain/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /blockchain/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /blockchain/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | import datetime 3 | import hashlib 4 | import json 5 | from uuid import uuid4 6 | import socket 7 | from urllib.parse import urlparse 8 | from django.http import JsonResponse, HttpResponse, HttpRequest 9 | from django.views.decorators.csrf import csrf_exempt 10 | 11 | 12 | class Blockchain: 13 | 14 | def __init__(self): 15 | self.chain = [] 16 | self.transactions = [] 17 | self.create_block(nonce = 1, previous_hash = '0') 18 | self.nodes = set() 19 | 20 | def create_block(self, nonce, previous_hash): 21 | block = {'index': len(self.chain) + 1, 22 | 'timestamp': str(datetime.datetime.now()), 23 | 'nonce': nonce, 24 | 'previous_hash': previous_hash, 25 | 'transactions': self.transactions} 26 | self.transactions = [] 27 | self.chain.append(block) 28 | return block 29 | 30 | def get_last_block(self): 31 | return self.chain[-1] 32 | 33 | def proof_of_work(self, previous_nonce): 34 | new_nonce = 1 35 | check_nonce = False 36 | while check_nonce is False: 37 | hash_operation = hashlib.sha256(str(new_nonce**2 - previous_nonce**2).encode()).hexdigest() 38 | if hash_operation[:4] == '0000': 39 | check_nonce = True 40 | else: 41 | new_nonce += 1 42 | return new_nonce 43 | 44 | def hash(self, block): 45 | encoded_block = json.dumps(block, sort_keys = True).encode() 46 | return hashlib.sha256(encoded_block).hexdigest() 47 | 48 | def is_chain_valid(self, chain): 49 | previous_block = chain[0] 50 | block_index = 1 51 | while block_index < len(chain): 52 | block = chain[block_index] 53 | if block['previous_hash'] != self.hash(previous_block): 54 | return False 55 | previous_nonce = previous_block['nonce'] 56 | nonce = block['nonce'] 57 | hash_operation = hashlib.sha256(str(nonce**2 - previous_nonce**2).encode()).hexdigest() 58 | if hash_operation[:4] != '0000': 59 | return False 60 | previous_block = block 61 | block_index += 1 62 | return True 63 | 64 | def add_transaction(self, sender, receiver, amount, time): 65 | self.transactions.append({'sender': sender, 66 | 'receiver': receiver, 67 | 'amount': amount, 68 | 'time': str(datetime.datetime.now())}) 69 | previous_block = self.get_last_block() 70 | return previous_block['index'] + 1 71 | 72 | def add_node(self, address): 73 | parsed_url = urlparse(address) 74 | self.nodes.add(parsed_url.netloc) 75 | 76 | 77 | def replace_chain(self): 78 | network = self.nodes 79 | longest_chain = None 80 | max_length = len(self.chain) 81 | for node in network: 82 | response = requests.get(f'http://{node}/get_chain') 83 | if response.status_code == 200: 84 | length = response.json()['length'] 85 | chain = response.json()['chain'] 86 | if length > max_length and self.is_chain_valid(chain): 87 | max_length = length 88 | longest_chain = chain 89 | if longest_chain: 90 | self.chain = longest_chain 91 | return True 92 | return False 93 | 94 | 95 | # Creating our Blockchain 96 | blockchain = Blockchain() 97 | # Creating an address for the node running our server 98 | node_address = str(uuid4()).replace('-', '') 99 | root_node = 'e36f0158f0aed45b3bc755dc52ed4560d' 100 | 101 | # Mining a new block 102 | def mine_block(request): 103 | if request.method == 'GET': 104 | previous_block = blockchain.get_last_block() 105 | previous_nonce = previous_block['nonce'] 106 | nonce = blockchain.proof_of_work(previous_nonce) 107 | previous_hash = blockchain.hash(previous_block) 108 | blockchain.add_transaction(sender = root_node, receiver = node_address, amount = 1.15, time=str(datetime.datetime.now())) 109 | block = blockchain.create_block(nonce, previous_hash) 110 | response = {'message': 'Congratulations, you just mined a block!', 111 | 'index': block['index'], 112 | 'timestamp': block['timestamp'], 113 | 'nonce': block['nonce'], 114 | 'previous_hash': block['previous_hash'], 115 | 'transactions': block['transactions']} 116 | return JsonResponse(response) 117 | 118 | # Getting the full Blockchain 119 | def get_chain(request): 120 | if request.method == 'GET': 121 | response = {'chain': blockchain.chain, 122 | 'length': len(blockchain.chain)} 123 | return JsonResponse(response) 124 | 125 | # Checking if the Blockchain is valid 126 | def is_valid(request): 127 | if request.method == 'GET': 128 | is_valid = blockchain.is_chain_valid(blockchain.chain) 129 | if is_valid: 130 | response = {'message': 'All good. The Blockchain is valid.'} 131 | else: 132 | response = {'message': 'Houston, we have a problem. The Blockchain is not valid.'} 133 | return JsonResponse(response) 134 | 135 | # Adding a new transaction to the Blockchain 136 | @csrf_exempt 137 | def add_transaction(request): 138 | if request.method == 'POST': 139 | received_json = json.loads(request.body) 140 | transaction_keys = ['sender', 'receiver', 'amount','time'] 141 | if not all(key in received_json for key in transaction_keys): 142 | return 'Some elements of the transaction are missing', HttpResponse(status=400) 143 | index = blockchain.add_transaction(received_json['sender'], received_json['receiver'], received_json['amount'],received_json['time']) 144 | response = {'message': f'This transaction will be added to Block {index}'} 145 | return JsonResponse(response) 146 | 147 | # Connecting new nodes 148 | @csrf_exempt 149 | def connect_node(request): 150 | if request.method == 'POST': 151 | received_json = json.loads(request.body) 152 | nodes = received_json.get('nodes') 153 | if nodes is None: 154 | return "No node", HttpResponse(status=400) 155 | for node in nodes: 156 | blockchain.add_node(node) 157 | response = {'message': 'All the nodes are now connected. The Sudocoin Blockchain now contains the following nodes:', 158 | 'total_nodes': list(blockchain.nodes)} 159 | return JsonResponse(response) 160 | 161 | # Replacing the chain by the longest chain if needed 162 | def replace_chain(request): 163 | if request.method == 'GET': 164 | is_chain_replaced = blockchain.replace_chain() 165 | if is_chain_replaced: 166 | response = {'message': 'The nodes had different chains so the chain was replaced by the longest one.', 167 | 'new_chain': blockchain.chain} 168 | else: 169 | response = {'message': 'All good. The chain is the largest one.', 170 | 'actual_chain': blockchain.chain} 171 | return JsonResponse(response) 172 | -------------------------------------------------------------------------------- /db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kemoszn/PyChain/fd958db3be619adb9093f1c1a7de67726b0e2cc2/db.sqlite3 -------------------------------------------------------------------------------- /frontend/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /frontend/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `npm start` 8 | 9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `npm test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `npm run build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `npm run eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 35 | 36 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 37 | 38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | 46 | ### Code Splitting 47 | 48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting 49 | 50 | ### Analyzing the Bundle Size 51 | 52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size 53 | 54 | ### Making a Progressive Web App 55 | 56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app 57 | 58 | ### Advanced Configuration 59 | 60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration 61 | 62 | ### Deployment 63 | 64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment 65 | 66 | ### `npm run build` fails to minify 67 | 68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify 69 | -------------------------------------------------------------------------------- /frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "frontend", 3 | "version": "0.1.0", 4 | "private": true, 5 | "proxy": "http://127.0.0.1:8000", 6 | "dependencies": { 7 | "axios": "^0.19.0", 8 | "bootstrap": "^4.3.1", 9 | "font-awesome": "^4.7.0", 10 | "react": "^16.10.2", 11 | "react-bootstrap": "^1.0.0-beta.14", 12 | "react-dom": "^16.10.2", 13 | "react-scripts": "3.2.0" 14 | }, 15 | "scripts": { 16 | "start": "react-scripts start", 17 | "build": "react-scripts build", 18 | "test": "react-scripts test", 19 | "eject": "react-scripts eject" 20 | }, 21 | "eslintConfig": { 22 | "extends": "react-app" 23 | }, 24 | "browserslist": { 25 | "production": [ 26 | ">0.2%", 27 | "not dead", 28 | "not op_mini all" 29 | ], 30 | "development": [ 31 | "last 1 chrome version", 32 | "last 1 firefox version", 33 | "last 1 safari version" 34 | ] 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /frontend/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kemoszn/PyChain/fd958db3be619adb9093f1c1a7de67726b0e2cc2/frontend/public/favicon.ico -------------------------------------------------------------------------------- /frontend/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | 28 | 33 | React App 34 | 35 | 36 | 37 |
38 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /frontend/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kemoszn/PyChain/fd958db3be619adb9093f1c1a7de67726b0e2cc2/frontend/public/logo192.png -------------------------------------------------------------------------------- /frontend/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kemoszn/PyChain/fd958db3be619adb9093f1c1a7de67726b0e2cc2/frontend/public/logo512.png -------------------------------------------------------------------------------- /frontend/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /frontend/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | -------------------------------------------------------------------------------- /frontend/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | } 8 | 9 | .App-header { 10 | background-color: #282c34; 11 | min-height: 100vh; 12 | display: flex; 13 | flex-direction: column; 14 | align-items: center; 15 | justify-content: center; 16 | font-size: calc(10px + 2vmin); 17 | color: white; 18 | } 19 | 20 | .App-link { 21 | color: #09d3ac; 22 | } 23 | -------------------------------------------------------------------------------- /frontend/src/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import './App.css'; 3 | import Status from './components/status' 4 | import Send from './components/send' 5 | import Transactions from './components/transactions' 6 | import axios from 'axios'; 7 | 8 | const endpoint = '/mine_block' 9 | class App extends Component { 10 | constructor(props){ 11 | super(props); 12 | } 13 | componentWillMount() { 14 | axios.get(endpoint) 15 | } 16 | render(){ 17 | return ( 18 |
19 | 20 | 21 | 22 |
23 | ); 24 | } 25 | } 26 | 27 | export default App; 28 | -------------------------------------------------------------------------------- /frontend/src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /frontend/src/components/send.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { Form, Container, Col, Row, Button } from 'react-bootstrap'; 3 | import axios from 'axios'; 4 | 5 | const postEndpoint = '/add_transaction' 6 | const getEndpoint = '/get_chain' 7 | class Send extends Component { 8 | constructor(props){ 9 | super(props); 10 | this.state = { 11 | recipient: '', 12 | amount: 0, 13 | time: '', 14 | sender: '', 15 | } 16 | this.handleRecipient = this.handleRecipient.bind(this); 17 | this.handleAmount = this.handleAmount.bind(this); 18 | this.handleSubmit = this.handleSubmit.bind(this); 19 | } 20 | 21 | handleRecipient(event){ 22 | this.setState({ recipient: event.target.value}); 23 | } 24 | handleAmount(event){ 25 | this.setState({ amount: event.target.value}); 26 | } 27 | componentDidMount() { 28 | axios.get(getEndpoint) 29 | .then(res => { 30 | const sender = res.data.chain[1].transactions[0].receiver; 31 | this.setState({ sender }); 32 | }) 33 | } 34 | 35 | handleSubmit(event) { 36 | event.preventDefault(); 37 | 38 | axios.post(postEndpoint, { "sender": this.state.sender, 39 | "receiver": this.state.recipient, 40 | "amount": this.state.amount, 41 | "time": this.state.time }) 42 | .then(res => { 43 | console.log(res); 44 | console.log(res.data); 45 | }) 46 | } 47 | 48 | render(){ 49 | return ( 50 | 51 |
52 |

SudoCoin

53 |

Send unlimited dummy crypto to anyone.

54 |
55 | 56 | 57 | Recipient 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | Amount 66 | 67 | 68 | 69 | 70 | Sudo 71 | 72 | 73 | 74 | 77 | 78 | 79 |
80 |

81 |
82 | ); 83 | } 84 | } 85 | 86 | export default Send; 87 | -------------------------------------------------------------------------------- /frontend/src/components/status.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import 'bootstrap/dist/css/bootstrap.min.css'; 3 | import 'font-awesome/css/font-awesome.min.css'; 4 | import { Container, Row, Col } from 'react-bootstrap'; 5 | import axios from 'axios'; 6 | 7 | const endpoint = '/get_chain' 8 | class Status extends Component { 9 | constructor(props){ 10 | super(props); 11 | this.state = { 12 | length: [], 13 | address: '', 14 | } 15 | } 16 | 17 | componentDidMount() { 18 | axios.get(endpoint) 19 | .then(res => { 20 | const length = res.data.length; 21 | const address = res.data.chain[1].transactions[0].receiver; 22 | this.setState({ length, address }); 23 | }) 24 | } 25 | render(){ 26 | return ( 27 | 28 |
29 | 30 | 31 |
No. of Blocks Mined

32 |
#{this.state.length}
33 | 34 |
35 |
Node Address (sync )

36 |
0x{this.state.address}
37 | 38 |
39 |


40 |
41 | ); 42 | } 43 | } 44 | 45 | export default Status; 46 | -------------------------------------------------------------------------------- /frontend/src/components/transactions.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { Container, Table } from 'react-bootstrap'; 3 | import axios from 'axios'; 4 | 5 | const endpoint = '/get_chain' 6 | class Transactions extends Component { 7 | constructor(props){ 8 | super(props); 9 | this.state = { 10 | transactions: [], 11 | } 12 | } 13 | componentDidMount() { 14 | axios.get(endpoint) 15 | .then(res => { 16 | const transactions = res.data.chain; 17 | this.setState({ transactions }); 18 | }) 19 | } 20 | render(){ 21 | return ( 22 | 23 |

Transactions

24 |

(Sync to get the latest transactions in the blockchain)

25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | { this.state.transactions.slice(0).reverse().map(transaction => 36 | transaction.transactions.map( t => 37 | 38 | 39 | 40 | 41 | 42 | 43 | ))} 44 | 45 |
FromToAmount (Sudo)Timestamp
0x{t.sender}0x{t.receiver}{parseFloat(t.amount).toFixed(5)} {t.time}
46 |
47 | ); 48 | } 49 | } 50 | 51 | export default Transactions; 52 | -------------------------------------------------------------------------------- /frontend/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 4 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /frontend/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /frontend/src/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /frontend/src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl) 104 | .then(response => { 105 | // Ensure service worker exists, and that we really are getting a JS file. 106 | const contentType = response.headers.get('content-type'); 107 | if ( 108 | response.status === 404 || 109 | (contentType != null && contentType.indexOf('javascript') === -1) 110 | ) { 111 | // No service worker found. Probably a different app. Reload the page. 112 | navigator.serviceWorker.ready.then(registration => { 113 | registration.unregister().then(() => { 114 | window.location.reload(); 115 | }); 116 | }); 117 | } else { 118 | // Service worker found. Proceed as normal. 119 | registerValidSW(swUrl, config); 120 | } 121 | }) 122 | .catch(() => { 123 | console.log( 124 | 'No internet connection found. App is running in offline mode.' 125 | ); 126 | }); 127 | } 128 | 129 | export function unregister() { 130 | if ('serviceWorker' in navigator) { 131 | navigator.serviceWorker.ready.then(registration => { 132 | registration.unregister(); 133 | }); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /instructions.md: -------------------------------------------------------------------------------- 1 | ***To contribute to this project*** 2 | 1. Clone the project 3 | `$ git clone https://www.github.com/kemoszn/pychain.git` 4 | 2. Install pip 5 | `$ sudo apt install python3-pip` or `$ sudo apt install python-pip` 6 | 2. Install virtualenv 7 | `$ pip3 install virtualenv` or `$ pip install virtualenv` 8 | 3. Create a virtual enviroment in your project directory 9 | `$ virtualenv venv` 10 | 4. Activate the virtual enviroment you created and run the following command: 11 | `$ source venv/bin/activate` 12 | 5. Install the project requirements 13 | `$ pip install -r requirements.txt` 14 | 6. Migrate then run the project's backend server 15 | ``` 16 | $ python manage.py migrate 17 | $ python manage.py runserver 18 | ``` 19 | 7. Make sure that everything is working as expected by going to 127.0.0.1:8000/get_chain 20 | 8. Run NodeJS server from https://github.com/kemoszn/PyChain/blob/master/frontend/README.md 21 | 22 | 9. **Done!** 23 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PyChain.settings') 9 | try: 10 | from django.core.management import execute_from_command_line 11 | except ImportError as exc: 12 | raise ImportError( 13 | "Couldn't import Django. Are you sure it's installed and " 14 | "available on your PYTHONPATH environment variable? Did you " 15 | "forget to activate a virtual environment?" 16 | ) from exc 17 | execute_from_command_line(sys.argv) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Django==2.2.6 2 | django-cors-headers==3.1.1 3 | pytz==2019.3 4 | sqlparse==0.3.0 5 | --------------------------------------------------------------------------------