LoginSignup
5
4

More than 5 years have passed since last update.

Pythonでブロックチェーンを組んでみる実験

Posted at

pythonで遊ぶ機会があったのでお遊びで作ったもののメモ

import hashlib
import json
import datetime
import pickle

class Block:
    def __init__(self, index, timestamp, transaction, previous_hash):
        self.index = index
        self.timestamp = timestamp
        self.transaction = transaction
        self.previous_hash = previous_hash
        self.difficulty = 4 #難易度を追加
        self.property_dict = {str(i): j for i, j in self.__dict__.items()}
        self.now_hash = self.calc_hash()
        self.proof = None # プルーフを追加
        self.proof_hash = None # プルーフを追加して計算したハッシュ

    def calc_hash(self):
        block_string = json.dumps(self.property_dict, sort_keys=True).encode('ascii')
        return hashlib.sha256(block_string).hexdigest()

    # プルーフの検証用関数
    def check_proof(self, proof):
        proof_string = self.now_hash + str(proof)
        calced = hashlib.sha256(proof_string.encode("ascii")).hexdigest()
        if calced[:self.difficulty:].count('0') == self.difficulty:
            self.proof_hash = calced
            return True
        else:
            return False

    # プルーフを採掘するための関数
    def mining(self):
        proof = 0
        while True:
            if self.check_proof(proof):
                break
            else:
                proof += 1
        return proof

# トランザクションを生成
def new_transaction(sender, recipient, amount):
    transaction = {
        "差出人": sender,
        "あて先": recipient,
        "金額": amount,
    }
    return transaction

block_chain = []

block = Block(0, 0, [], '-') #最初のブロックを作成

block.proof = block.mining()

block_chain.append(block)

i=0
while datetime.datetime(2018, 11, 10, 3, 20) > datetime.datetime.now(): 
# for i in range(10):
    # i=0
    # i=i+1
    block = Block(i+1, str(datetime.datetime.now()), new_transaction("太郎", "花子", 100), block_chain[i].now_hash)
    block.proof = block.mining()
    block_chain.append(block)


    with open('sample.pickle', mode='wb') as f:
        pickle.dump(block_chain, f)
        f.close()

    i=i+1

    for block in block_chain:
        for key, value in block.__dict__.items():
            print(key, ':', value)
        print("")
    print("==== ==== ==== ==== ==== ==== ==== ==== ====")

#    for block in block_chain:
#        for key, value in block.__dict__.items():
#            print(key, ':', value)
#        print("")

'''
print("==== ==== ==== ==== ==== ==== ==== ==== ====")
with open('sample.pickle', mode='rb') as f:
    pickle.load(f)
    f.close()

    for block in block_chain:
        for key, value in block.__dict__.items():
            print(key, ':', value)
        print("")
'''

'''
for block in block_chain:
    for key, value in block.__dict__.items():
        print(key, ':', value)
    print("")
'''

参考

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4