1.9. Asosiy PoWni amalga oshirish Keling, blokcheyn prototipi uchun shunga o'xshash algoritmni amalga oshiramiz.
Biz yuqorida aytib o'tilgan qoidaga o'xshash qoidani (muammoni) qabul qilamiz:
p raqamini toping, shundayki, oldingi blokning yechimi bilan xeshlanganda u
to'rtta bosh nolga ega xeshni hosil qiladi.
1 import hashlib
2 import json
3
4 from time import time
5 from uuid import uuid4
6
7
8 class Blockchain(object):
9 ...
10
11 def proof_of_work(self, last_proof):
12 """
13 Algoritmni oddiy tekshirish:
14 - p` raqamini topish, chunki hash(pp`) 4 ta bosh nolni o'z ichiga oladi, bu erda p – oldingi
15 - p - oldingi dalil, p` esa yangi
16
17 :param last_proof: 18 :return: 19 """
20
21 proof = 0
22 while self.valid_proof(last_proof, proof) is False:
23 proof += 1
24
25 return proof
26
27 @staticmethod
28 def valid_proof(last_proof, proof):
29 """
30 Isbot isboti: hash(last_proof, proof) 4 ta bosh noldan iboratmi?
31
32 :param last_proof: Oldingi isbot
33 :param isboti: Joriy dalil
34 :return: To'g'ri bo'lsa rost, bo'lmasa noto'g'ri.
35 """
36
37 guess = f'{last_proof}{proof}'.encode()
38 guess_hash = hashlib.sha256(guess).hexdigest()
39 return guess_hash[:4] == "0000"
Algoritmning murakkabligini sozlash uchun biz bosh nol sonini o'zgartirishimiz
mumkin. Bizning holatda, 4 ta etarli. Bitta qo'shimcha nol qo'shilishi, yechim topish
uchun zarur bo'lgan vaqtni katta farq qiladi (kon).
1.10 Yangi bloklar va PoW yaratishning amaliy misoli Blockchain sinfida biz ikkita ro'yxat bilan blokcheyn sinfini yaratamiz, biri
bloklarni saqlash uchun, biri tranzaktsiyalarni saqlash uchun. Mana shunday sinfning
tartibi:
1 package blockchain.basic;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 public class Blockchain {
7
8 private List chain = new ArrayList<>();
10 private List currentTransactions = new Ar-
rayList<>();
11
12
13 public void newBlock() {
14
15 }
16
17 public void newTransaction() {
18
19 }
20
21 public static void hash(Block block) {
22
23 }
24
25 public Block lastBlock() {
26
27 return this.chain.size()>0?this.chain.get(this.chain.size()-
1):null;
28 }
29
30 }