濮阳杆衣贸易有限公司

主頁(yè) > 知識(shí)庫(kù) > Python創(chuàng)建自己的加密貨幣的示例

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

熱門(mén)標(biāo)簽:舉辦過(guò)冬奧會(huì)的城市地圖標(biāo)注 qt百度地圖標(biāo)注 地圖地圖標(biāo)注有嘆號(hào) 阿里電話機(jī)器人對(duì)話 螳螂科技外呼系統(tǒng)怎么用 電銷機(jī)器人系統(tǒng)廠家鄭州 正安縣地圖標(biāo)注app 400電話申請(qǐng)資格 遼寧智能外呼系統(tǒng)需要多少錢(qián)

隨著當(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ù)庫(kù),它不可逆地記錄和認(rèn)證數(shù)字資產(chǎn)的擁有和傳輸。像比特幣和以太坊這樣的數(shù)字貨幣就是基于這個(gè)概念。 

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

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

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

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

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

在本教程中,我將逐步說(shuō)明構(gòu)建數(shù)字貨幣的過(guò)程(我使用了Python編程語(yǔ)言的面向?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)在,讓我解釋一下接下來(lái)應(yīng)該怎么做……

1.建立第一個(gè)Block類

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

在應(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í)例,從而可以訪問(wèn)與該類關(guān)聯(lián)的方法和屬性;
  • 索引—跟蹤區(qū)塊鏈在區(qū)塊鏈中的位置;
  • proof_no-這是在創(chuàng)建新塊(稱為挖礦)期間產(chǎn)生的數(shù)量;
  • prev_hash —這是指鏈中上一個(gè)塊的哈希值;
  • 數(shù)據(jù)-提供所有已完成交易的記錄,例如購(gòu)買(mǎi)數(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ū)塊將具有無(wú)效的哈希值,從而導(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方法來(lái)構(gòu)建鏈中的初始?jí)K。在區(qū)塊鏈慣例中,此塊是特殊的,因?yàn)樗笳髦鴧^(qū)塊鏈的開(kāi)始。

在這種情況下,讓我們通過(guò)簡(jiǎn)單地將一些默認(rèn)值傳遞給Construct_block方法來(lái)構(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ì)重置該列表以確保將來(lái)的事務(wù)被添加到該列表中。并且,該過(guò)程將連續(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語(yǔ)句檢查每個(gè)塊的哈希是否正確。

它還通過(guò)比較其哈希值來(lái)驗(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方法中的說(shuō)明進(jìn)行重置。

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

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

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è)可以解決問(wèn)題的編號(hào)。

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

在這種情況下,我們將使用一種簡(jiǎn)單的算法來(lái)阻止人們挖掘區(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)

有效!

這是挖掘過(guò)程的輸出:

***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ú)法滿足當(dāng)前市場(chǎng)對(duì)穩(wěn)定,安全且易于使用的加密貨幣的需求。

因此,仍可以通過(guò)添加其他功能來(lái)增強(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)文章!

您可能感興趣的文章:
  • python 逆向爬蟲(chóng)正確調(diào)用 JAR 加密邏輯
  • Python3 使用cookiejar管理cookie的方法
  • python調(diào)用java的jar包方法
  • Java實(shí)現(xiàn)的執(zhí)行python腳本工具類示例【使用jython.jar】
  • Python爬蟲(chóng)實(shí)例之2021貓眼票房字體加密反爬策略(粗略版)
  • python通過(guò)cython加密代碼
  • python 實(shí)現(xiàn)aes256加密
  • Python 正確調(diào)用 jar 包加密得到加密值的操作方法

標(biāo)簽:信陽(yáng) 隨州 合肥 昭通 濟(jì)源 興安盟 阜新 淘寶好評(píng)回訪

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python創(chuàng)建自己的加密貨幣的示例》,本文關(guān)鍵詞  Python,創(chuàng)建,自己的,加密,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Python創(chuàng)建自己的加密貨幣的示例》相關(guān)的同類信息!
  • 本頁(yè)收集關(guān)于Python創(chuàng)建自己的加密貨幣的示例的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    武鸣县| 墨竹工卡县| 乐都县| 枣强县| 万荣县| 沙河市| 盈江县| 汤阴县| 大埔区| 神农架林区| 南澳县| 望城县| 鄯善县| 屏山县| 饶河县| 页游| 柳林县| 淳化县| 耿马| 高邮市| 临湘市| 凌云县| 烟台市| 宁波市| 长葛市| 许昌市| 策勒县| 太康县| 朔州市| 营山县| 海安县| 齐齐哈尔市| 房产| 太康县| 吴桥县| 万年县| 白朗县| 镶黄旗| 建始县| 西林县| 南部县|