-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathblockchain.py
More file actions
81 lines (63 loc) · 2.56 KB
/
blockchain.py
File metadata and controls
81 lines (63 loc) · 2.56 KB
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
from typing import Union, List
from abstract_participant import AbstractParticipant
from transaction import Transaction
import hashlib
import json
from time import time
class Blockchain(object):
def __init__(self):
self.chain = []
self.pending_transactions = []
self.new_block(previous_hash="Initial block : blockchain begins here",
proof=100)
# Create a new block listing key/value pairs of block information in a JSON object.
# Reset the list of pending transactions & append the newest block to the chain.
def __str__(self) -> str:
return json.dumps({
'chain': [{
'index': chain_element['index'],
'content': [a_transaction.to_dict() for a_transaction in chain_element['transactions']]
} for chain_element in self.chain]
})
def new_block(self, proof, previous_hash=None):
try:
new_hash = self.hash(self.chain[-1]['transactions'][0].data)
except:
new_hash = None
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.pending_transactions,
'proof': proof,
'previous_hash': previous_hash or new_hash,
}
self.pending_transactions = []
self.chain.append(block)
return block
# Search the blockchain for the most recent block.
@property
def last_block(self):
return self.chain[-1]
# Add a transaction with relevant info to the 'blockpool' - list of pending tx's.
def add_transaction(self, data, participant_a: AbstractParticipant,
participant_b: AbstractParticipant) -> Transaction:
transaction = Transaction(data, participant_a, participant_b)
self.pending_transactions.append(transaction)
return transaction
def fetch_transaction_ids(self, transaction_ids: List[str]) -> dict:
"""
:param transaction_ids:
:return: {transacton_id: content}
"""
found_transactions= {}
for block in self.chain:
for a_transaction in block['transactions']:
if a_transaction.id in transaction_ids:
found_transactions.update({a_transaction.id: a_transaction.data})
return found_transactions
def hash(self, block):
string_object = json.dumps(block, sort_keys=True)
block_string = string_object.encode()
raw_hash = hashlib.sha256(block_string)
hex_hash = raw_hash.hexdigest()
return hex_hash