Python创建自己的加密货币的示例


Posted in Python onMarch 01, 2021

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

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

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

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

最近,我们看到政府,组织和个人使用区块链技术来创建自己的加密货币。值得注意的是,当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类的实例,从而可以访问与该类关联的方法和属性;
  • 索引—跟踪区块链在区块链中的位置;
  • proof_no-这是在创建新块(称为挖矿)期间产生的数量;
  • prev_hash —这是指链中上一个块的哈希值;
  • 数据-提供所有已完成交易的记录,例如购买数量;
  • 时间戳记-为事务放置时间戳记。

类中的第二个方法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类将在blockchain完成各种任务的各种辅助方法。

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

A.构造方法

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

class BlockChain:

 def __init__(self):
  self.chain = []
  self.current_data = []
  self.nodes = set()
        self.construct_genesis()

以下是其属性的作用:

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

B.构建创世块

区块链需要一个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创造新的块。

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

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

D.检查有效性

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

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

因此,此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.添加交易数据

该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加密货币的完整代码。

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创建自己的区块链的方式。

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

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

以上就是Python创建自己的加密货币的示例的详细内容,更多关于Python创建自己的加密货币的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
python求素数示例分享
Feb 16 Python
详解Python中DOM方法的动态性
Apr 11 Python
python Crypto模块的安装与使用方法
Dec 21 Python
Python中矩阵创建和矩阵运算方法
Aug 04 Python
python3实现字符串操作的实例代码
Apr 16 Python
快速解决docker-py api版本不兼容的问题
Aug 30 Python
解决python -m pip install --upgrade pip 升级不成功问题
Mar 05 Python
浅谈django 模型类使用save()方法的好处与注意事项
Mar 28 Python
Python restful框架接口开发实现
Apr 13 Python
Jupyter打开图形界面并画出正弦函数图像实例
Apr 24 Python
Python中内建模块collections如何使用
May 27 Python
Python如何执行系统命令
Sep 23 Python
python 实现网易邮箱邮件阅读和删除的辅助小脚本
Mar 01 #Python
详解Django中的FBV和CBV对比分析
Mar 01 #Python
Python3压缩和解压缩实现代码
Mar 01 #Python
python re模块常见用法例举
Mar 01 #Python
Python实现简单的2048小游戏
Mar 01 #Python
Python使用Turtle模块绘制国旗的方法示例
Feb 28 #Python
Python页面加载的等待方式总结
Feb 28 #Python
You might like
php页码形式分页函数支持静态化地址及ajax分页
2014/03/28 PHP
Yii查询生成器(Query Builder)用法实例教程
2014/09/04 PHP
php缩放gif和png图透明背景变成黑色的解决方法
2014/10/14 PHP
php实现xml与json之间的相互转换功能实例
2016/07/07 PHP
PHP简单实现二维数组的矩阵转置操作示例
2017/11/24 PHP
javascript之bind使用介绍
2011/10/09 Javascript
js实现浏览器的各种菜单命令比如打印、查看源文件等等
2013/10/24 Javascript
一个不错的js html页面倒计时可精确到秒
2014/10/22 Javascript
javascript中setTimeout和setInterval的unref()和ref()用法示例
2014/11/26 Javascript
javascript实现表格增删改操作实例详解
2015/05/15 Javascript
JS实现带关闭功能的阿里妈妈网站顶部滑出banner工具条代码
2015/09/17 Javascript
用JS生成UUID的方法实例
2016/03/30 Javascript
Angular开发者指南之入门介绍
2017/03/05 Javascript
详解angular2实现ng2-router 路由和嵌套路由
2017/03/24 Javascript
Angular2使用Guard和Resolve进行验证和权限控制
2017/04/24 Javascript
[02:38]DOTA2亚洲邀请赛 IG战队巡礼
2015/02/03 DOTA
Python中使用glob和rmtree删除目录子目录及所有文件的例子
2014/11/21 Python
python检测远程udp端口是否打开的方法
2015/03/14 Python
详解Python中的strftime()方法的使用
2015/05/22 Python
Django卸载之后重新安装的方法
2017/03/15 Python
深入理解Python3中的http.client模块
2017/03/29 Python
浅谈Python2.6和Python3.0中八进制数字表示的区别
2017/04/28 Python
Python爬虫包BeautifulSoup异常处理(二)
2018/06/17 Python
Python中Subprocess的不同函数解析
2019/12/10 Python
Pytorch Tensor基本数学运算详解
2019/12/30 Python
python+tifffile之tiff文件读写方式
2020/01/13 Python
python计算二维矩形IOU实例
2020/01/18 Python
John Varvatos官方网站:设计师男士时装
2017/02/08 全球购物
Links of London官方网站:英国标志性的珠宝品牌
2017/04/09 全球购物
三好学生自我鉴定
2013/12/17 职场文书
特色蛋糕店创业计划书
2014/01/28 职场文书
《童年》教学反思
2014/02/18 职场文书
离职证明范本(5篇)
2014/09/19 职场文书
2014年预算员工作总结
2014/12/05 职场文书
幼儿园语言教学反思
2016/02/23 职场文书
导游词之无锡丝业博物馆
2019/11/12 职场文书