- บทนำ
- 1. สิ่งที่จะได้เรียนรู้
- 2. Architecture
- 3. เตรียม Environment
- 4. Hash คืออะไร
- 5. สร้าง Block
- 6. สร้าง Blockchain
- 7. เพิ่ม Transaction
- 8. Proof of Work
- 9. Mine Pending Transactions
- 10. ตรวจสอบความถูกต้องของ Blockchain
- 11. โปรแกรมฉบับสมบูรณ์
- 12. รันโปรแกรม
- 13. ทดลองแก้ข้อมูลใน Blockchain
- 14. สิ่งที่ระบบนี้ยังไม่มี
- 15. ขั้นต่อไป: Wallet และ Digital Signature
- 16. ถ้าต้องการสร้าง Token จริง
- 17. Roadmap สำหรับ Workshop ต่อเนื่อง
- 18. สรุป
- แหล่งศึกษาเพิ่มเติม
บทความนี้เป็น Workshop เพื่อการศึกษา อธิบายหลักการทำงานของ Blockchain และ Cryptocurrency ด้วย Python โดยสร้าง Blockchain ขนาดเล็กขึ้นมาเอง ไม่ควรนำโค้ดตัวอย่างไปใช้จัดการสินทรัพย์จริงโดยไม่มีการออกแบบด้าน Security, Consensus และการตรวจสอบอย่างเหมาะสม
#บทนำ
การสร้าง “เหรียญ Crypto” อาจหมายถึง 2 แนวทางหลัก
- สร้าง Blockchain และ Native Coin ของตัวเอง เช่น Bitcoin มี BTC เป็นสินทรัพย์ของเครือข่าย
- สร้าง Token บน Blockchain ที่มีอยู่แล้ว เช่น ERC-20 บน Ethereum/EVM
บทความนี้เลือกแนวทางแรกเพื่อให้เห็นกลไกพื้นฐาน ได้แก่ Block, Hash, Blockchain, Transaction, Proof of Work, Mining และ Chain Validation โดยใช้ Python
ตัวอย่างจะเรียกเหรียญสมมติว่า NPRU Coin (NPRU)
#1. สิ่งที่จะได้เรียนรู้
หลังจบ Workshop จะสามารถอธิบายได้ว่า
- Blockchain เชื่อม Block เข้าด้วยกันอย่างไร
- SHA-256 Hash มีบทบาทอย่างไร
- Genesis Block คืออะไร
- Transaction ถูกบันทึกลง Block อย่างไร
- Proof of Work และ Mining ทำงานอย่างไรในระดับแนวคิด
- การแก้ข้อมูลย้อนหลังตรวจพบได้อย่างไร
- ระบบตัวอย่างต่างจาก Cryptocurrency ที่ใช้งานจริงอย่างไร
#2. Architecture
Alice Wallet
|
| 100 NPRU
v
+------------------+
| Transaction |
+------------------+
|
v
+------------------+
| Pending TX Pool |
+------------------+
|
| Mining
v
+------------------+
| Block #1 |
| transactions[] |
| previous_hash |
| nonce |
| hash |
+------------------+
|
v
+------------------+
| Block #2 |
| transactions[] |
| previous_hash |
| nonce |
| hash |
+------------------+
Block แต่ละตัวเก็บ previous_hash เพื่ออ้างอิง Block ก่อนหน้า ทำให้ข้อมูลเรียงต่อกันเป็น chain
#3. เตรียม Environment
ตรวจสอบ Python
python --version
หรือ
python3 --version
สร้างโครงการ
mkdir python-crypto
cd python-crypto
สร้างไฟล์
python-crypto/
└── blockchain.py
ตัวอย่างนี้ใช้ Python Standard Library จึงไม่จำเป็นต้องติดตั้ง package เพิ่มเติม
#4. Hash คืออะไร
Hash function แปลงข้อมูลเป็นค่าที่มีขนาดคงที่ ใน Workshop นี้ใช้ SHA-256
import hashlib
message = "Hello Blockchain"
hash_value = hashlib.sha256(
message.encode()
).hexdigest()
print(hash_value)
เมื่อข้อมูลต้นฉบับเปลี่ยน แม้เพียงเล็กน้อย hash ที่ได้ก็เปลี่ยนตาม
print(hashlib.sha256(b"Hello Blockchain").hexdigest())
print(hashlib.sha256(b"Hello blockchain").hexdigest())
คุณสมบัตินี้เป็นส่วนสำคัญของการตรวจจับการเปลี่ยนแปลงข้อมูลใน Blockchain
#5. สร้าง Block
เริ่มจาก import library
import hashlib
import json
import time
สร้าง class Block
class Block:
def __init__(
self,
index,
transactions,
previous_hash,
nonce=0
):
self.index = index
self.timestamp = time.time()
self.transactions = transactions
self.previous_hash = previous_hash
self.nonce = nonce
self.hash = self.calculate_hash()
def calculate_hash(self):
block_data = {
"index": self.index,
"timestamp": self.timestamp,
"transactions": self.transactions,
"previous_hash": self.previous_hash,
"nonce": self.nonce
}
block_string = json.dumps(
block_data,
sort_keys=True
)
return hashlib.sha256(
block_string.encode()
).hexdigest()
Block ประกอบด้วยข้อมูลสำคัญ เช่น
| Field | ความหมาย |
|---|---|
index |
ลำดับ Block |
timestamp |
เวลาที่สร้าง |
transactions |
รายการ Transaction |
previous_hash |
Hash ของ Block ก่อนหน้า |
nonce |
ค่าที่เปลี่ยนระหว่าง Mining |
hash |
Hash ของ Block ปัจจุบัน |
#6. สร้าง Blockchain
เพิ่ม class Blockchain
class Blockchain:
def __init__(self, difficulty=4):
self.chain = []
self.pending_transactions = []
self.difficulty = difficulty
self.create_genesis_block()
def create_genesis_block(self):
genesis = Block(
0,
[],
"0"
)
self.chain.append(genesis)
def get_latest_block(self):
return self.chain[-1]
#Genesis Block
Block แรกของ Blockchain เรียกว่า Genesis Block
Genesis Block
|
v
Block #1
|
v
Block #2
|
v
Block #3
เนื่องจากไม่มี Block ก่อนหน้า ตัวอย่างจึงกำหนด
previous_hash = "0"
#7. เพิ่ม Transaction
เพิ่ม method ต่อไปนี้ใน Blockchain
def add_transaction(self, sender, receiver, amount):
if amount <= 0:
raise ValueError("Amount must be greater than zero")
transaction = {
"sender": sender,
"receiver": receiver,
"amount": amount
}
self.pending_transactions.append(transaction)
ทดลองสร้าง Transaction
blockchain.add_transaction(
"Alice",
"Bob",
100
)
แนวคิดคือ
Alice
|
| 100 NPRU
v
Bob
ในระบบจริง การมีเพียงชื่อ Alice และ Bob ไม่เพียงพอ ต้องใช้ Address, Public Key, Private Key และ Digital Signature รวมถึงตรวจสอบยอดคงเหลือและป้องกัน Double Spending
#8. Proof of Work
เราจะสร้าง Proof of Work แบบง่าย โดยกำหนดให้ hash ต้องขึ้นต้นด้วยเลขศูนย์ตามจำนวน difficulty
เพิ่ม method
def mine_block(self, block):
target = "0" * self.difficulty
while not block.hash.startswith(target):
block.nonce += 1
block.hash = block.calculate_hash()
return block
ถ้า
difficulty = 4
เป้าหมายคือ hash ลักษณะนี้
0000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ระบบจะทดลองเปลี่ยน nonce
nonce = 0 -> 83fd...
nonce = 1 -> 217a...
nonce = 2 -> f902...
...
nonce = N -> 0000ab34... OK
ยิ่งกำหนด difficulty สูง จำนวนรอบที่ต้องทดลองโดยเฉลี่ยก็เพิ่มขึ้นอย่างรวดเร็ว
#9. Mine Pending Transactions
เพิ่ม method
def mine_pending_transactions(self):
if not self.pending_transactions:
return None
block = Block(
len(self.chain),
self.pending_transactions.copy(),
self.get_latest_block().hash
)
self.mine_block(block)
self.chain.append(block)
self.pending_transactions = []
return block
Flow จะเป็น
Transaction
|
v
Pending Transactions
|
v
Proof of Work
|
v
New Block
|
v
Blockchain
#10. ตรวจสอบความถูกต้องของ Blockchain
เพิ่ม method
def is_chain_valid(self):
for i in range(1, len(self.chain)):
current = self.chain[i]
previous = self.chain[i - 1]
if current.hash != current.calculate_hash():
return False
if current.previous_hash != previous.hash:
return False
if not current.hash.startswith(
"0" * self.difficulty
):
return False
return True
มีการตรวจสอบ 3 ประเด็น
- ข้อมูลปัจจุบันต้องคำนวณกลับมาเป็น hash เดิม
previous_hashต้องตรงกับ hash ของ Block ก่อนหน้า- Block ที่ mined ต้องผ่านเงื่อนไข Proof of Work
#11. โปรแกรมฉบับสมบูรณ์
สร้าง blockchain.py
import hashlib
import json
import time
class Block:
def __init__(
self,
index,
transactions,
previous_hash,
nonce=0
):
self.index = index
self.timestamp = time.time()
self.transactions = transactions
self.previous_hash = previous_hash
self.nonce = nonce
self.hash = self.calculate_hash()
def calculate_hash(self):
block_data = {
"index": self.index,
"timestamp": self.timestamp,
"transactions": self.transactions,
"previous_hash": self.previous_hash,
"nonce": self.nonce
}
block_string = json.dumps(
block_data,
sort_keys=True
)
return hashlib.sha256(
block_string.encode()
).hexdigest()
class Blockchain:
def __init__(self, difficulty=4):
self.chain = []
self.pending_transactions = []
self.difficulty = difficulty
self.create_genesis_block()
def create_genesis_block(self):
genesis = Block(
0,
[],
"0"
)
self.chain.append(genesis)
def get_latest_block(self):
return self.chain[-1]
def add_transaction(self, sender, receiver, amount):
if amount <= 0:
raise ValueError(
"Amount must be greater than zero"
)
transaction = {
"sender": sender,
"receiver": receiver,
"amount": amount
}
self.pending_transactions.append(transaction)
def mine_block(self, block):
target = "0" * self.difficulty
while not block.hash.startswith(target):
block.nonce += 1
block.hash = block.calculate_hash()
return block
def mine_pending_transactions(self):
if not self.pending_transactions:
return None
block = Block(
len(self.chain),
self.pending_transactions.copy(),
self.get_latest_block().hash
)
self.mine_block(block)
self.chain.append(block)
self.pending_transactions = []
return block
def is_chain_valid(self):
for i in range(1, len(self.chain)):
current = self.chain[i]
previous = self.chain[i - 1]
if current.hash != current.calculate_hash():
return False
if current.previous_hash != previous.hash:
return False
if not current.hash.startswith(
"0" * self.difficulty
):
return False
return True
blockchain = Blockchain(difficulty=4)
blockchain.add_transaction(
"Alice",
"Bob",
100
)
blockchain.add_transaction(
"Bob",
"Charlie",
25
)
print("Mining...")
mined_block = blockchain.mine_pending_transactions()
if mined_block:
print("Block mined:", mined_block.hash)
print("\nBlockchain")
for block in blockchain.chain:
print("-" * 60)
print("Block:", block.index)
print("Hash:", block.hash)
print("Previous Hash:", block.previous_hash)
print("Nonce:", block.nonce)
print("Transactions:", block.transactions)
print("\nValid:", blockchain.is_chain_valid())
#12. รันโปรแกรม
python blockchain.py
หรือ
python3 blockchain.py
ผลลัพธ์จะมีลักษณะประมาณนี้
Mining...
Block mined: 0000...
Blockchain
------------------------------------------------------------
Block: 0
Hash: ...
Previous Hash: 0
Nonce: 0
Transactions: []
------------------------------------------------------------
Block: 1
Hash: 0000...
Previous Hash: ...
Nonce: ...
Transactions: [
{'sender': 'Alice', 'receiver': 'Bob', 'amount': 100},
{'sender': 'Bob', 'receiver': 'Charlie', 'amount': 25}
]
Valid: True
ค่า hash และ nonce จะแตกต่างกันในแต่ละครั้ง เนื่องจาก timestamp และกระบวนการ mining
#13. ทดลองแก้ข้อมูลใน Blockchain
หลังจากสร้าง Block แล้ว ทดลองแก้ Transaction
blockchain.chain[1].transactions[0]["amount"] = 999999
print(
blockchain.is_chain_valid()
)
ผลลัพธ์
False
สาเหตุคือข้อมูล Transaction เปลี่ยน แต่ hash ที่บันทึกไว้ใน Block ไม่ตรงกับ hash ที่คำนวณจากข้อมูลใหม่
นี่แสดงแนวคิด tamper evidence ของ hash chain แต่ไม่ได้หมายความว่าโปรแกรมตัวอย่างนี้เป็น immutable distributed ledger แบบระบบจริง
#14. สิ่งที่ระบบนี้ยังไม่มี
Blockchain สำหรับการศึกษาในบทความนี้ยังขาดองค์ประกอบสำคัญ เช่น
- Public/Private Key
- Digital Signature
- Wallet Address
- Balance Validation
- Double-spending Protection
- Transaction Fee
- Mining Reward
- Merkle Tree
- Peer-to-Peer Network
- Distributed Nodes
- Consensus ระหว่างหลาย Node
- Persistent Database
- Network Synchronization
- Fork Resolution
- Smart Contract
- Security Audit
ดังนั้นไม่ควรนำระบบนี้ไปใช้กับเงินจริง
#15. ขั้นต่อไป: Wallet และ Digital Signature
Architecture ที่สมจริงขึ้นควรเป็น
Private Key
|
v
Sign Transaction
|
v
Digital Signature
|
v
Transaction
|
v
Verify with Public Key
|
v
Pending Transaction Pool
|
v
Mining / Consensus
|
v
Blockchain
Transaction จึงไม่ควรมีเพียง
{
"sender": "Alice",
"receiver": "Bob",
"amount": 100
}
แต่ควรมีข้อมูลเชิง cryptographic เช่น
{
"sender": "PUBLIC_KEY_OR_ADDRESS",
"receiver": "PUBLIC_KEY_OR_ADDRESS",
"amount": 100,
"signature": "DIGITAL_SIGNATURE"
}
Node ต้องตรวจสอบ signature ก่อนรับ Transaction
#16. ถ้าต้องการสร้าง Token จริง
หากเป้าหมายไม่ใช่สร้าง Blockchain ใหม่ แต่ต้องการสร้าง Fungible Token บน Ethereum/EVM แนวทางทั่วไปคือใช้ ERC-20 Smart Contract
Solidity
|
v
ERC-20 Smart Contract
|
v
Ethereum / EVM
^
|
web3.py
^
|
Python Application
Python เหมาะสำหรับเขียน application, deployment script, automation หรือ backend ที่เชื่อมต่อ Blockchain ผ่าน web3.py ส่วน Token contract มักเขียนด้วย Solidity และควรใช้ library มาตรฐานที่ผ่านการใช้งานอย่างกว้างขวาง เช่น OpenZeppelin Contracts
#17. Roadmap สำหรับ Workshop ต่อเนื่อง
Python
|
v
SHA-256 Hash
|
v
Block
|
v
Blockchain
|
v
Transaction
|
v
Proof of Work
|
v
Wallet + Digital Signature
|
v
FastAPI Blockchain Node
|
v
Multiple Nodes / Consensus
|
+-------------------------+
| |
v v
Educational Coin ERC-20 + web3.py
Workshop สามารถต่อยอดเป็นโครงสร้างโครงการ เช่น
python-crypto/
├── app/
│ ├── block.py
│ ├── blockchain.py
│ ├── transaction.py
│ ├── wallet.py
│ └── node.py
├── tests/
│ ├── test_block.py
│ ├── test_blockchain.py
│ └── test_transaction.py
├── main.py
├── pyproject.toml
└── README.md
จากนั้นใช้ FastAPI สร้าง REST API เช่น
POST /transactions
POST /mine
GET /chain
GET /validate
GET /balance/{address}
เพื่อจำลอง Blockchain Node หลายตัวได้
#18. สรุป
การสร้าง Blockchain ขนาดเล็กด้วย Python เป็นวิธีที่ดีในการเรียนรู้กลไกภายในของ Cryptocurrency เพราะทำให้เห็นความสัมพันธ์ระหว่าง
Transaction
↓
Block
↓
Hash
↓
Previous Hash
↓
Proof of Work
↓
Blockchain
อย่างไรก็ตาม Blockchain เพื่อการศึกษา กับ Cryptocurrency Production แตกต่างกันมาก ระบบจริงต้องพิจารณา Cryptography, Distributed Systems, Consensus, Economic Security, Key Management, Network Security และการตรวจสอบโค้ดอย่างรอบคอบ
สำหรับผู้เริ่มต้น ลำดับที่เหมาะสมคือเริ่มจาก Blockchain ด้วย Python ให้เข้าใจหลักการ แล้วต่อยอดไปยัง Wallet + Digital Signature, FastAPI Multi-node Blockchain และสุดท้ายจึงศึกษา ERC-20 + Solidity + web3.py
#แหล่งศึกษาเพิ่มเติม
- Python
hashlib: https://docs.python.org/3/library/hashlib.html - Python
json: https://docs.python.org/3/library/json.html - Ethereum Developers: https://ethereum.org/developers/
- web3.py: https://web3py.readthedocs.io/
- OpenZeppelin Contracts: https://docs.openzeppelin.com/contracts/
หมายเหตุ: เนื้อหาและ Source Code ในบทความนี้จัดทำเพื่อการศึกษาและการทดลองด้าน Software Engineering / Blockchain เท่านั้น ไม่ใช่คำแนะนำด้านการลงทุนหรือระบบสำหรับเก็บสินทรัพย์จริง