How to create your own Crypto Blockchain.


SUBMITTED BY: godsend

DATE: Dec. 1, 2020, 4:54 p.m.

UPDATED: Feb. 12, 2021, 3:59 p.m.

FORMAT: Text only

SIZE: 14.7 kB

HITS: 873

  1. Tips or donations can be made at 18e1561MhqrJwmb4tXuCU3V9cGtb3yJCSx further tips or hacks or tutorials on winning big money
  2. Contact Telegram @Passionateforcoin
  3. No charge, I accept only donations.
  4. Here is the basic blueprint of the Python class we’ll use for creating the blockchain:
  5. 1
  6. class Block(object):
  7. 2
  8. 3
  9. def __init__():
  10. 4
  11. 5
  12. pass
  13. 6
  14. 7
  15. #initial structure of the block class
  16. 8
  17. 9
  18. def compute_hash():
  19. 10
  20. 11
  21. pass
  22. 12
  23. 13
  24. #producing the cryptographic hash of each block
  25. 14
  26. 15
  27. class BlockChain(object):
  28. 16
  29. 17
  30. def __init__(self):
  31. 18
  32. 19
  33. #building the chain
  34. 20
  35. 21
  36. def build_genesis(self):
  37. 22
  38. 23
  39. pass
  40. 24
  41. 25
  42. #creating the initial block
  43. 26
  44. 27
  45. def build_block(self, proof_number, previous_hash):
  46. 28
  47. 29
  48. pass
  49. 30
  50. 31
  51. #builds new block and adds to the chain
  52. 32
  53. 33
  54. @staticmethod
  55. 34
  56. 35
  57. def confirm_validity(block, previous_block):
  58. 36
  59. 37
  60. pass
  61. 38
  62. 39
  63. #checks whether the blockchain is valid
  64. 40
  65. 41
  66. def get_data(self, sender, receiver, amount):
  67. 42
  68. 43
  69. pass
  70. 44
  71. 45
  72. # declares data of transactions
  73. 46
  74. 47
  75. @staticmethod
  76. 48
  77. 49
  78. def proof_of_work(last_proof):
  79. 50
  80. 51
  81. pass
  82. 52
  83. 53
  84. #adds to the security of the blockchain
  85. 54
  86. 55
  87. @property
  88. 56
  89. 57
  90. def latest_block(self):
  91. 58
  92. 59
  93. pass
  94. 60
  95. 61
  96. #returns the last block in the chain
  97. Now, let’s explain how the blockchain class works.
  98. Initial Structure of the Block Class
  99. Here is the code for our initial block class:
  100. 1
  101. import hashlib
  102. 2
  103. 3
  104. import time
  105. 4
  106. 5
  107. class Block(object):
  108. 6
  109. 7
  110. def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
  111. 8
  112. 9
  113. self.index = index
  114. 10
  115. 11
  116. self.proof_number = proof_number
  117. 12
  118. 13
  119. self.previous_hash = previous_hash
  120. 14
  121. 15
  122. self.data = data
  123. 16
  124. 17
  125. self.timestamp = timestamp or time.time()
  126. 18
  127. 19
  128. @property
  129. 20
  130. 21
  131. def compute_hash(self):
  132. 22
  133. 23
  134. string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
  135. 24
  136. 25
  137. return hashlib.sha256(string_block.encode()).hexdigest()
  138. As you can see above, the class constructor or initiation method ( __init__()) above takes the following parameters:
  139. self — just like any other Python class, this parameter is used to refer to the class itself. Any variable associated with the class can be accessed using it.
  140. index — it’s used to track the position of a block within the blockchain.
  141. previous_hash — it used to reference the hash of the previous block within the blockchain.
  142. data—it gives details of the transactions done, for example, the amount bought.
  143. timestamp—it inserts a timestamp for all the transactions performed.
  144. The second method in the class, compute_hash , is used to produce the cryptographic hash of each block based on the above values.
  145. As you can see, we imported the SHA-256 algorithm into the cryptocurrency blockchain project to help in getting the hashes of the blocks.
  146. Once the values have been placed inside the hashing module, the algorithm will return a 256-bit string denoting the contents of the block.
  147. So, this is what gives the blockchain immutability. Since each block will be represented by a hash, which will be computed from the hash of the previous block, corrupting any block in the chain will make the other blocks have invalid hashes, resulting in breakage of the whole blockchain network.
  148. Building the Chain
  149. The whole concept of a blockchain is based on the fact that the blocks are “chained” to each other. Now, we’ll create a blockchain class that will play the critical role of managing the entire chain.
  150. It will keep the transactions data and include other helper methods for completing various roles, such as adding new blocks.
  151. Let’s talk about the helper methods.
  152. Adding the Constructor Method
  153. Here is the code:
  154. 1
  155. class BlockChain(object):
  156. 2
  157. 3
  158. def __init__(self):
  159. 4
  160. 5
  161. self.chain = []
  162. 6
  163. 7
  164. self.current_data = []
  165. 8
  166. 9
  167. self.nodes = set()
  168. 10
  169. 11
  170. self.build_genesis()
  171. The __init__() constructor method is what instantiates the blockchain.
  172. Here are the roles of its attributes:
  173. self.chain — this variable stores all the blocks.
  174. self.current_data — this variable stores information about the transactions in the block.
  175. self.build_genesis() — this method is used to create the initial block in the chain.
  176. Building the Genesis Block
  177. The build_genesis() method is used for creating the initial block in the chain, that is, a block without any predecessors. The genesis block is what represents the beginning of the blockchain.
  178. To create it, we’ll call the build_block() method and give it some default values. The parameters proof_number and previous_hash are both given a value of zero, though you can give them any value you desire.
  179. Here is the code:
  180. 1
  181. def build_genesis(self):
  182. 2
  183. 3
  184. self.build_block(proof_number=0, previous_hash=0)
  185. 4
  186. 5
  187. def build_block(self, proof_number, previous_hash):
  188. 6
  189. 7
  190. block = Block(
  191. 8
  192. 9
  193. index=len(self.chain),
  194. 10
  195. 11
  196. proof_number=proof_number,
  197. 12
  198. 13
  199. previous_hash=previous_hash,
  200. 14
  201. 15
  202. data=self.current_data
  203. 16
  204. 17
  205. )
  206. 18
  207. 19
  208. self.current_data = []
  209. 20
  210. 21
  211. self.chain.append(block)
  212. 22
  213. 23
  214. return block
  215. Confirming Validity of the Blockchain
  216. The confirm_validity method is critical in examining the integrity of the blockchain and making sure inconsistencies are lacking.
  217. As explained earlier, hashes are pivotal for realizing the security of the cryptocurrency blockchain, because any slight alteration in an object will result in the creation of an entirely different hash.
  218. Thus, the confirm_validity method utilizes a series of if statements to assess whether the hash of each block has been compromised.
  219. Furthermore, it also compares the hash values of every two successive blocks to identify any anomalies. If the chain is working properly, it returns true; otherwise, it returns false.
  220. Here is the code:
  221. 1
  222. def confirm_validity(block, previous_block):
  223. 2
  224. 3
  225. if previous_block.index + 1 != block.index:
  226. 4
  227. 5
  228. return False
  229. 6
  230. 7
  231. elif previous_block.compute_hash != block.previous_hash:
  232. 8
  233. 9
  234. return False
  235. 10
  236. 11
  237. elif block.timestamp <= previous_block.timestamp:
  238. 12
  239. 13
  240. return False
  241. 14
  242. 15
  243. return True
  244. Declaring Data of Transactions
  245. The get_data method is important in declaring the data of transactions on a block. This method takes three parameters (sender’s information, receiver’s information, and amount) and adds the transaction data to the self.current_data list.
  246. Here is the code:
  247. 1
  248. def get_data(self, sender, receiver, amount):
  249. 2
  250. 3
  251. self.current_data.append({
  252. 4
  253. 5
  254. 'sender': sender,
  255. 6
  256. 7
  257. 'receiver': receiver,
  258. 8
  259. 9
  260. 'amount': amount
  261. 10
  262. 11
  263. })
  264. 12
  265. 13
  266. return True
  267. Effecting the Proof of Work
  268. In blockchain technology, Proof of Work (PoW) refers to the complexity involved in mining or generating new blocks on the blockchain.
  269. For example, the PoW can be implemented by identifying a number that solves a problem whenever a user completes some computing work. Anyone on the blockchain network should find the number complex to identify but easy to verify — this is the main concept of PoW.
  270. This way, it discourages spamming and compromising the integrity of the network.
  271. In this article, we’ll illustrate how to include a Proof of Work algorithm in a blockchain cryptocurrency project.
  272. Finalizing With the Last Block
  273. Finally, the latest_block() helper method is used for retrieving the last block on the network, which is actually the current block.
  274. Here is the code:
  275. 1
  276. def latest_block(self):
  277. 2
  278. 3
  279. return self.chain[-1]
  280. Implementing Blockchain Mining
  281. Now, this is the most exciting section!
  282. Initially, the transactions are kept in a list of unverified transactions. Mining refers to the process of placing the unverified transactions in a block and solving the PoW problem. It can be referred to as the computing work involved in verifying the transactions.
  283. If everything has been figured out correctly, a block is created or mined and joined together with the others in the blockchain. If users have successfully mined a block, they are often rewarded for using their computing resources to solve the PoW problem.
  284. Here is the mining method in this simple cryptocurrency blockchain project:
  285. 1
  286. def block_mining(self, details_miner):
  287. 2
  288. 3
  289. self.get_data(
  290. 4
  291. 5
  292. sender="0", #it implies that this node has created a new block
  293. 6
  294. 7
  295. receiver=details_miner,
  296. 8
  297. 9
  298. quantity=1, #creating a new block (or identifying the proof number) is awarded with 1
  299. 10
  300. 11
  301. )
  302. 12
  303. 13
  304. last_block = self.latest_block
  305. 14
  306. 15
  307. last_proof_number = last_block.proof_number
  308. 16
  309. 17
  310. proof_number = self.proof_of_work(last_proof_number)
  311. 18
  312. 19
  313. 20
  314. 21
  315. last_hash = last_block.compute_hash
  316. 22
  317. 23
  318. block = self.build_block(proof_number, last_hash)
  319. 24
  320. 25
  321. 26
  322. 27
  323. return vars(block)
  324. 28
  325. 29
  326. Summary
  327. Here is the whole code for our crypto blockchain class in Python:
  328. 1
  329. import hashlib
  330. 2
  331. 3
  332. import time
  333. 4
  334. 5
  335. class Block(object):
  336. 6
  337. 7
  338. def __init__(self, index, proof_number, previous_hash, data, timestamp=None):
  339. 8
  340. 9
  341. self.index = index
  342. 10
  343. 11
  344. self.proof_number = proof_number
  345. 12
  346. 13
  347. self.previous_hash = previous_hash
  348. 14
  349. 15
  350. self.data = data
  351. 16
  352. 17
  353. self.timestamp = timestamp or time.time()
  354. 18
  355. 19
  356. @property
  357. 20
  358. 21
  359. def compute_hash(self):
  360. 22
  361. 23
  362. string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
  363. 24
  364. 25
  365. return hashlib.sha256(string_block.encode()).hexdigest()
  366. 26
  367. 27
  368. def __repr__(self):
  369. 28
  370. 29
  371. return "{} - {} - {} - {} - {}".format(self.index, self.proof_number, self.previous_hash, self.data, self.timestamp)
  372. 30
  373. 31
  374. class BlockChain(object):
  375. 32
  376. 33
  377. def __init__(self):
  378. 34
  379. 35
  380. self.chain = []
  381. 36
  382. 37
  383. self.current_data = []
  384. 38
  385. 39
  386. self.nodes = set()
  387. 40
  388. 41
  389. self.build_genesis()
  390. 42
  391. 43
  392. def build_genesis(self):
  393. 44
  394. 45
  395. self.build_block(proof_number=0, previous_hash=0)
  396. 46
  397. 47
  398. def build_block(self, proof_number, previous_hash):
  399. 48
  400. 49
  401. block = Block(
  402. 50
  403. 51
  404. index=len(self.chain),
  405. 52
  406. 53
  407. proof_number=proof_number,
  408. 54
  409. 55
  410. previous_hash=previous_hash,
  411. 56
  412. 57
  413. data=self.current_data
  414. 58
  415. 59
  416. )
  417. 60
  418. 61
  419. self.current_data = []
  420. 62
  421. 63
  422. self.chain.append(block)
  423. 64
  424. 65
  425. return block
  426. 66
  427. 67
  428. @staticmethod
  429. 68
  430. 69
  431. def confirm_validity(block, previous_block):
  432. 70
  433. 71
  434. if previous_block.index + 1 != block.index:
  435. 72
  436. 73
  437. return False
  438. 74
  439. 75
  440. elif previous_block.compute_hash != block.previous_hash:
  441. 76
  442. 77
  443. return False
  444. 78
  445. 79
  446. elif block.timestamp <= previous_block.timestamp:
  447. 80
  448. 81
  449. return False
  450. 82
  451. 83
  452. return True
  453. 84
  454. 85
  455. def get_data(self, sender, receiver, amount):
  456. 86
  457. 87
  458. self.current_data.append({
  459. 88
  460. 89
  461. 'sender': sender,
  462. 90
  463. 91
  464. 'receiver': receiver,
  465. 92
  466. 93
  467. 'amount': amount
  468. 94
  469. 95
  470. })
  471. 96
  472. 97
  473. return True
  474. 98
  475. 99
  476. @staticmethod
  477. 100
  478. 101
  479. def proof_of_work(last_proof):
  480. 102
  481. 103
  482. pass
  483. 104
  484. 105
  485. @property
  486. 106
  487. 107
  488. def latest_block(self):
  489. 108
  490. 109
  491. return self.chain[-1]
  492. 110
  493. 111
  494. def chain_validity(self):
  495. 112
  496. 113
  497. pass
  498. 114
  499. 115
  500. def block_mining(self, details_miner):
  501. 116
  502. 117
  503. self.get_data(
  504. 118
  505. 119
  506. sender="0", #it implies that this node has created a new block
  507. 120
  508. 121
  509. receiver=details_miner,
  510. 122
  511. 123
  512. quantity=1, #creating a new block (or identifying the proof number) is awared with 1
  513. 124
  514. 125
  515. )
  516. 126
  517. 127
  518. last_block = self.latest_block
  519. 128
  520. 129
  521. last_proof_number = last_block.proof_number
  522. 130
  523. 131
  524. proof_number = self.proof_of_work(last_proof_number)
  525. 132
  526. 133
  527. last_hash = last_block.compute_hash
  528. 134
  529. 135
  530. block = self.build_block(proof_number, last_hash)
  531. 136
  532. 137
  533. return vars(block)
  534. 138
  535. 139
  536. def create_node(self, address):
  537. 140
  538. 141
  539. self.nodes.add(address)
  540. 142
  541. 143
  542. return True
  543. 144
  544. 145
  545. @staticmethod
  546. 146
  547. 147
  548. def get_block_object(block_data):
  549. 148
  550. 149
  551. return Block(
  552. 150
  553. 151
  554. block_data['index'],
  555. 152
  556. 153
  557. block_data['proof_number'],
  558. 154
  559. 155
  560. block_data['previous_hash'],
  561. 156
  562. 157
  563. block_data['data'],
  564. 158
  565. 159
  566. timestamp=block_data['timestamp']
  567. 160
  568. 161
  569. )
  570. 162
  571. 163
  572. blockchain = BlockChain()
  573. 164
  574. 165
  575. print("GET READY MINING ABOUT TO START")
  576. 166
  577. 167
  578. print(blockchain.chain)
  579. 168
  580. 169
  581. last_block = blockchain.latest_block
  582. 170
  583. 171
  584. last_proof_number = last_block.proof_number
  585. 172
  586. 173
  587. proof_number = blockchain.proof_of_work(last_proof_number)
  588. 174
  589. 175
  590. blockchain.get_data(
  591. 176
  592. 177
  593. sender="0", #this means that this node has constructed another block
  594. 178
  595. 179
  596. receiver="LiveEdu.tv",
  597. 180
  598. 181
  599. amount=1, #building a new block (or figuring out the proof number) is awarded with 1
  600. 182
  601. 183
  602. )
  603. 184
  604. 185
  605. last_hash = last_block.compute_hash
  606. 186
  607. 187
  608. block = blockchain.build_block(proof_number, last_hash)
  609. 188
  610. 189
  611. print("WOW, MINING HAS BEEN SUCCESSFUL!")
  612. 190
  613. 191
  614. print(blockchain.chain)
  615. Now, let’s try to run our code to see if we can generate some digital coins...

comments powered by Disqus