-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathblockchain.py
More file actions
132 lines (115 loc) · 5.06 KB
/
blockchain.py
File metadata and controls
132 lines (115 loc) · 5.06 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
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
"""
MIT License
Copyright (c) 2021 STR-Coding-Club
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import json
import sys
from time import time
from crypto import hash
class Blockchain(object):
@property
def last_block(self) -> dict:
# Returns the last (header) block in the chain
return self.chain[-1]
@property
def blockchain(self) -> list:
return self.chain
def __init__(self, chain_file):
self.chain = []
self.pending_transactions = []
self.current_transactions = []
self.pending_balances = {}
self.current_balances = {}
self.push_time = 0
self.mine_time = 0
# If chain already exists on disk
try:
with open(chain_file, 'r') as blockchain_file:
self.chain = json.loads(blockchain_file.read())
return None
except (FileNotFoundError, json.JSONDecodeError):
print('Error while importing chain_file! Creating temporary test chain', file=sys.stderr)
"""
Create Testchain with default Genesis Block
THIS SHOULD NEVER BE CALLED!!
- When rolled out, this functions should instead call for a sync with the node to import the live
chain
"""
self.new_block(previous_hash=1, proof=100)
def new_block(self, proof, previous_hash=None) -> dict:
"""
Creates new block to add to the blockchain. Uses previous header to generate new block.
:param proof: <int> POW value that returns hash < predetermined target hash
:param previous_hash: <str> hash of current header block
:return: <dict> new block
"""
block = {
'index': len(self.chain) + 1,
'transactions': self.current_transactions,
'previous_hash': previous_hash or hash(self.last_block)
}
self.current_transactions = []
# Reset the current list of transactions
block['proof'] = proof
self.chain.append(block)
self.save_blockchain()
self.push_time = time()
self.mine_time = time()
self.current_balances = {}
return block
def new_transaction(self, sender, recipient, amount):
"""
Compiles and appends new incoming transactions to add to the block.
Once mined, transactions will "go through" and are added to the blockchain.
Incoming transactions, therefore, are not transacted until the block is mined.
:param sender: <str> Wallet address of the Sender
:param recipient: <str> Wallet address of the Recipient
:param amount: <float> Amount of $TR (Robcoin) to be transacted
:return: <int> Index of transaction to add to the new block. (see example-block.py)
"""
self.pending_transactions.append(
{
'sender': sender,
'recipient': recipient,
'amount': amount,
})
if sender not in self.pending_balances:
self.pending_balances[sender] = amount
else:
self.pending_balances[sender] += amount
return self.last_block['index'] + 1
def save_blockchain(self, file="blockchain.txt"):
"""
:param file: saves blockchain to 'blockchain.txt' in case node goes down
"""
with open(file, 'w+', encoding='utf-8') as out:
json.dump(self.chain, out, ensure_ascii=False, indent=4) # Padding to make json look pretty
def ready_to_push(self) -> bool:
return (time() - self.push_time) >= 10 # seconds
def ready_to_mine(self) -> bool:
return (time() - self.mine_time) >= 10
def push_pending(self) -> list:
self.current_transactions += self.pending_transactions
self.pending_transactions = []
self.push_time = time()
for sender in self.pending_balances.keys():
if sender not in self.current_balances:
self.current_balances[sender] = self.pending_balances
else:
self.current_balances[sender] += self.pending_balances
self.pending_balances = {}