-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockchain.py
151 lines (116 loc) · 4.33 KB
/
blockchain.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# -*- coding: utf-8 -*-
"""
Created on Mon May 4 00:25:35 2020
@author: smshi
"""
import hashlib
import json
import logging
import sys
import time
from ecdsa import NIST256p
from ecdsa import VerifyingKey
#自分で作ったので標準ワイぶらりとは分ける
import utils
MINING_DIFFICULTY = 3
MINING_SENDER = 'THE BLOCKCHAIN'
MINING_REWARD = 1.0
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
logger = logging.getLogger(__name__)
#ブロックチェーンのクラス生成
class Blockchain(object):
def __init__(self, blockchain_address=None, port=None):
self.transaction_pool = []
self.chain = []
self.create_block(0, 'init hash')
self.blockchain_address = blockchain_address
self.port = port
def create_block(self, nonce, previous_hash):
block = utils.sorted_dict_by_key({
'timestamp': time.time(),
'transactions': self.transaction_pool,
'nonce': nonce,
'previous_hash': previous_hash
})
self.chain.append(block)
self.transaction_pool = []
return block
def hash(self, block):
sorted_block = json.dumps(block, sort_keys=True)#jsonでdictを読み出すときdampで文字列に変換、sort_key=Trueでsort
return hashlib.sha256(sorted_block.encode()).hexdigest()
def add_transaction(self, sender_blockchain_address,
recipient_blockchain_address, value,
sender_public_key=None, signature=None):
transaction = utils.sorted_dict_by_key({
'sender_blockchain_address': sender_blockchain_address,
'recipient_blockchain_address': recipient_blockchain_address,
'value': float(value)
})
#マイニングのときにはしトランザクションの検証はしなくともいい
if sender_blockchain_address == MINING_SENDER:
self.transaction_pool.append(transaction)
return True
if self.verify_transaction_signature(
sender_public_key, signature, transaction):
#if self.calculate_total_amount(sender_blockchain_address) < float(value):
# logger.error({'action': 'add_transaction', 'error': 'no_value'})
# return False
self.transaction_pool.append(transaction)
return True
return False
def create_transaction(self, sender_blockchain_address,
recipient_blockchain_address, value,
sender_public_key, signature):
is_transacted = self.add_transaction(
sender_blockchain_address, recipient_blockchain_address,
value, sender_public_key, signature)
#TODO
#sync
return is_transacted
self.transaction_pool.append(transaction)
return True
def verify_transaction_signature(self, sender_public_key, signature, transaction):
sha256 = hashlib.sha256()
sha256.update(str(transaction).encode('utf-8'))
message = sha256.digest()
signature_byte = bytes().fromhex(signature)
verifing_key = VerifyingKey.from_string(
bytes().fromhex(sender_public_key), curve=NIST256p)
verified_key = verifing_key.verify(signature_byte, message)
return verified_key
def valid_proof(self, transactions, previous_hash,
nonce,difficulty=MINING_DIFFICULTY):
guess_block = utils.sorted_dict_by_key({
'transactions': transactions,
'nonce': nonce,
'previous_hash': previous_hash
})
guess_hash = self.hash(guess_block)
return guess_hash[:difficulty] == '0'*difficulty
def proof_of_work(self):
transactions = self.transaction_pool.copy()
previous_hash = self.hash(self.chain[-1])
nonce = 0
while self.valid_proof(transactions, previous_hash, nonce) is False:
nonce += 1
return nonce
def mining(self):
self.add_transaction(
sender_blockchain_address=MINING_SENDER,
recipient_blockchain_address=self.blockchain_address,
value=MINING_REWARD)
nonce = self.proof_of_work()
previous_hash = self.hash(self.chain[-1])
self.create_block(nonce, previous_hash)
logger.info({'action': 'mining','status': 'success'})
return True
def calculate_total_amount(self, blockchain_address):
total_amount = 0.0
for block in self.chain:
for transaction in block['transactions']:
value = float(transaction['value'])
if blockchain_address == transaction['recipient_blockchain_address']:
total_amount += value
if blockchain_address == transaction['sender_blockchain_address']:
total_amount -= value
return total_amount