欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python創(chuàng)建自己的加密貨幣的示例

 更新時(shí)間:2021年03月01日 10:20:28   作者:鏈三豐  
這篇文章主要介紹了Python創(chuàng)建自己的加密貨幣的示例,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下

隨著當(dāng)前加密貨幣的興起,區(qū)塊鏈在技術(shù)界引起了轟動(dòng)。 

這項(xiàng)技術(shù)之所以吸引了如此多的關(guān)注,主要是因?yàn)樗哂斜WC安全,強(qiáng)制分權(quán)和加快多個(gè)行業(yè)(尤其是金融行業(yè))流程的能力。

本質(zhì)上,區(qū)塊鏈?zhǔn)且粋€(gè)公共數(shù)據(jù)庫,它不可逆地記錄和認(rèn)證數(shù)字資產(chǎn)的擁有和傳輸。像比特幣和以太坊這樣的數(shù)字貨幣就是基于這個(gè)概念。 

區(qū)塊鏈?zhǔn)且豁?xiàng)令人興奮的技術(shù),可用于轉(zhuǎn)換應(yīng)用程序的功能。

最近,我們看到政府,組織和個(gè)人使用區(qū)塊鏈技術(shù)來創(chuàng)建自己的加密貨幣。值得注意的是,當(dāng)Facebook提出自己的加密貨幣Libra時(shí),這一公告激起了全世界的許多熱潮。

如果您也可以效仿并創(chuàng)建自己的加密貨幣版本,你應(yīng)該如何著手?

我考慮了這一點(diǎn),決定開發(fā)一種可以創(chuàng)建加密貨幣的算法。

我決定將加密貨幣稱為fccCoin。 

在本教程中,我將逐步說明構(gòu)建數(shù)字貨幣的過程(我使用了Python編程語言的面向?qū)ο蟾拍睿?nbsp;

這是用于創(chuàng)建fccCoin的區(qū)塊鏈算法的基本藍(lán)圖:

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.建立第一個(gè)Block類

區(qū)塊鏈由幾個(gè)相互連接的塊組成,因此,如果一個(gè)塊被篡改,則鏈將變?yōu)闊o效。

在應(yīng)用上述概念時(shí),我創(chuàng)建了以下初始?jí)K類:

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ù)將在啟動(dòng)Block類時(shí)執(zhí)行,就像在其他任何Python類中一樣。

我為啟動(dòng)函數(shù)提供了以下參數(shù):

  • self-引用Block類的實(shí)例,從而可以訪問與該類關(guān)聯(lián)的方法和屬性;
  • 索引—跟蹤區(qū)塊鏈在區(qū)塊鏈中的位置;
  • proof_no-這是在創(chuàng)建新塊(稱為挖礦)期間產(chǎn)生的數(shù)量;
  • prev_hash —這是指鏈中上一個(gè)塊的哈希值;
  • 數(shù)據(jù)-提供所有已完成交易的記錄,例如購買數(shù)量;
  • 時(shí)間戳記-為事務(wù)放置時(shí)間戳記。

類中的第二個(gè)方法calculate_hash將使用上述值生成塊的哈希。SHA-256模塊被導(dǎo)入到項(xiàng)目中,以幫助獲得塊的哈希值。

將值輸入到密碼哈希算法后,該函數(shù)將返回一個(gè)256位字符串,表示該塊的內(nèi)容。

這就是在區(qū)塊鏈中實(shí)現(xiàn)安全性的方式-每個(gè)塊都將具有哈希,并且該哈希將依賴于前一個(gè)塊的哈希。

因此,如果有人試圖破壞鏈中的任何區(qū)塊,其他區(qū)塊將具有無效的哈希值,從而導(dǎo)致整個(gè)區(qū)塊鏈網(wǎng)絡(luò)的破壞。

最終,一個(gè)塊將如下所示:

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

2.建立區(qū)塊鏈類

顧名思義,區(qū)塊鏈的主要思想涉及將多個(gè)區(qū)塊相互“鏈接”。

因此,我將構(gòu)建一個(gè)對(duì)管理整個(gè)鏈的工作很有用的Blockchain類。這是大多數(shù)動(dòng)作將要發(fā)生的地方。

該Blockchain類將在blockchain完成各種任務(wù)的各種輔助方法。

讓我解釋一下每個(gè)方法在類中的作用。

A.構(gòu)造方法

此方法確保實(shí)例化區(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() -此方法將負(fù)責(zé)構(gòu)造初始?jí)K。

B.構(gòu)建創(chuàng)世塊

區(qū)塊鏈需要一個(gè)construct_genesis方法來構(gòu)建鏈中的初始?jí)K。在區(qū)塊鏈慣例中,此塊是特殊的,因?yàn)樗笳髦鴧^(qū)塊鏈的開始。

在這種情況下,讓我們通過簡(jiǎn)單地將一些默認(rèn)值傳遞給Construct_block方法來構(gòu)造它。

盡管您可以提供所需的任何值,但我都給了proof_no和prev_hash一個(gè)零值。

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ū)塊鏈的長(zhǎng)度;
  • proof_nor&prev_hash —調(diào)用者方法傳遞它們;
  • 數(shù)據(jù)-包含節(jié)點(diǎn)上任何塊中未包含的所有事務(wù)的記錄;
  • self.current_data-用于重置節(jié)點(diǎn)上的事務(wù)列表。如果已經(jīng)構(gòu)造了一個(gè)塊并將事務(wù)分配給該塊,則會(huì)重置該列表以確保將來的事務(wù)被添加到該列表中。并且,該過程將連續(xù)進(jìn)行;
  • self.chain.append()-此方法將新構(gòu)建的塊連接到鏈;
  • return-最后,返回一個(gè)構(gòu)造的塊對(duì)象。

D.檢查有效性

該check_validity方法是評(píng)估blockchain的完整性,確保異常是絕對(duì)重要。

如上所述,散列對(duì)于區(qū)塊鏈的安全至關(guān)重要,因?yàn)榧词箤?duì)象發(fā)生任何細(xì)微變化也將導(dǎo)致生成全新的哈希。 

因此,此check_validity 方法使用if語句檢查每個(gè)塊的哈希是否正確。

它還通過比較其哈希值來驗(yàn)證每個(gè)塊是否指向正確的上一個(gè)塊。如果一切正確,則返回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ù)的塊。這是一種非常簡(jiǎn)單的方法:它接受三個(gè)參數(shù)(發(fā)送者的詳細(xì)信息,接收者的詳細(xì)信息和數(shù)量),并將交易數(shù)據(jù)附加到self.current_data列表中。

每當(dāng)創(chuàng)建新塊時(shí),都會(huì)將該列表分配給該塊,并再次按Construct_block方法中的說明進(jìn)行重置。

將交易數(shù)據(jù)添加到列表后,將返回要?jiǎng)?chuàng)建的下一個(gè)塊的索引。

該索引是通過將當(dāng)前塊的索引(即區(qū)塊鏈中的最后一個(gè))的索引加1來計(jì)算的。數(shù)據(jù)將幫助用戶將來提交交易。

def new_data(self, sender, recipient, quantity):
 self.current_data.append({
  'sender': sender,
  'recipient': recipient,
  'quantity': quantity
 })
 return True

F.添加工作證明

工作量證明是防止區(qū)塊鏈濫用的概念。簡(jiǎn)而言之,其目的是在完成一定數(shù)量的計(jì)算工作后,確定一個(gè)可以解決問題的編號(hào)。

如果識(shí)別數(shù)字的難度很高,則不鼓勵(lì)發(fā)送垃圾郵件和篡改區(qū)塊鏈。

在這種情況下,我們將使用一種簡(jiǎn)單的算法來阻止人們挖掘區(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ū)塊鏈中的最后一個(gè)塊。請(qǐng)記住,最后一個(gè)塊實(shí)際上是鏈中的當(dāng)前塊。

@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)在,讓我們測(cè)試我們的代碼,看看它是否有效。

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ū)塊鏈的方式。

如果按原樣部署該代幣,它將無法滿足當(dāng)前市場(chǎng)對(duì)穩(wěn)定,安全且易于使用的加密貨幣的需求。

因此,仍可以通過添加其他功能來增強(qiáng)其挖掘和發(fā)送財(cái)務(wù)交易的功能,從而對(duì)其進(jìn)行改進(jìn)。

以上就是Python創(chuàng)建自己的加密貨幣的示例的詳細(xì)內(nèi)容,更多關(guān)于Python創(chuàng)建自己的加密貨幣的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • OpenCV平滑處理的實(shí)現(xiàn)示例

    OpenCV平滑處理的實(shí)現(xiàn)示例

    本文主要介紹了OpenCV平滑處理的實(shí)現(xiàn)示例,Opencv中濾波方式可分為均值濾波、高斯濾波和中值濾波,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-02-02
  • Python樹的重建實(shí)現(xiàn)示例

    Python樹的重建實(shí)現(xiàn)示例

    樹的重建是一種從給定的遍歷序列中恢復(fù)原樹結(jié)構(gòu)的算法,本文就來介紹一下Python樹的重建實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-11-11
  • python繪制箱線圖boxplot()的教程詳解

    python繪制箱線圖boxplot()的教程詳解

    本文主要介紹了python如何繪制箱線圖boxplot()的方法教程,文中有詳細(xì)的代碼示例和圖文講解,需要的朋友可以參考下
    2023-05-05
  • Python繪制雷達(dá)圖時(shí)遇到的坑的解決

    Python繪制雷達(dá)圖時(shí)遇到的坑的解決

    這篇文章主要介紹了Python繪制雷達(dá)圖時(shí)遇到的坑的解決,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • tensor.squeeze函數(shù)和tensor.unsqueeze函數(shù)的使用詳解

    tensor.squeeze函數(shù)和tensor.unsqueeze函數(shù)的使用詳解

    本文主要介紹了tensor.squeeze函數(shù)和tensor.unsqueeze函數(shù)的使用詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • python定時(shí)任務(wù)schedule庫用法詳細(xì)講解

    python定時(shí)任務(wù)schedule庫用法詳細(xì)講解

    python中有一個(gè)輕量級(jí)的定時(shí)任務(wù)調(diào)度的庫schedule,下面這篇文章主要給大家介紹了關(guān)于python定時(shí)任務(wù)schedule庫用法的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-01-01
  • 老生常談Python中的Pickle庫

    老生常談Python中的Pickle庫

    pickle是python語言的一個(gè)標(biāo)準(zhǔn)模塊,安裝python后已包含pickle庫,不需要單獨(dú)再安裝。這篇文章主要介紹了Python中的Pickle庫,需要的朋友可以參考下
    2022-01-01
  • python自動(dòng)化運(yùn)維之Telnetlib的具體使用

    python自動(dòng)化運(yùn)維之Telnetlib的具體使用

    本文將結(jié)合實(shí)例代碼,介紹python自動(dòng)化運(yùn)維之Telnetlib的具體使用,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-06-06
  • 使用pycharm和pylint檢查python代碼規(guī)范操作

    使用pycharm和pylint檢查python代碼規(guī)范操作

    這篇文章主要介紹了使用pycharm和pylint檢查python代碼規(guī)范操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • python中字典(Dictionary)用法實(shí)例詳解

    python中字典(Dictionary)用法實(shí)例詳解

    這篇文章主要介紹了python中字典(Dictionary)用法,以實(shí)例形式較為詳細(xì)的分析了Python字典建立、添加、刪除等常見操作技巧,需要的朋友可以參考下
    2015-05-05

最新評(píng)論