Browse Source

Initial commit.

master
Toromino 3 years ago
parent
commit
786c0d1aed
No account linked to committer's email address
3 changed files with 105 additions and 0 deletions
  1. 23
    0
      block.py
  2. 65
    0
      blockchain.py
  3. 17
    0
      example_chain.py

+ 23
- 0
block.py View File

@@ -0,0 +1,23 @@
1
+import hashlib
2
+import jsonpickle
3
+
4
+class Block(object):
5
+
6
+    def __init__(self, _index, _timestamp, _data = [], _prevHash = '', _merkleHash = ''):
7
+        self.index, self.timestamp, self.data, self.prevHash, self.merkleHash, self.nonce, self.hash = _index, _timestamp, _data, _prevHash, _merkleHash, 0, ''
8
+
9
+
10
+    def calculateHash(self):
11
+        hash = ''.join([str(self.index), str(self.prevHash), str(self.merkleHash), str(self.timestamp), jsonpickle.encode(self.data), str(self.nonce)])
12
+        hash = hash.encode('utf-8')
13
+        return hashlib.sha256(hash).hexdigest()
14
+
15
+    def mine(self, _difficulty):
16
+        s = []
17
+        for i in range(0, _difficulty):
18
+            s.append('0')
19
+        s = ''.join(s)
20
+        while self.hash[0:_difficulty] != s:
21
+            self.nonce+=1
22
+            self.hash = self.calculateHash()
23
+        print("[Info] Block mined: ", self.hash)

+ 65
- 0
blockchain.py View File

@@ -0,0 +1,65 @@
1
+import time, json, sys
2
+
3
+from block import Block
4
+
5
+class Blockchain(object):
6
+
7
+    def __init__(self, _startDifficulty, _maxBlockSize,_nodes = []):
8
+        self.chain, self.difficulty, self.nodes, self.latestData, self.maxBlockSize = [self.createGenesisBlock()], _startDifficulty, _nodes, [], _maxBlockSize
9
+
10
+    def addData(self, _data):
11
+        self.latestData.append(_data)
12
+
13
+        return self.getLatestBlock().index + 1
14
+
15
+    def createGenesisBlock(self):
16
+        block = Block(0, time.ctime(), "Genesis block")
17
+        block.hash = block.calculateHash();
18
+        self.addLocalBlockFile(block)
19
+        return block
20
+
21
+    def getLatestBlock(self):
22
+        return self.chain[len(self.chain) - 1]
23
+
24
+    def addBlock(self, _block):
25
+        if sys.getsizeof(self.latestData) >= self.maxBlockSize:
26
+            if len(self.chain) % 1000 == 0:
27
+                self.difficulty += 1
28
+            _block.prevHash = self.getLatestBlock().hash
29
+            _block.mine(self.difficulty)
30
+            _block.data = self.latestData
31
+
32
+            self.addLocalBlockFile(_block)
33
+
34
+            self.chain.append(_block)
35
+            self.latestData = []
36
+
37
+    def addLocalBlockFile(self, _block):
38
+        with open(''.join(['blocks/',_block.hash, '.tbf']), 'a') as outfile:
39
+            json.dump([str(_block.index),
40
+            str(_block.prevHash),
41
+            str(_block.merkleHash),
42
+            str(_block.timestamp),
43
+            str(_block.data),
44
+            str(_block.nonce)], outfile, ensure_ascii=False)
45
+
46
+    def addNode(self, _url):
47
+        self.nodes.append(urlparse(_url))
48
+
49
+    def isValid(self):
50
+        for i in range(1, len(self.chain)):
51
+            currentBlock = self.chain[i]
52
+            prevBlock = self.chain[i-1]
53
+
54
+            if currentBlock.hash != currentBlock.calculateHash() or  currentBlock.prevHash != prevBlock.hash:
55
+                return False
56
+
57
+        return True
58
+
59
+    def restoreValidity(self):
60
+
61
+        return True
62
+
63
+    def compareToFullChain(self):
64
+        if self.restoreValidity == True:
65
+            return True

+ 17
- 0
example_chain.py View File

@@ -0,0 +1,17 @@
1
+import time
2
+
3
+from block import Block
4
+from blockchain import Blockchain
5
+
6
+testBlockchain = Blockchain(4, 42)
7
+
8
+for i in range(100):
9
+
10
+    block = Block(len(testBlockchain.chain), time.ctime())
11
+    print("".join(["[Info] Mining block ", str(block.index), " with difficulty ", str(testBlockchain.difficulty), "... "]))
12
+    testBlockchain.addBlock(block)
13
+
14
+    if testBlockchain.isValid():
15
+        print("\n[Info] Is blockchain valid? ", str(testBlockchain.isValid()))
16
+    else:
17
+        print("\n[Error] Is blockchain valid? ",str(testBlockchain.isValid()))

Loading…
Cancel
Save