Simple Python Blockchain Implementation Script -- Simplecoin Part 1

Namaste Friends,



Sorry For my late blog posts, Actually I was studying blockchain and bitcoin concepts. So, Today, I am going to share with you a very beginners level python script where i tried to create a simple blockchain based ledger.


Note

  • Tutorials And Reference For This Script Coming Soon...
  • Sorry For Less Comments And Bad Coding Styles.

Actually, Guys, I'm Still Busy In Developing This Script To Make More Advance, Adding More Features In It.
So, I'm Open For Suggestions Comments.


Some Key Features Of This Script.


  • Transactions Feature Supported
  • Transactions Merkle Data hashing Algorithm Supported
  • Proof Of Work Supported (hashcash)
  • Database created In Json To Make It More Simple To Understand
  • Python Object Orient Programming Basic Support


For More Details. Refer To my Github Repo. Check Here


  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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
#!/usr/bin/python

__author__='''
        Suraj Singh bisht
        surajsinghbisht054@gmail.com
        www.bitforestinfo.com
        github.com/surajsinghbisht054


'''

#
# import modules
import json
import os
from hashlib import sha256
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
import time


# Simple Request Transection
class RequestTransection:
    def __init__(self):
        '''
        
        '''
        self.category = ''
        self.sender   = ''
        self.receiver = ''
        self.amount   = ''
        self.time     = str(time.time())
        self.fee      = ''
        self.sign     = ''
        self.pubkey   = ''
        self.prvkey   = ''
        self.rsa_key  = ''
        
    def getitems(self):
        return {
            "category" : self.category,
            "sender"   : self.sender,
            "receiver" : self.receiver,
            "amount"   : self.amount,
            "fee"      : self.fee,
            "sign"     : self.sign,
            "time"     : self.time,
            
        }
    
    def __repr__(self):
        return "< Transection {} | {} >".format(self.category, self.time)

    def new_user(self):
        random  = RSA.Random.new().read
        self.rsa_key = RSA.generate(512, random) 
        self.prvkey  =  self.rsa_key.exportKey() # private key object
        self.pubkey  =  self.rsa_key.publickey().exportKey() # public key object
        self.create_transection("n", '', )
        return
    
    def create_transection(self, category, sender, receiver, amount, fee):
        category = category.lower()
        if category not in ['new', 'send', 'receive']:
            raise "please use valid categories like new, send or receive"
        
        self.category = category
        self.sender   = sender
        self.receiver = receiver
        self.amount   = amount
        self.fee      = fee
        return

    def previous_block_hash(self, blockitemdict):
        return sha256("{index}{previoushash}{timestamp}{hash}{datahash}{nonce}{targetbit}".format(**blockitemdict)).hexdigest()


# In[62]:


class RequestBlock:
    def __init__(self, index, previoushash, targetbit=3, transbuffer = []):
        self.index       = index
        self.previoushash = previoushash
        self.timestamp   = str(time.time())
        self.targetbit   = targetbit
        self.hash        = ''
        self.datahash    = ''
        self.dataload    = []
        self.nonce       = ''
        self.transbuffer = transbuffer
        self.calculate_block()
        
    def previous_block_hash(self, blockitemdict):
        return sha256("{index}{previoushash}{timestamp}{hash}{datahash}{nonce}{targetbit}".format(**blockitemdict)).hexdigest()

    def merkle_hash(self):
        hl1 = []
        hl2 = []
        
        for data in self.dataload:
            #print data.getitem()
            hl1.append(sha256("{category}{sender}{receiver}{amount}{fee}{sign}{time}".format(**data.getitems())).hexdigest())
        
        if not hl1:
            return sha256('').hexdigest()
        
        while True:
            v1 = ''
            v2 = ''
            hl2 = []
    
            if int(len(hl1) % 2)==0 and len(hl1)>1:
                # Even Number's List
        
                for h in hl1:
                    if not v1:
                        v1 = h
                        continue
                    v2 = h
            
                    hl2.append(sha256(v1+v2).hexdigest())
                    v1 = ''
                    v2 = ''
    
            elif int(len(hl1) % 2)==1 and len(hl1)>1:
                hl2 = hl1
                hl2.append('')
    
    
            elif len(hl1)==1:
                return hl1[0]
            
            else:
                return False

            hl1 = hl2        

        return False
        
    
    def calculate_block(self): 
        # load transections from Node Buffer
        self.load_data_from_network_buffer()
        tmp = self.merkle_hash()
        if not tmp:
            print "[Note] No Data load Found"
        self.datahash = tmp
        return
        
    def load_data_from_network_buffer(self):
        for trans_req in self.transbuffer:
            if trans_req not in self.dataload:
                self.dataload.append(trans_req)
        return
        
    def getitems(self):
        return {
            "index"       : self.index,
            "previoushash": self.previoushash,
            "timestamp"   : self.timestamp,
            "targetbit"   : self.targetbit,
            "hash"        : self.hash,
            "datahash"    : self.datahash,
            "dataload"    : [i.getitems() for i in self.dataload],
            "nonce"       : self.nonce,
        }



class MineBlock:
    def __init__(self):
        self.pow = False
        self.block = ''
        self.difficulty = 0
        
    
    def load(self, block):
        self.block = block
        self.difficulty = int(self.block.targetbit)
        self.proof_of_work_number_generator()
        self.pow = True
        return
    
    def getblock(self):
        return self.block
    
    def getitems(self):
        return self.block.getitems()
    
    def previous_block_hash(self, blockitemdict):
        return sha256("{index}{previoushash}{timestamp}{hash}{datahash}{nonce}{targetbit}".format(**blockitemdict)).hexdigest()
    
    
    def proof_of_work_number_generator(self):
        self.block.nonce = 0
        while sha256("{}{}{}{}{}".format(self.block.previoushash,self.block.datahash,self.block.timestamp,self.block.targetbit,self.block.nonce)).hexdigest()[:self.difficulty]!='0'*self.difficulty:
            self.block.nonce+= 1
        self.block.hash = sha256("{}{}{}{}{}".format(self.block.previoushash,self.block.datahash,self.block.timestamp,self.block.targetbit,self.block.nonce)).hexdigest()
        return self.block.nonce
    


class SimpleBlockChain:
    
    def __init__(self, dbname='ChainStore.json'):
        self.dbname = dbname
        
        # Check BlockChain Json Storage File
        if os.path.exists(self.dbname):
            self.chain  = json.load(open(self.dbname, 'r'))
        else:
            self.chain = {
                "blockchain": [],
                'lastupdate': time.time(),
            }
        
        
        # Check BlockChain Status    
        if not self.check_chain_len():
            
            # Add Genesis Block
            self.add_genesis_block()
        
        
    # add genesis block request
    def add_genesis_block(self):
        print "Add Genesis Block Request"
        tmpobj = RequestBlock(1,0)
        mineblock = MineBlock()
        mineblock.load(tmpobj)
        self.new_block_request(mineblock.getblock())
        return
    
    # New Blocking Join Request
    def new_block_request(self, block):
        
        # Verify Block
        if self.validate_new_block(block):
            self.chain['blockchain'].append(block.getitems())
            pass
        return
    
    
    # Validate New Block Before Joining It to main Chain
    def validate_new_block(self, block):
        return True
        
        
    # Check block chain length
    def check_chain_len(self):
        return len(self.chain['blockchain'])
    
    def pre_block(self):
        return self.chain['blockchain'][-1]
        #return
        
    # save updates
    def close(self):
        f = open(self.dbname, 'w')
        self.chain['lastupdate']= time.time()
        json.dump(self.chain, f, sort_keys=True, indent=4, separators=(',', ': '))
        f.close()
        return
    
    
    
if __name__=='__main__':
    sbc = SimpleBlockChain() 
    trans = RequestTransection()
    trans.create_transection("send", "123456", "654231", '0', '500')
    print trans.previous_block_hash(sbc.pre_block())

    reqblock = RequestBlock(index=sbc.check_chain_len()+1, previoushash=trans.previous_block_hash(sbc.pre_block()), transbuffer=[trans])

    m = MineBlock()
    m.load(reqblock)
    sbc.new_block_request(block=m.getblock())

    print sbc.chain
    sbc.close()


To Run This Script.
Just Type:


$ python path/to/script.py

Blockchain JSON Output


 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
{
    "blockchain": [
        {
            "datahash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
            "dataload": [],
            "hash": "000908b3530025e84e75a3cc9de116c58d2f81eb5d601b25203fc589a5a71909",
            "index": 1,
            "nonce": 6366,
            "previoushash": 0,
            "targetbit": 3,
            "timestamp": "1527103856.95"
        },
        {
            "datahash": "7fa3e2f14492a7c2329587ad2295f2cc2daba78840ab204cb1f2d305184cf05f",
            "dataload": [
                {
                    "amount": "0",
                    "category": "send",
                    "fee": "500",
                    "receiver": "654231",
                    "sender": "123456",
                    "sign": "",
                    "time": "1527103856.97"
                }
            ],
            "hash": "0001deded9620a3f0f22a693142174cdc0f7646722d859805064d5bf40aa6d4c",
            "index": 2,
            "nonce": 13263,
            "previoushash": "fa38a4a2dbda49e55d52410910f8b521aaa7396c4ad7ab3c633b724240ad5c92",
            "targetbit": 3,
            "timestamp": "1527103856.97"
        }
    ],
    "lastupdate": 1527103857.013431
}






Share this

Related Posts

Previous
Next Post »