如何使用Python创建自己的加密货币

知新闻 2023-07-05 17:29:38
26阅读

 

随着当前加密货币的兴起,区块链在技术界引起了轰动。

这项技术之所以吸引了如此多的关注,主要是因为它具有保证安全,强制分权和加快多个行业(尤其是金融行业)流程的能力。

本质上,区块链是一个公共数据库,它不可逆地记录和认证数字资产的拥有和传输。像比特币和以太坊这样的数字货币就是基于这个概念。

区块链是一项令人兴奋的技术,可用于转换应用程序的功能。

最近,我们看到政府,组织和个人使用区块链技术来创建自己的加密货币。值得注意的是,当Facebook提出自己的加密货币Libra时,这一公告激起了全世界的许多热潮。

如果您也可以效仿并创建自己的加密货币版本,你应该如何着手?

我考虑了这一点,决定开发一种可以创建加密货币的算法。

我决定将加密货币称为fccCoin。

在本教程中,我将逐步说明构建数字货币的过程(我使用了Python编程语言的面向对象概念)。

这是用于创建fccCoin的区块链算法的基本蓝图:

 
  1. class Block: 
  2.  
  3.     def __init__(): 
  4.  
  5.     #first block class 
  6.  
  7.         pass 
  8.      
  9.     def calculate_hash(): 
  10.      
  11.     #calculates the cryptographic hash of every block 
  12.          
  13.      
  14. class BlockChain: 
  15.      
  16.     def __init__(self): 
  17.      # constructor method 
  18.     pass 
  19.      
  20.     def construct_genesis(self): 
  21.         # constructs the initial block 
  22.         pass 
  23.  
  24.     def construct_block(self, proof_no, prev_hash): 
  25.         # constructs a new block and adds it to the chain 
  26.         pass 
  27.  
  28.     @staticmethod 
  29.     def check_validity(): 
  30.         # checks whether the blockchain is valid 
  31.         pass 
  32.  
  33.     def new_data(self, sender, recipient, quantity): 
  34.         # adds a new transaction to the data of the transactions 
  35.         pass 
  36.  
  37.     @staticmethod 
  38.     def construct_proof_of_work(prev_proof): 
  39.         # protects the blockchain from attack 
  40.         pass 
  41.     
  42.     @property 
  43.     def last_block(self): 
  44.         # returns the last block in the chain 
  45.         return self.chain[-1] 

现在,让我解释一下接下来应该怎么做……

1.建立第一个Block类

区块链由几个相互连接的块组成,因此,如果一个块被篡改,则链将变为无效。

在应用上述概念时,我创建了以下初始块类:

 
  1. import hashlib 
  2. import time 
  3.  
  4. class Block: 
  5.  
  6.     def __init__(self, index, proof_no, prev_hash, data, timestamp=None): 
  7.         self.index = index 
  8.         self.proof_no = proof_no 
  9.         self.prev_hash = prev_hash 
  10.         self.data = data 
  11.         self.timestamp = timestamp or time.time() 
  12.  
  13.     @property 
  14.     def calculate_hash(self): 
  15.         block_of_string = "{}{}{}{}{}".format(self.index, self.proof_no, 
  16.                                               self.prev_hash, self.data, 
  17.                                               self.timestamp
  18.  
  19.         return hashlib.sha256(block_of_string.encode()).hexdigest() 
  20.  
  21.     def __repr__(self): 
  22.         return "{} - {} - {} - {} - {}".format(self.index, self.proof_no, 
  23.                                                self.prev_hash, self.data, 
  24.                                                self.timestamp

从上面的代码中可以看到,我定义了__init __()函数,该函数将在启动Block类时执行,就像在其他任何Python类中一样。

我为启动函数提供了以下参数:

  • self-引用Block类的实例,从而可以访问与该类关联的方法和属性;
  • 索引—跟踪区块链在区块链中的位置;
  • proof_no-这是在创建新块(称为挖矿)期间产生的数量;
  • prev_hash —这是指链中上一个块的哈希值;
  • 数据-提供所有已完成交易的记录,例如购买数量;
  • 时间戳记-为事务放置时间戳记。

类中的第二个方法calculate_hash将使用上述值生成块的哈希。SHA-256模块被导入到项目中,以帮助获得块的哈希值。

将值输入到密码哈希算法后,该函数将返回一个256位字符串,表示该块的内容。

这就是在区块链中实现安全性的方式-每个块都将具有哈希,并且该哈希将依赖于前一个块的哈希。

因此,如果有人试图破坏链中的任何区块,其他区块将具有无效的哈希值,从而导致整个区块链网络的破坏。

最终,一个块将如下所示:

 
  1.     "index": 2, 
  2.     "proof": 21, 
  3.     "prev_hash""6e27587e8a27d6fe376d4fd9b4edc96c8890346579e5cbf558252b24a8257823"
  4.     "transactions": [ 
  5.         {'sender''0''recipient''Quincy Larson''quantity': 1} 
  6.     ], 
  7.     "timestamp": 1521646442.4096143 

2.建立区块链类

顾名思义,区块链的主要思想涉及将多个区块相互“链接”。

因此,我将构建一个对管理整个链的工作很有用的Blockchain类。这是大多数动作将要发生的地方。

该Blockchain类将在blockchain完成各种任务的各种辅助方法。

让我解释一下每个方法在类中的作用。

A.构造方法

此方法确保实例化区块链。

 
  1. class BlockChain: 
  2.  
  3.     def __init__(self): 
  4.         self.chain = [] 
  5.         self.current_data = [] 
  6.         self.nodes = set() 
  7.         self.construct_genesis() 

以下是其属性的作用:

  • self.chain-此变量保留所有块;
  • self.current_data-此变量将所有已完成的事务保留在该块中;
  • self.construct_genesis() -此方法将负责构造初始块。

B.构建创世块

区块链需要一个construct_genesis方法来构建链中的初始块。在区块链惯例中,此块是特殊的,因为它象征着区块链的开始。

在这种情况下,让我们通过简单地将一些默认值传递给Construct_block方法来构造它。

尽管您可以提供所需的任何值,但我都给了proof_no和prev_hash一个零值。

 
  1. def construct_genesis(self): 
  2.     self.construct_block(proof_no=0, prev_hash=0) 
  3.  
  4.  
  5. def construct_block(self, proof_no, prev_hash): 
  6.     block = Block( 
  7.         index=len(self.chain), 
  8.         proof_no=proof_no, 
  9.         prev_hash=prev_hash, 
  10.         data=self.current_data) 
  11.     self.current_data = [] 
  12.  
  13.     self.chain.append(block) 
  14.     return block 

C.建造新的街区

该construct_block 方法用于在blockchain创造新的块。

这是此方法的各种属性所发生的情况:

  • 索引-代表区块链的长度;
  • proof_nor&prev_hash —调用者方法传递它们;
  • 数据-包含节点上任何块中未包含的所有事务的记录;
  • self.current_data-用于重置节点上的事务列表。如果已经构造了一个块并将事务分配给该块,则会重置该列表以确保将来的事务被添加到该列表中。并且,该过程将连续进行;
  • self.chain.append()-此方法将新构建的块连接到链;
  • return-最后,返回一个构造的块对象。

D.检查有效性

该check_validity方法是评估blockchain的完整性,确保异常是绝对重要。

如上所述,散列对于区块链的安全至关重要,因为即使对象发生任何细微变化也将导致生成全新的哈希。

因此,此check_validity 方法使用if语句检查每个块的哈希是否正确。

它还通过比较其哈希值来验证每个块是否指向正确的上一个块。如果一切正确,则返回true;否则,返回true。否则,它返回false。

 
  1. @staticmethod 
  2. def check_validity(block, prev_block): 
  3.     if prev_block.index + 1 != block.index
  4.         return False 
  5.  
  6.     elif prev_block.calculate_hash != block.prev_hash: 
  7.         return False 
  8.  
  9.     elif not BlockChain.verifying_proof(block.proof_no, prev_block.proof_no): 
  10.         return False 
  11.  
  12.     elif block.timestamp <= prev_block.timestamp
  13.         return False 
  14.  
  15.     return True 

E.添加交易数据

该NEW_DATA方法用于添加事务的数据的块。这是一种非常简单的方法:它接受三个参数(发送者的详细信息,接收者的详细信息和数量),并将交易数据附加到self.current_data列表中。

每当创建新块时,都会将该列表分配给该块,并再次按Construct_block方法中的说明进行重置。

将交易数据添加到列表后,将返回要创建的下一个块的索引。

该索引是通过将当前块的索引(即区块链中的最后一个)的索引加1来计算的。数据将帮助用户将来提交交易。

 
  1. def new_data(self, sender, recipient, quantity): 
  2.     self.current_data.append({ 
  3.         'sender': sender, 
  4.         'recipient': recipient, 
  5.         'quantity': quantity 
  6.     }) 
  7.     return True 

F.添加工作证明

工作量证明是防止区块链滥用的概念。简而言之,其目的是在完成一定数量的计算工作后,确定一个可以解决问题的编号。

如果识别数字的难度很高,则不鼓励发送垃圾邮件和篡改区块链。

在这种情况下,我们将使用一种简单的算法来阻止人们挖掘区块或轻松创建区块。

 
  1. @staticmethod 
  2. def proof_of_work(last_proof): 
  3.     '''this simple algorithm identifies a number f' such that hash(ff') contain 4 leading zeroes 
  4.          f is the previous f' 
  5.          f' is the new proof 
  6.         ''' 
  7.     proof_no = 0 
  8.     while BlockChain.verifying_proof(proof_no, last_proof) is False
  9.         proof_no += 1 
  10.  
  11.     return proof_no 
  12.  
  13.  
  14. @staticmethod 
  15. def verifying_proof(last_proof, proof): 
  16.     #verifying the proof: does hash(last_proof, proof) contain 4 leading zeroes? 
  17.  
  18.     guess = f'{last_proof}{proof}'.encode() 
  19.     guess_hash = hashlib.sha256(guess).hexdigest() 
  20.     return guess_hash[:4] == "0000" 

G.得到最后一块

最后,latest_block 方法是一种帮助程序方法,可帮助获取区块链中的最后一个块。请记住,最后一个块实际上是链中的当前块。

 
  1. @property 
  2.     def latest_block(self): 
  3.         return self.chain[-1] 

总结

这是用于创建fccCoin加密货币的完整代码。

 
  1. import hashlib 
  2. import time 
  3.  
  4.  
  5. class Block: 
  6.  
  7.     def __init__(self, index, proof_no, prev_hash, data, timestamp=None): 
  8.         self.index = index 
  9.         self.proof_no = proof_no 
  10.         self.prev_hash = prev_hash 
  11.         self.data = data 
  12.         self.timestamp = timestamp or time.time() 
  13.  
  14.     @property 
  15.     def calculate_hash(self): 
  16.         block_of_string = "{}{}{}{}{}".format(self.index, self.proof_no, 
  17.                                               self.prev_hash, self.data, 
  18.                                               self.timestamp
  19.  
  20.         return hashlib.sha256(block_of_string.encode()).hexdigest() 
  21.  
  22.     def __repr__(self): 
  23.         return "{} - {} - {} - {} - {}".format(self.index, self.proof_no, 
  24.                                                self.prev_hash, self.data, 
  25.                                                self.timestamp
  26.  
  27.  
  28. class BlockChain: 
  29.  
  30.     def __init__(self): 
  31.         self.chain = [] 
  32.         self.current_data = [] 
  33.         self.nodes = set() 
  34.         self.construct_genesis() 
  35.  
  36.     def construct_genesis(self): 
  37.         self.construct_block(proof_no=0, prev_hash=0) 
  38.  
  39.     def construct_block(self, proof_no, prev_hash): 
  40.         block = Block( 
  41.             index=len(self.chain), 
  42.             proof_no=proof_no, 
  43.             prev_hash=prev_hash, 
  44.             data=self.current_data) 
  45.         self.current_data = [] 
  46.  
  47.         self.chain.append(block) 
  48.         return block 
  49.  
  50.     @staticmethod 
  51.     def check_validity(block, prev_block): 
  52.         if prev_block.index + 1 != block.index
  53.             return False 
  54.  
  55.         elif prev_block.calculate_hash != block.prev_hash: 
  56.             return False 
  57.  
  58.         elif not BlockChain.verifying_proof(block.proof_no, 
  59.                                             prev_block.proof_no): 
  60.             return False 
  61.  
  62.         elif block.timestamp <= prev_block.timestamp
  63.             return False 
  64.  
  65.         return True 
  66.  
  67.     def new_data(self, sender, recipient, quantity): 
  68.         self.current_data.append({ 
  69.             'sender': sender, 
  70.             'recipient': recipient, 
  71.             'quantity': quantity 
  72.         }) 
  73.         return True 
  74.  
  75.     @staticmethod 
  76.     def proof_of_work(last_proof): 
  77.         '''this simple algorithm identifies a number f' such that hash(ff') contain 4 leading zeroes 
  78.          f is the previous f' 
  79.          f' is the new proof 
  80.         ''
  81.         proof_no = 0 
  82.         while BlockChain.verifying_proof(proof_no, last_proof) is False
  83.             proof_no += 1 
  84.  
  85.         return proof_no 
  86.  
  87.     @staticmethod 
  88.     def verifying_proof(last_proof, proof): 
  89.         #verifying the proof: does hash(last_proof, proof) contain 4 leading zeroes? 
  90.  
  91.         guess = f'{last_proof}{proof}'.encode() 
  92.         guess_hash = hashlib.sha256(guess).hexdigest() 
  93.         return guess_hash[:4] == "0000" 
  94.  
  95.     @property 
  96.     def latest_block(self): 
  97.         return self.chain[-1] 
  98.  
  99.     def block_mining(self, details_miner): 
  100.  
  101.         self.new_data( 
  102.             sender="0",  #it implies that this node has created a new block 
  103.             receiver=details_miner, 
  104.             quantity= 
  105.             1,  #creating a new block (or identifying the proof number) is awarded with 1 
  106.         ) 
  107.  
  108.         last_block = self.latest_block 
  109.  
  110.         last_proof_no = last_block.proof_no 
  111.         proof_no = self.proof_of_work(last_proof_no) 
  112.  
  113.         last_hash = last_block.calculate_hash 
  114.         block = self.construct_block(proof_no, last_hash) 
  115.  
  116.         return vars(block) 
  117.  
  118.     def create_node(self, address): 
  119.         self.nodes.add(address) 
  120.         return True 
  121.  
  122.     @staticmethod 
  123.     def obtain_block_object(block_data): 
  124.         #obtains block object from the block data 
  125.  
  126.         return Block( 
  127.             block_data['index'], 
  128.             block_data['proof_no'], 
  129.             block_data['prev_hash'], 
  130.             block_data['data'], 
  131.             timestamp=block_data['timestamp']) 

现在,让我们测试我们的代码,看看它是否有效。

 
  1. blockchain = BlockChain() 
  2.  
  3. print("***Mining fccCoin about to start***"
  4. print(blockchain.chain) 
  5.  
  6. last_block = blockchain.latest_block 
  7. last_proof_no = last_block.proof_no 
  8. proof_no = blockchain.proof_of_work(last_proof_no) 
  9.  
  10. blockchain.new_data( 
  11.     sender="0",  #it implies that this node has created a new block 
  12.     recipient="Quincy Larson",  #let's send Quincy some coins! 
  13.     quantity= 
  14.     1,  #creating a new block (or identifying the proof number) is awarded with 1 
  15.  
  16. last_hash = last_block.calculate_hash 
  17. block = blockchain.construct_block(proof_no, last_hash) 
  18.  
  19. print("***Mining fccCoin has been successful***"
  20. print(blockchain.chain) 

有效!

这是挖掘过程的输出:

 
  1. ***Mining fccCoin about to start*** 
  2. [0 - 0 - 0 - [] - 1566930640.2707076] 
  3. ***Mining fccCoin has been successful*** 
  4. [0 - 0 - 0 - [] - 1566930640.2707076, 1 - 88914 - a8d45cb77cddeac750a9439d629f394da442672e56edfe05827b5e41f4ba0138 - [{'sender''0''recipient''Quincy Larson''quantity': 1}] - 1566930640.5363243] 

结论

以上就是使用Python创建自己的区块链的方式。

如果按原样部署该代币,它将无法满足当前市场对稳定,安全且易于使用的加密货币的需求。

因此,仍可以通过添加其他功能来增强其挖掘和发送财务交易的功能,从而对其进行改进。

the end
免责声明:本文不代表本站的观点和立场,如有侵权请联系本站删除!本站仅提供信息存储空间服务。