-
Notifications
You must be signed in to change notification settings - Fork 39
/
walkthrough.py
68 lines (50 loc) · 2.2 KB
/
walkthrough.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
import hashlib
import json
from time import time
class Blockchain(object):
def __init__(self):
self.chain = []
self.pending_transactions = []
self.new_block(previous_hash="The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.", 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 new_block(self, proof, previous_hash=None):
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.pending_transactions,
'proof': proof,
'previous_hash': previous_hash or self.hash(self.chain[-1]),
}
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 new_transaction(self, sender, recipient, amount):
transaction = {
'sender': sender,
'recipient': recipient,
'amount': amount
}
self.pending_transactions.append(transaction)
return self.last_block['index'] + 1
# receive one block. Turn it into a string, turn that into Unicode (for hashing). Hash with SHA256 encryption, then translate the Unicode into a hexidecimal string.
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
blockchain = Blockchain()
t1 = blockchain.new_transaction("Satoshi", "Mike", '5 BTC')
t2 = blockchain.new_transaction("Mike", "Satoshi", '1 BTC')
t3 = blockchain.new_transaction("Satoshi", "Hal Finney", '5 BTC')
blockchain.new_block(12345)
t4 = blockchain.new_transaction("Mike", "Alice", '1 BTC')
t5 = blockchain.new_transaction("Alice", "Bob", '0.5 BTC')
t6 = blockchain.new_transaction("Bob", "Mike", '0.5 BTC')
blockchain.new_block(6789)
print("Genesis block: ", blockchain.chain)