Untitled
unknown
plain_text
2 years ago
7.6 kB
8
Indexable
import datetime
import hashlib
import json
from flask import Flask, jsonify
from flask import render_template
class Blockchain:
def __init__(self):
self.chain = []
self.create_block(proof=1, previous_hash='0', body='')
def create_block(self, proof, previous_hash, body):
block = {'index': len(self.chain) + 1,
'timestamp': str(datetime.datetime.now()),
'proof': proof,
'previous_hash': previous_hash,
'body': body}
self.chain.append(block)
return block
def print_previous_block(self):
return self.chain[-1]
def proof_of_work(self, previous_proof):
new_proof = 1
check_proof = False
while check_proof is False:
hash_operation = hashlib.sha256(
str(new_proof**2 - previous_proof**2).encode()).hexdigest()
if hash_operation[:5] == '00000':
check_proof = True
else:
new_proof += 1
return new_proof
def hash(self, block):
encoded_block = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(encoded_block).hexdigest()
def chain_valid(self, chain):
previous_block = chain[0]
block_index = 1
while block_index < len(chain):
block = chain[block_index]
if block['previous_hash'] != self.hash(previous_block):
return False
previous_proof = previous_block['proof']
proof = block['proof']
hash_operation = hashlib.sha256(
str(proof**2 - previous_proof**2).encode()).hexdigest()
if hash_operation[:5] != '00000':
return False
previous_block = block
block_index += 1
return True
app = Flask(__name__)
blockchain = Blockchain()
@app.route('/mine_block', methods=['GET'])
def mine_block(body):
previous_block = blockchain.print_previous_block()
previous_proof = previous_block['proof']
proof = blockchain.proof_of_work(previous_proof)
previous_hash = blockchain.hash(previous_block)
block = blockchain.create_block(proof, previous_hash, body)
response = {'message': 'A block is MINED',
'index': block['index'],
'timestamp': block['timestamp'],
'proof': block['proof'],
'previous_hash': block['previous_hash'],
'body': block['body']}
return jsonify(response), 200
@app.route('/get_chain', methods=['GET'])
def display_chain():
response = {'chain': blockchain.chain,
'length': len(blockchain.chain)}
return jsonify(response), 200
@app.route('/valid', methods=['GET'])
def valid():
valid = blockchain.chain_valid(blockchain.chain)
if valid:
response = {'message': 'The Blockchain is valid.'}
else:
response = {'message': 'The Blockchain is not valid.'}
return jsonify(response), 200
#self.create_block(proof=1, previous_hash='0', body='')
#mine_block('<h1>Статья2</h1><p>Текст статьи 2</p>')
#mine_block('<h1>Статья3</h1><p>Текст статьи 3</p>')
def test_init(body):
previous_block = blockchain.print_previous_block()
previous_proof = previous_block['proof']
proof = blockchain.proof_of_work(previous_proof)
previous_hash = blockchain.hash(previous_block)
block = blockchain.create_block(proof, previous_hash, body)
test_init('<h1>Блокчейн</h1><p> - выстроенная по определённым правилам непрерывная последовательная цепочка блоков (связный список), содержащих какую-либо информацию. Связь между блоками обеспечивается не только нумерацией, но и тем, что каждый блок содержит свою собственную хеш-сумму и хеш-сумму предыдущего блока. Изменение любой информации в блоке изменит его хеш-сумму. </p>')
test_init('<h1>Энциклопедия</h1><p> - приведённое в систему обозрение всех отраслей человеческого знания или круга дисциплин, в совокупности составляющих отдельную отрасль знания </p>')
test_init('<h1>Интернет</h1><p> -коммуникационная сеть и всемирная система объединённых компьютерных сетей для хранения и передачи информации</p>')
import telebot
import time
bot = telebot.TeleBot('6930570585:AAEdmedLhpaQ_553gJ42spQael3vh9px_Is')
markup = telebot.types.ReplyKeyboardMarkup()
buttons = [
telebot.types.KeyboardButton(text='Загрузить'),
telebot.types.KeyboardButton(text='Начать проверку'),
#telebot.types.KeyboardButton(text='Загрузить'),
telebot.types.KeyboardButton(text='Справка'),
]
stop_markup = telebot.types.InlineKeyboardMarkup()
stop_button = telebot.types.InlineKeyboardButton(text='Остановить ввод', callback_data='stop')
stop_markup.add(stop_button)
for i in buttons:
markup.add(i)
questions = []
answers = []
step_count = 0
@bot.message_handler(commands=['start'])
def start(message):
bot.send_message(message.chat.id, text='Приветсвие(дописать)....', reply_markup=markup)
#time.sleep(2)
#bot.edit_message_text(text='Новый', chat_id=msg1.chat.id, message_id=msg1.id, reply_markup=markup)
@bot.message_handler(content_types=['text'])
def menu_listener(message):
if message.text == 'Загрузить':
bot.send_message(message.chat.id, text='Условия загрузки билетов: отправляйте вопросы и ответы на них по одному, разными сообщение')
bot.register_next_step_handler(message, procces_new_question)
elif message.text == 'Начать проверку':
pass
elif message.text == 'Справка':
pass
def procces_new_question(message):
global step_count
step_count += 1
if step_count % 2 == 1:
questions.append(message.text)
elif step_count % 2 == 0:
answers.append(message.text)
bot.send_message(message.chat.id,text='Билет '+str(step_count//2),reply_markup=stop_markup)
bot.register_next_step_handler(message, procces_new_question)
@bot.callback_query_handler(func = lambda call: True)
def callback_query(call):
if call.data == 'stop':
bot.register_next_step_handler(call.message, menu_listener)
bot.polling(non_stop=True)
@app.route('/index', methods=['GET'])
def index():
list_of_articles = []
for i in blockchain.chain:
list_of_articles.append(i['body'][:50])
return render_template('index.html', articles=list_of_articles)
@app.route('/articles/<int:article_id>')
def get_article(article_id):
for i in blockchain.chain:
if i['index'] == article_id:
return i['body']
app.run(host='127.0.0.1', port=5000)
Editor is loading...
Leave a Comment