|
Python,創建,加密貨幣
隨著當前加密貨幣的興起,區塊鏈正在技術世界中引起轟動。這項技術之所以引起如此多的關注,主要是因為它能夠保證安全性、實施去中心化以及加快多個行業的流程——尤其是金融行業。
從本質上講,區塊鍊是一個公共數據庫,不可逆轉地記錄和驗證數字資產的擁有和傳輸。比特幣和以太坊等數字貨幣就是基於這個概念。區塊鍊是一項令人興奮的技術,您可以使用它來轉換應用程序的功能。
最近,我們已經看到政府、組織和個人使用區塊鏈技術來創建自己的加密貨幣,並避免被拋在後面。值得注意的是,當 Facebook 提出自己的加密貨幣Libra 時,這一聲明在全球範圍內掀起了軒然大波。
如果您也可以效仿並創建自己的加密貨幣版本怎麼辦?
我考慮了這一點並決定開發一種算法來創建加密。
我決定將加密貨幣稱為 fccCoin。
在本教程中,我將說明我用來構建數字貨幣的分步過程(我使用了Python編程語言的面向對象概念)。
以下是創建fccCoin 的區塊鏈算法的基本藍圖:
- class Block:
- def __init__():
- #first block class
- pass
-
- def calculate_hash():
- #calculates the cryptographic hash of every block
-
- class BlockChain:
- def __init__(self):
- # constructor method
- pass
-
- def construct_genesis(self):
- # constructs the initial block
- pass
- def construct_block(self, proof_no, prev_hash):
- # constructs a new block and adds it to the chain
- pass
- @staticmethod
- def check_validity():
- # checks whether the blockchain is valid
- pass
- def new_data(self, sender, recipient, quantity):
- # adds a new transaction to the data of the transactions
- pass
- @staticmethod
- def construct_proof_of_work(prev_proof):
- # protects the blockchain from attack
- pass
-
- @property
- def last_block(self):
- # returns the last block in the chain
- return self.chain[-1]
複製代碼
現在,讓我解釋一下正在發生的事情……
1. 構建第一個 Block 類
區塊鏈由幾個相互連接的塊組成(聽起來很熟悉,對吧?)。
區塊鏈發生這樣的情況,如果一個區塊被篡改,則鏈的其餘部分將無效。
在應用上述概念時,我創建了以下初始塊類:
- import hashlib
- import time
- class Block:
- def __init__(self, index, proof_no, prev_hash, data, timestamp=None):
- self.index = index
- self.proof_no = proof_no
- self.prev_hash = prev_hash
- self.data = data
- self.timestamp = timestamp or time.time()
- @property
- def calculate_hash(self):
- block_of_string = "{}{}{}{}{}".format(self.index, self.proof_no, self.prev_hash, self.data,self.timestamp)
- return hashlib.sha256(block_of_string.encode()).hexdigest()
- def __repr__(self):
- return "{} - {} - {} - {} - {}".format(self.index, self.proof_no,
- self.prev_hash, self.data,
- self.timestamp)
複製代碼
從上面的代碼可以看出,我定義了__init__()函數,它將在Block類啟動時執行,就像在任何其他 Python 類中一樣。
我為啟動函數提供了以下參數:
self — 引用Block類的實例,從而可以訪問與該類關聯的方法和屬性;
index——跟踪區塊在區塊鏈中的位置;
proof_no —這是在創建新區塊(稱為挖礦)期間產生的數字;
prev_hash——這是指鏈中前一個區塊的哈希值;
data——這給出了所有已完成交易的記錄,例如購買的數量;
timestamp——這為交易放置了一個時間戳。
類中的第二個方法calculate_hash將使用上述值生成塊的哈希值。項目導入SHA-256模塊,輔助獲取區塊的哈希值。
在將值輸入到加密哈希算法中後,該函數將返回一個 256 位的字符串,表示塊的內容。
這就是在區塊鏈中實現安全性的方式——每個區塊都有一個哈希值,而該哈希值將依賴於前一個區塊的哈希值。
因此,如果有人試圖破壞鏈中的任何塊,其他塊將具有無效的哈希值,從而導致整個區塊鍊網絡中斷。
最終,一個塊將如下所示:
- {
- "index": 2,
- "proof": 21,
- "prev_hash": "6e27587e8a27d6fe376d4fd9b4edc96c8890346579e5cbf558252b24a8257823",
- "transactions": [
- {'sender': '0', 'recipient': 'Quincy Larson', 'quantity': 1}
- ],
- "timestamp": 1521646442.4096143
- }
複製代碼
2. 構建區塊鏈類
顧名思義,區塊鏈的主要思想涉及將幾個塊“鏈接”到彼此。
因此,我將構建一個區塊鏈類,該類將有助於管理整個鏈的工作。這是大部分操作將發生的地方。
該Blockchain類將在blockchain完成各種任務的各種輔助方法。
讓我解釋一下類中每個方法的作用。
一個。構造方法
此方法可確保區塊鏈被實例化。
- class BlockChain:
- def __init__(self):
- self.chain = []
- self.current_data = []
- self.nodes = set()
- self.construct_genesis()
複製代碼
以下是其屬性的作用:
self.chain——這個變量保存所有的塊;
self.current_data — 該變量保存區塊中所有已完成的交易;
self.construct_genesis() ——這個方法將負責構建初始塊。
灣 構建創世區塊
區塊鏈需要一個construct_genesis方法來構建鏈中的初始塊。在區塊鏈公約中,這個區塊很特別,因為它像徵著區塊鏈的開始。
在這種情況下,讓我們通過簡單地將一些默認值傳遞給construct_block方法來構建它。
我給proof_no和prev_hash的值都為零,儘管你可以提供任何你想要的值。
- def construct_genesis(self):
- self.construct_block(proof_no=0, prev_hash=0)
- def construct_block(self, proof_no, prev_hash):
- block = Block(
- index=len(self.chain),
- proof_no=proof_no,
- prev_hash=prev_hash,
- data=self.current_data)
- self.current_data = []
- self.chain.append(block)
- return block
複製代碼
C。構建新塊
該construct_block 方法用於在blockchain創造新的塊。
以下是此方法的各種屬性發生的情況:
index-這表示blockchain的長度;
proof_nor & prev_hash——調用者方法傳遞它們;
data——這包含所有未包含在節點上任何塊中的交易的記錄;
self.current_data — 用於重置節點上的事務列表。如果已經構建了一個塊並將交易分配給它,則重置列表以確保將來的交易添加到此列表中。並且,這個過程會持續進行;
self.chain.append()——這個方法將新構建的塊連接到鏈上;
return -最後,返回一個構造的塊對象。
d. 檢查有效性
該check_validity方法是評估blockchain的完整性,確保異常是缺席重要。
如前所述,散列對於區塊鏈的安全性至關重要,因為即使對像中最輕微的變化也會導致生成全新的散列。
因此,這個check_validity 方法使用if語句來檢查每個塊的哈希是否正確。
它還通過比較它們的哈希值來驗證每個塊是否指向正確的前一個塊。如果一切正確,則返回 true;否則,它返回 false。
- @staticmethod
- def check_validity(block, prev_block):
- if prev_block.index + 1 != block.index:
- return False
- elif prev_block.calculate_hash != block.prev_hash:
- return False
- elif not BlockChain.verifying_proof(block.proof_no, prev_block.proof_no):
- return False
- elif block.timestamp <= prev_block.timestamp:
- return False
- return True
複製代碼
e. 添加交易數據
該NEW_DATA方法用於添加事務的數據的塊。這是一個非常簡單的方法:它接受三個參數(發送者的詳細信息、接收者的詳細信息和數量)並將交易數據附加到self.current_data列表中。
每當創建一個新塊時,該列表都會分配給該塊並再次重置,如construct_block方法中所述。
一旦將交易數據添加到列表中,將返回下一個要創建的塊的索引。
該索引是通過將當前塊(區塊鏈中的最後一個)的索引加 1 來計算的。該數據將幫助用戶在未來提交交易。
- def new_data(self, sender, recipient, quantity):
- self.current_data.append({
- 'sender': sender,
- 'recipient': recipient,
- 'quantity': quantity
- })
- return True
複製代碼
F。添加工作證明
工作量證明是一個防止區塊鏈被濫用的概念。簡而言之,它的目標是確定在完成一定量的計算工作後解決問題的數字。
如果識別號碼的難度級別很高,它會阻止垃圾郵件和篡改區塊鏈。
在這種情況下,我們將使用一個簡單的算法來阻止人們挖掘區塊或輕鬆創建區塊。
- @staticmethod
- def proof_of_work(last_proof):
- '''this simple algorithm identifies a number f' such that hash(ff') contain 4 leading zeroes
- f is the previous f'
- f' is the new proof
- '''
- proof_no = 0
- while BlockChain.verifying_proof(proof_no, last_proof) is False:
- proof_no += 1
- return proof_no
- @staticmethod
- def verifying_proof(last_proof, proof):
- #verifying the proof: does hash(last_proof, proof) contain 4 leading zeroes?
- guess = f'{last_proof}{proof}'.encode()
- guess_hash = hashlib.sha256(guess).hexdigest()
- return guess_hash[:4] == "0000"
複製代碼
G。獲取最後一個區塊
最後,latest_block 方法是幫助獲取區塊鏈中最後一個區塊的輔助方法。請記住,最後一個塊實際上是鏈中的當前塊。
- @property
- def latest_block(self):
- return self.chain[-1]
複製代碼
讓我們總結一下
這是創建fccCoin加密貨幣的完整代碼。
您還可以在此 GitHub 存儲庫中獲取代碼。
- import hashlib
- import time
- class Block:
- def __init__(self, index, proof_no, prev_hash, data, timestamp=None):
- self.index = index
- self.proof_no = proof_no
- self.prev_hash = prev_hash
- self.data = data
- self.timestamp = timestamp or time.time()
- @property
- def calculate_hash(self):
- block_of_string = "{}{}{}{}{}".format(self.index, self.proof_no,
- self.prev_hash, self.data,
- self.timestamp)
- return hashlib.sha256(block_of_string.encode()).hexdigest()
- def __repr__(self):
- return "{} - {} - {} - {} - {}".format(self.index, self.proof_no,
- self.prev_hash, self.data,
- self.timestamp)
- class BlockChain:
- def __init__(self):
- self.chain = []
- self.current_data = []
- self.nodes = set()
- self.construct_genesis()
- def construct_genesis(self):
- self.construct_block(proof_no=0, prev_hash=0)
- def construct_block(self, proof_no, prev_hash):
- block = Block(
- index=len(self.chain),
- proof_no=proof_no,
- prev_hash=prev_hash,
- data=self.current_data)
- self.current_data = []
- self.chain.append(block)
- return block
- @staticmethod
- def check_validity(block, prev_block):
- if prev_block.index + 1 != block.index:
- return False
- elif prev_block.calculate_hash != block.prev_hash:
- return False
- elif not BlockChain.verifying_proof(block.proof_no,
- prev_block.proof_no):
- return False
- elif block.timestamp <= prev_block.timestamp:
- return False
- return True
- def new_data(self, sender, recipient, quantity):
- self.current_data.append({
- 'sender': sender,
- 'recipient': recipient,
- 'quantity': quantity
- })
- return True
- @staticmethod
- def proof_of_work(last_proof):
- '''this simple algorithm identifies a number f' such that hash(ff') contain 4 leading zeroes
- f is the previous f'
- f' is the new proof
- '''
- proof_no = 0
- while BlockChain.verifying_proof(proof_no, last_proof) is False:
- proof_no += 1
- return proof_no
- @staticmethod
- def verifying_proof(last_proof, proof):
- #verifying the proof: does hash(last_proof, proof) contain 4 leading zeroes?
- guess = f'{last_proof}{proof}'.encode()
- guess_hash = hashlib.sha256(guess).hexdigest()
- return guess_hash[:4] == "0000"
- @property
- def latest_block(self):
- return self.chain[-1]
- def block_mining(self, details_miner):
- self.new_data(
- sender="0", #it implies that this node has created a new block
- receiver=details_miner,
- quantity=1, #creating a new block (or identifying the proof number) is awarded with 1
- )
- last_block = self.latest_block
- last_proof_no = last_block.proof_no
- proof_no = self.proof_of_work(last_proof_no)
- last_hash = last_block.calculate_hash
- block = self.construct_block(proof_no, last_hash)
- return vars(block)
- def create_node(self, address):
- self.nodes.add(address)
- return True
- @staticmethod
- def obtain_block_object(block_data):
- #obtains block object from the block data
- return Block(
- block_data['index'],
- block_data['proof_no'],
- block_data['prev_hash'],
- block_data['data'],
- timestamp=block_data['timestamp'])
複製代碼
現在,讓我們測試我們的代碼,看看它是否有效。
- blockchain = BlockChain()
- print("***Mining fccCoin about to start***")
- print(blockchain.chain)
- last_block = blockchain.latest_block
- last_proof_no = last_block.proof_no
- proof_no = blockchain.proof_of_work(last_proof_no)
- blockchain.new_data(
- sender="0", #it implies that this node has created a new block
- recipient="Quincy Larson", #let's send Quincy some coins!
- quantity=1, #creating a new block (or identifying the proof number) is awarded with 1
- )
- last_hash = last_block.calculate_hash
- block = blockchain.construct_block(proof_no, last_hash)
- print("***Mining fccCoin has been successful***")
- print(blockchain.chain)
複製代碼
有效!
這是挖礦過程的輸出:
- ***Mining fccCoin about to start***
- [0 - 0 - 0 - [] - 1566930640.2707076]
- ***Mining fccCoin has been successful***
- [0 - 0 - 0 - [] - 1566930640.2707076, 1 - 88914 - a8d45cb77cddeac750a9439d629f394da442672e56edfe05827b5e41f4ba0138 - [{'sender': '0', 'recipient': 'Quincy Larson', 'quantity': 1}] - 1566930640.5363243]
複製代碼
結論
你有它!
這就是您可以使用 Python 創建自己的區塊鏈的方式。
讓我說,本教程只是演示了讓您涉足創新區塊鏈技術的基本概念。
如果按原樣部署該硬幣,則無法滿足當前市場對穩定、安全和易於使用的加密貨幣的需求。
因此,它仍然可以通過添加附加功能來改進其挖掘和發送金融交易的能力。
儘管如此,如果您決定讓您的名字在令人驚嘆的加密貨幣世界中廣為人知,這是一個很好的起點。
文章出處
|
|