Python創(chuàng)建自己的加密貨幣的示例
隨著當前加密貨幣的興起,區(qū)塊鏈在技術(shù)界引起了轟動。
這項技術(shù)之所以吸引了如此多的關(guān)注,主要是因為它具有保證安全,強制分權(quán)和加快多個行業(yè)(尤其是金融行業(yè))流程的能力。
本質(zhì)上,區(qū)塊鏈是一個公共數(shù)據(jù)庫,它不可逆地記錄和認證數(shù)字資產(chǎn)的擁有和傳輸。像比特幣和以太坊這樣的數(shù)字貨幣就是基于這個概念。
區(qū)塊鏈是一項令人興奮的技術(shù),可用于轉(zhuǎn)換應(yīng)用程序的功能。
最近,我們看到政府,組織和個人使用區(qū)塊鏈技術(shù)來創(chuàng)建自己的加密貨幣。值得注意的是,當Facebook提出自己的加密貨幣Libra時,這一公告激起了全世界的許多熱潮。
如果您也可以效仿并創(chuàng)建自己的加密貨幣版本,你應(yīng)該如何著手?
我考慮了這一點,決定開發(fā)一種可以創(chuàng)建加密貨幣的算法。
我決定將加密貨幣稱為fccCoin。
在本教程中,我將逐步說明構(gòu)建數(shù)字貨幣的過程(我使用了Python編程語言的面向?qū)ο蟾拍睿?nbsp;
這是用于創(chuàng)建fccCoin的區(qū)塊鏈算法的基本藍圖:
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]
現(xiàn)在,讓我解釋一下接下來應(yīng)該怎么做……
1.建立第一個Block類
區(qū)塊鏈由幾個相互連接的塊組成,因此,如果一個塊被篡改,則鏈將變?yōu)闊o效。
在應(yīng)用上述概念時,我創(chuàng)建了以下初始塊類:
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 __()函數(shù),該函數(shù)將在啟動Block類時執(zhí)行,就像在其他任何Python類中一樣。
我為啟動函數(shù)提供了以下參數(shù):
- self-引用Block類的實例,從而可以訪問與該類關(guān)聯(lián)的方法和屬性;
- 索引—跟蹤區(qū)塊鏈在區(qū)塊鏈中的位置;
- proof_no-這是在創(chuàng)建新塊(稱為挖礦)期間產(chǎn)生的數(shù)量;
- prev_hash —這是指鏈中上一個塊的哈希值;
- 數(shù)據(jù)-提供所有已完成交易的記錄,例如購買數(shù)量;
- 時間戳記-為事務(wù)放置時間戳記。
類中的第二個方法calculate_hash將使用上述值生成塊的哈希。SHA-256模塊被導(dǎo)入到項目中,以幫助獲得塊的哈希值。
將值輸入到密碼哈希算法后,該函數(shù)將返回一個256位字符串,表示該塊的內(nèi)容。
這就是在區(qū)塊鏈中實現(xiàn)安全性的方式-每個塊都將具有哈希,并且該哈希將依賴于前一個塊的哈希。
因此,如果有人試圖破壞鏈中的任何區(qū)塊,其他區(qū)塊將具有無效的哈希值,從而導(dǎo)致整個區(qū)塊鏈網(wǎng)絡(luò)的破壞。
最終,一個塊將如下所示:
{ "index": 2, "proof": 21, "prev_hash": "6e27587e8a27d6fe376d4fd9b4edc96c8890346579e5cbf558252b24a8257823", "transactions": [ {'sender': '0', 'recipient': 'Quincy Larson', 'quantity': 1} ], "timestamp": 1521646442.4096143 }
2.建立區(qū)塊鏈類
顧名思義,區(qū)塊鏈的主要思想涉及將多個區(qū)塊相互“鏈接”。
因此,我將構(gòu)建一個對管理整個鏈的工作很有用的Blockchain類。這是大多數(shù)動作將要發(fā)生的地方。
該Blockchain類將在blockchain完成各種任務(wù)的各種輔助方法。
讓我解釋一下每個方法在類中的作用。
A.構(gòu)造方法
此方法確保實例化區(qū)塊鏈。
class BlockChain: def __init__(self): self.chain = [] self.current_data = [] self.nodes = set() self.construct_genesis()
以下是其屬性的作用:
- self.chain-此變量保留所有塊;
- self.current_data-此變量將所有已完成的事務(wù)保留在該塊中;
- self.construct_genesis() -此方法將負責(zé)構(gòu)造初始塊。
B.構(gòu)建創(chuàng)世塊
區(qū)塊鏈需要一個construct_genesis方法來構(gòu)建鏈中的初始塊。在區(qū)塊鏈慣例中,此塊是特殊的,因為它象征著區(qū)塊鏈的開始。
在這種情況下,讓我們通過簡單地將一些默認值傳遞給Construct_block方法來構(gòu)造它。
盡管您可以提供所需的任何值,但我都給了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.建造新的街區(qū)
該construct_block 方法用于在blockchain創(chuàng)造新的塊。
這是此方法的各種屬性所發(fā)生的情況:
- 索引-代表區(qū)塊鏈的長度;
- proof_nor&prev_hash —調(diào)用者方法傳遞它們;
- 數(shù)據(jù)-包含節(jié)點上任何塊中未包含的所有事務(wù)的記錄;
- self.current_data-用于重置節(jié)點上的事務(wù)列表。如果已經(jīng)構(gòu)造了一個塊并將事務(wù)分配給該塊,則會重置該列表以確保將來的事務(wù)被添加到該列表中。并且,該過程將連續(xù)進行;
- self.chain.append()-此方法將新構(gòu)建的塊連接到鏈;
- return-最后,返回一個構(gòu)造的塊對象。
D.檢查有效性
該check_validity方法是評估blockchain的完整性,確保異常是絕對重要。
如上所述,散列對于區(qū)塊鏈的安全至關(guān)重要,因為即使對象發(fā)生任何細微變化也將導(dǎo)致生成全新的哈希。
因此,此check_validity 方法使用if語句檢查每個塊的哈希是否正確。
它還通過比較其哈希值來驗證每個塊是否指向正確的上一個塊。如果一切正確,則返回true;否則,返回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.添加交易數(shù)據(jù)
該NEW_DATA方法用于添加事務(wù)的數(shù)據(jù)的塊。這是一種非常簡單的方法:它接受三個參數(shù)(發(fā)送者的詳細信息,接收者的詳細信息和數(shù)量),并將交易數(shù)據(jù)附加到self.current_data列表中。
每當創(chuàng)建新塊時,都會將該列表分配給該塊,并再次按Construct_block方法中的說明進行重置。
將交易數(shù)據(jù)添加到列表后,將返回要創(chuàng)建的下一個塊的索引。
該索引是通過將當前塊的索引(即區(qū)塊鏈中的最后一個)的索引加1來計算的。數(shù)據(jù)將幫助用戶將來提交交易。
def new_data(self, sender, recipient, quantity): self.current_data.append({ 'sender': sender, 'recipient': recipient, 'quantity': quantity }) return True
F.添加工作證明
工作量證明是防止區(qū)塊鏈濫用的概念。簡而言之,其目的是在完成一定數(shù)量的計算工作后,確定一個可以解決問題的編號。
如果識別數(shù)字的難度很高,則不鼓勵發(fā)送垃圾郵件和篡改區(qū)塊鏈。
在這種情況下,我們將使用一種簡單的算法來阻止人們挖掘區(qū)塊或輕松創(chuàng)建區(qū)塊。
@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 方法是一種幫助程序方法,可幫助獲取區(qū)塊鏈中的最后一個塊。請記住,最后一個塊實際上是鏈中的當前塊。
@property def latest_block(self): return self.chain[-1]
總結(jié)
這是用于創(chuàng)建fccCoin加密貨幣的完整代碼。
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'])
現(xiàn)在,讓我們測試我們的代碼,看看它是否有效。
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]
結(jié)論
以上就是使用Python創(chuàng)建自己的區(qū)塊鏈的方式。
如果按原樣部署該代幣,它將無法滿足當前市場對穩(wěn)定,安全且易于使用的加密貨幣的需求。
因此,仍可以通過添加其他功能來增強其挖掘和發(fā)送財務(wù)交易的功能,從而對其進行改進。
以上就是Python創(chuàng)建自己的加密貨幣的示例的詳細內(nèi)容,更多關(guān)于Python創(chuàng)建自己的加密貨幣的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
tensor.squeeze函數(shù)和tensor.unsqueeze函數(shù)的使用詳解
本文主要介紹了tensor.squeeze函數(shù)和tensor.unsqueeze函數(shù)的使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03使用pycharm和pylint檢查python代碼規(guī)范操作
這篇文章主要介紹了使用pycharm和pylint檢查python代碼規(guī)范操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06