Ask Cách xây dựng bản demo blockchain

biglion484

New member
#BlockChain #Demo #Build #tutorial #crypto ** Cách xây dựng một blockchain demo **

Blockchain là một công nghệ sổ cái phân tán được sử dụng để duy trì danh sách các hồ sơ phát triển liên tục, được gọi là các khối.Mỗi khối chứa một hàm băm mật mã của khối trước, dấu thời gian và dữ liệu giao dịch.Blockchains thường được quản lý bởi một mạng ngang hàng để tuân thủ một giao thức để giao tiếp giữa các nút và xác thực các khối mới.Sau khi được ghi lại, dữ liệu trong bất kỳ khối nào cũng không thể thay đổi hồi tố mà không thay đổi tất cả các khối tiếp theo, đòi hỏi sự thông đồng của đa số mạng.

Xây dựng một blockchain demo có thể là một cách thú vị và giáo dục để tìm hiểu thêm về công nghệ mới nổi này.Trong hướng dẫn này, chúng tôi sẽ hướng dẫn bạn trong quá trình tạo ra một blockchain đơn giản trong Python.

### Điều kiện tiên quyết

Để làm theo với hướng dẫn này, bạn sẽ cần những điều sau đây:

* Một máy tính với Python được cài đặt
* The [Flask] (Welcome to Flask — Flask Documentation (2.1.x)) Khung Web
* [Postgresql] (PostgreSQL) Hệ thống quản lý cơ sở dữ liệu

### Tạo blockchain

Bước đầu tiên là tạo một tệp python mới có tên là `blockchain.py`.Tệp này sẽ chứa tất cả các mã cho blockchain của chúng tôi.

`` `Python
Nhập khẩu Hashlib
Nhập JSON
Từ bình nhập bình, Jsonify, yêu cầu
từ flask_sqlalchemy nhập sqlalchemy

Ứng dụng = Flask (__ name__)
app.config ['sqlalchemy_database_uri'] = 'postgresql: // localhost/blockchain'
app.config ['sqlalchemy_track_modifications'] = false

db = sqlalchemy (Ứng dụng)

khối lớp (db.model):
id = db.column (db.integer, chính_key = true)
Dấu thời gian = db.column (db.dateTime, index = true)
data = db.column (db.string)
Hash = db.column (DB.String)
trước_hash = db.column (db.String)

def __init __ (self, dấu thời gian, dữ liệu, trước đó_hash):
self.timestamp = dấu thời gian
self.data = dữ liệu
self.hash = self.calculation_hash ()
self.previous_hash = trước_hash

def calculate_hash (tự):
"" "
Tính toán băm của khối.
"" "
block_string = json.dumps (self.to_dict (), sort_keys = true)
trả về hashlib.sha256 (block_string.encode ()). hexdigest ()

@App.Route ('/Mine', Phương thức = ['Post']))
def mine ():
"" "
Mỏ một khối mới và thêm nó vào blockchain.
"" "
# Nhận dữ liệu cho khối mới từ thân yêu cầu.
data = request.get_json ()

# Tạo một khối mới và thêm nó vào blockchain.
new_block = block (
Timestamp = datetime.utcnow (),
Dữ liệu = dữ liệu,
trước_hash = blockchain [-1] .hash
)
db.session.add (new_block)
db.session.Commit ()

# Trả về băm của khối mới.
trả về jsonify ({'băm': new_block.hash}))

@App.Route ('/Chuỗi', Phương thức = ['Get']))
chuỗi def ():
"" "
Trả về toàn bộ blockchain.
"" "
# Nhận tất cả các khối từ cơ sở dữ liệu.
blocks = block.query.all ()

# Trả lại các khối theo thứ tự.
trả về jsonify ([block.to_dict () cho khối trong các khối])

Nếu __name__ == '__main__':
app.run (gỡ lỗi = true)
`` `

Mã này tạo ra một lớp mới gọi là `block` đại diện cho một khối trong blockchain.Lớp `block` có các thuộc tính sau:

* `id`: mã định danh duy nhất cho
=======================================
#BlockChain #Demo #Build #tutorial #crypto **How to Build a Demo Blockchain**

Blockchain is a distributed ledger technology that is used to maintain a continuously growing list of records, called blocks. Each block contains a cryptographic hash of the previous block, a timestamp, and transaction data. Blockchains are typically managed by a peer-to-peer network collectively adhering to a protocol for inter-node communication and validating new blocks. Once recorded, the data in any given block cannot be altered retroactively without the alteration of all subsequent blocks, which requires collusion of the network majority.

Building a demo blockchain can be a fun and educational way to learn more about this emerging technology. In this tutorial, we will walk you through the process of creating a simple blockchain in Python.

### Prerequisites

To follow along with this tutorial, you will need the following:

* A computer with Python installed
* The [Flask](https://flask.palletsprojects.com/en/2.1.x/) web framework
* The [PostgreSQL](https://www.postgresql.org/) database management system

### Creating the Blockchain

The first step is to create a new Python file called `blockchain.py`. This file will contain all of the code for our blockchain.

```python
import hashlib
import json
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/blockchain'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class Block(db.Model):
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime, index=True)
data = db.Column(db.String)
hash = db.Column(db.String)
previous_hash = db.Column(db.String)

def __init__(self, timestamp, data, previous_hash):
self.timestamp = timestamp
self.data = data
self.hash = self.calculate_hash()
self.previous_hash = previous_hash

def calculate_hash(self):
"""
Calculates the hash of the block.
"""
block_string = json.dumps(self.to_dict(), sort_keys=True)
return hashlib.sha256(block_string.encode()).hexdigest()

@app.route('/mine', methods=['POST'])
def mine():
"""
Mines a new block and adds it to the blockchain.
"""
# Get the data for the new block from the request body.
data = request.get_json()

# Create a new block and add it to the blockchain.
new_block = Block(
timestamp=datetime.utcnow(),
data=data,
previous_hash=blockchain[-1].hash
)
db.session.add(new_block)
db.session.commit()

# Return the hash of the new block.
return jsonify({'hash': new_block.hash})

@app.route('/chain', methods=['GET'])
def chain():
"""
Returns the entire blockchain.
"""
# Get all of the blocks from the database.
blocks = Block.query.all()

# Return the blocks in order.
return jsonify([block.to_dict() for block in blocks])

if __name__ == '__main__':
app.run(debug=True)
```

This code creates a new class called `Block` that represents a block in the blockchain. The `Block` class has the following attributes:

* `id`: The unique identifier for the
 
Join Telegram ToolsKiemTrieuDoGroup
Back
Top