2 – amaliy mashg’ulot Mavzu: BigData va Blokcheyn texnologiyalari. Tranzaksiyalar. Blockcheyn prototipini ishlab chiqish muhiti va tuzilishi
Download 0.78 Mb. Pdf ko'rish
|
2-amaliy blokchain
1.7. Yangi bloklarni yaratish Blokcheyn namunasi yaratilgandan so'ng, unga genezis blokini kiritish kerak - o'tmishdoshlari bo'lmagan birinchi blok. Bundan tashqari, ushbu genezis blokiga "dalil" qo'shish kerak bo'ladi, bu konchilik (yoki bajarilgan ishni tasdiqlash) natijasidir. Biz keyinroq qazib olishni ko'rib chiqamiz. Konstruktorda genezis blokini yaratishdan tashqari, biz new_block(), new_transaction() va hash() usullarini ham yozamiz: 1 import hashlib 2 import json 3 from time import time 4 5 class Blockchain(object): 6 def __init__(self): 7 self.current_transactions = [] 8 self.chain = [] 9 10 # Genezis blokining yaratilishi 11 self.new_block(previous_hash=1, proof=100) 12 13 def new_block(self, proof, previous_hash=None): 14 """ 15 Blokcheynda yangi blok yaratish 16 17 : param proof: 18 :param previous_hash: Oldingi blokning xeshi 19 :return: 20 """ 21 22 block = { 23 'index': len(self.chain) + 1, 24 'timestamp': time(), 25 'transactions': self.current_transactions, 26 'proof': proof, 27 'previous_hash': previous_hash or self.hash(self.chain[-1]), 28 } 29 30 # Joriy tranzaktsiyalar ro'yxatini qayta yuklang 31 self.current_transactions = [] 32 33 self.chain.append(block) 34 return block 35 36 def new_transaction(self, sender, recipient, amount): 37 """ 38 Yangi tranzaksiyani keyingi blokga yuboradi 39 40 :param sender: 41 :param recipient: 42 :param amount: 43 :return: 44 """ 45 self.current_transactions.append({ 46 'sender': sender, 47 'recipient': recipient, 48 'amount': amount, 49 }) 50 51 return self.last_block['index'] + 1 52 53 @property 54 def last_block(self): 55 return self.chain[-1] 56 57 @staticmethod 58 def hash(block): 59 60 """ 61 Blokning SHA-256 xeshini yaratadi 62 63 :param block: 64 :return: 65 """ 66 67 # Lug'at buyurtma qilinganligiga ishonch hosil qilish kerak, aks holda mos kelmaydigan xeshlar bo'ladi 68 block_string = json.dumps(block, sort_keys=True).encode() 69 return hashlib.sha256(block_string).hexdigest() Blokcheyn prototipi skeleti bilan deyarli bajarildi. Endi yangi bloklar qanday yaratilganligini bilib olaylik. Download 0.78 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling