/
block.py
54 lines (44 loc) · 1.4 KB
/
block.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
from hashlib import sha256
from time import time, localtime
from transaction import Transaction
from utils import (
get_all_transactions_as_str,
validate_argument_type,
get_local_time,
get_sha256,
)
class Block(object):
def __init__(self, block_no, nonce, previous_hash, transactions=None):
self.block_no = block_no
self.transactions = transactions or []
self.nonce = nonce
self.previous_hash = previous_hash
self.timestamp = time()
self.hash = None
def create_hash(self):
block_info = "{}{}{}{}{}".format(
self.block_no,
self.nonce,
self.previous_hash,
self.get_transaction_str(),
self.timestamp)
self.hash = get_sha256(block_info)
@validate_argument_type(Transaction)
def append_transaction(self, transaction):
self.transactions.append(transaction)
def get_transaction_str(self):
return get_all_transactions_as_str(self)
@property
def transactions(self):
return self.transactions_
@transactions.setter
def transactions(self, transactions_):
self.transactions_ = transactions_
def __str__(self):
return "{}{}{}{}{}".format(
self.block_no,
self.nonce,
self.previous_hash,
get_local_time(self.timestamp),
self.hash
)