{"id":16774359,"url":"https://github.com/rahulraikwar00/blockchain1","last_synced_at":"2025-04-10T20:07:07.113Z","repository":{"id":45303080,"uuid":"414087695","full_name":"rahulraikwar00/Blockchain1","owner":"rahulraikwar00","description":"The goal of this project is to explain and to make clearer how is a blockchain structured at the very core. It's not built with the intention to replicate an advanced blockchain like Bitcoin or Ethereum","archived":false,"fork":false,"pushed_at":"2021-12-23T01:57:16.000Z","size":47,"stargazers_count":4,"open_issues_count":1,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-24T17:52:40.721Z","etag":null,"topics":["blockchain","falsk","python"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rahulraikwar00.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-10-06T05:59:35.000Z","updated_at":"2023-08-03T12:06:47.000Z","dependencies_parsed_at":"2022-07-14T16:00:49.966Z","dependency_job_id":null,"html_url":"https://github.com/rahulraikwar00/Blockchain1","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rahulraikwar00%2FBlockchain1","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rahulraikwar00%2FBlockchain1/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rahulraikwar00%2FBlockchain1/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rahulraikwar00%2FBlockchain1/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rahulraikwar00","download_url":"https://codeload.github.com/rahulraikwar00/Blockchain1/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248288345,"owners_count":21078903,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["blockchain","falsk","python"],"created_at":"2024-10-13T06:48:53.789Z","updated_at":"2025-04-10T20:07:07.081Z","avatar_url":"https://github.com/rahulraikwar00.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ``TESTCOIN``\n## Python implementation of a blockchain.\n\n![](https://img.shields.io/github/issues/rahulraikwar00/Blockchain1) ![](https://img.shields.io/github/stars/rahulraikwar00/Blockchain1) ![](https://img.shields.io/github/forks/rahulraikwar00/Blockchain1)\n![](https://img.shields.io/github/license/rahulraikwar00/Blockchain1)\n![](https://img.shields.io/twitter/url?label=Rahul%20Raikwar\u0026style=social\u0026url=https%3A%2F%2Ftwitter.com%2Frahulraikwar00)\n\n![img](https://i.imgur.com/RBkR1Z3.png)\n\n## Description\n\nThe Testcoin implementation is focused almost exclusively in the hashed ledger feature. It does include some advanced feature like a distributed nodes and a consensus protocol via proof of work. which is just a simple function not a complex algorithm.\n\nThe goal of this project is to explain and to make clearer how is a blockchain structured at the very core. It's not built with the intention to replicate an advanced blockchain like Bitcoin or Ethereum.\n\n### Before you get started..\n\nRemember that a Blockchain is an immutable, sequential chain of records called Blocks. They can contain transactions, files or any data you like, really. But the important thing is that they’re chained together using hashes.\n\n### What is needed?\n\nMake sure that you have Python 3.6+ installed (along with pip) and you will also need Flask and Requests library.\n\n```sh\n$ pip3 install -r requirements\n```\n\nYou will also need an HTTP client like Postman or curl. But anything will do.\n\n# Step 1: Building a Blockchain\n\nSo what does a block look like?\n\nEach block has an index, timestamp, transactions, proof (more on that later) and a hash of the previous transaction.\n\nHere is an example of what a single Block looks like:\n\n\n# MYCODE\n```python\n```\n\n### Represenging a Blockchain\n\nWe'll create a Blockchain class whose constructor creates a list to store our Blockchain and another to store transactions.  Here is how the Class will look like:\n\n```python\nclass BlockChain(object):\n    def __init__(self):\n        self.chain = []\n        self.current_transactions = []\n\n    @staticmethod\n    def hash(block):\n        pass\n\n    def new_block(self):\n        pass\n\n    @property\n    def last_block(self):\n        return self.chain[-1]\n```\nThis Blockchain class is responsible for managing the chain. It will store transactions and have helper functions.\n\nThe new_block method will create a new block and adds it on the chain and returns the last block in the chain.\n\nThe last_block method will return the last block in the chain.\n\nEach block contains the hash and the hash of the previous block. This is what gives blockchains it's immutability - i.e. if anyone attack this, all subsequent blocks will be corrupt.\n\nIt's the core idea of blockchains. :)\n\n\n### Adding transactions to the block\n\nWe will need some way of adding transactions to the block.\n#MYCODE\n```python\n\n```\n\nThe new_transaction returns index of the block which will be added to current_transactions and is next one to be mined..\n\n### Creating new blocks\n\nIn addition to creating the genesis block in our constructor, we will also need to flesh out methods for the new_block(), add_new_transaction() and hash().\n\n#MYCODE\n```python\n\n```\n\nOnce our block is initiated, we need to feed it with the genesis block (a block with no predecessors). We will also need to add \"a proof of work\" to our genesis block which is the result of mining.\n\nAt this point, we're nearly done representing our Blockchain.\n\nSo lets talk about how the new blocks are created, forged and mined. :)\n\n\n### Understanding Proof of Work\n\nA proof of work algorithm are how new Blocks are created or mined on the Blockchain.\n\nThe goal is to discover a number that solves a problem.\n\nThe number must be difficult and resources consuming to find but super quick and easy to verify.\n\nThis is the core idea of Proof of Work.  :)\n\n\nSo lets work out some stupid-shit math problem that we are going to require to be solved in order for a block to be mined.\n\nLets say that hash of some integer ```x``` multiplied by another ```y``` must always end in 0.  So, as an example, the ```hash(x * y) = 4b4f4b4f54...0```.\n\n#MYCODE\n```python\n\n```\n\nIn the Bitcoin world, the Proof of Work algorithm is called Hashcash. And it's not any different from the example above.  It's the very algorithm that miners race to solve in order to create a new block.  The difficulty is of course determined by the number of the characters searched for in the string. In our example we simplified it by defining that the resultant hash must end in 0 to make the whole thing in our case quicker and less resource intensive but this is how it works really.\n\nThe miners are rewarded for finding a solution by receiving a coin. In a transaction. There are many opinions on effectiness of this but this is how it works. And it really is that simple and this way the network is able to easily verify their solution. :)\n\n** Editor's note: 4b-4f-4b-4f-54 in the example above in hex translates to = \"kokot\" lol. :D\n\n\n### Implementing Proof of Work\n\nLet's implement a similar algorithm for our Blockchain. Our rule will be similar to the example above.\n\n\"Find a number p that when hashed with the previous block's solution a hash with 4 leading 0 is produced.\"\n\n#MYCODE\n```python\n\n```\n\nTo adjust the difficulty of the algorithm, we could modify the number of leading zeors.  But strictly speaking 4 is sufficient enough.  Also, you may find out that adding an extra 0 makes a mammoth difference to the time required to find a solution.\n\nNow, our Blockchain class is pretty much complete, let's begin to interact with the ledger using the HTTP requests.\n\n\n# Step 2: Blockchain as an API\n\nWe'll use Python Flask framework.  It's a micro-framework and it's really easy to use so for our example it'll do nicely.\n\nWe'll create three simple API endpoints:\n\n  - /transactions/new to create a new transaction block\n  - /mine to tell our service to mine a new block\n  - /chain to return the full Blockchain\n\n### Setting up Flask\n\nOur server will form a single node in our Blockchain.  So let's create some code.\n#MYCODE\n```python\n\n```\n\n### The transaction endpoint\n\nThis is what the request for the transaction will look like. It's what the user will send to the server.\n\n```json\n{\n    \"sender\": \"sender_address\",\n    \"recipient\": \"recipient_address\",\n    \"amount\": 100\n}\n```\n\nSince we already have the method for adding transactions to a block, the rest is easy and pretty straight forward.\n\n```python\nimport hashlib\nimport json\n\nfrom time import time\nfrom uulib import uulib4\nfrom flask import Flask, jsonify, request\n\n...\n\n@app.route('/transactions/new', methods=['POST'])\ndef new_transaction():\n\n    values = request.get_json()\n    required = ['sender', 'recipient', 'amount']\n\n    if not all(k in values for k in required):\n        return 'Missing values', 400\n\n    # create a new transaction\n    index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])\n    response = {'message': f'Transaction will be added to the Block {index}.'}\n\n    return jsonify(response, 200)\n```\n\n### The mining endpoint\n\nOur mining endpoint is where the mining happens and it's actually very easy as all it has to do are three things:\n\n1) Calculate proof of work\n\n2) Reward the miner by adding a transaction granting miner 1 coin\n\n3) Forge the new Block by adding it to the chain\n\n\nSo, let's add on the mining function on our API:\n\n```python\nimport hashlib\nimport json\n\nfrom time import time\nfrom uulib import uulib4\nfrom flask import Flask, jsonify, request\n\n...\n\n@app.route('/mine', methods=['GET'])\ndef mine():\n\n    # first we have to run the proof of work algorithm to calculate the new proof..\n    last_block = blockchain.last_block\n    last_proof = last_block['proof']\n    proof = blockchain.proof_of_work(last_proof)\n\n    # we must receive reward for finding the proof\n    blockchain.new_transaction(\n        sender=0,\n        recipient=node_identifier,\n        amount=1,\n    )\n\n    # forge the new block by adding it to the chain\n    previous_hash = blockchain.hash(last_block)\n    block = blockchain.new_block(proof, previous_hash)\n\n    response = {\n        'message': \"Forged new block.\",\n        'index': block['index'],\n        'transactions': block['transaction'],\n        'proof': block['proof'],\n        'previous_hash': block['previous_hash'],\n    }\n    return jsonify(response), 200\n```\n\nAt this point, we are done, and we can start interacting with out blockchain.  :)\n\n\n# Step 3: Interacting with our Blockchain\n\nYou can use a plain old cURL or Postman to interact with our Blockchain API ovet the network.\n\nFire up the server:\n\n```\n$ python3 blockchain.py\n* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)\n\n```\n\nSo first off let's try mining a block by making a GET request to the \"mine\" http://localhost:5000/mine:\n\n```json\n[\n  {\n    \"index\": 1, \n    \"message\": \"Forged new block.\", \n    \"previous_hash\": \"7cd122100c9ded644768ccdec2d9433043968352e37d23526f63eefc65cd89e6\", \n    \"proof\": 35293, \n    \"transactions\": [\n      {\n        \"data\": 1, \n        \"recipient\": \"6a01861c7b3f483eab90727e621b2b96\", \n        \"sender\": 0\n      }\n    ]\n  }, \n  200\n]\n```\n\nMotherfucker, very good! :)\n\nNow lets create a new transaction by making a POST request to http://localhost:5000/transaction/new with a body containing our transaction structure. Let's make this call using the cURL:\n\n```\n$ curl -X POST -H \"Content-Type: application/json\" -d '{\n \"sender\": \"d4ee26eee15148ee92c6cd394edd974e\",\n \"recipient\": \"recipient-address\",\n \"amount\": 5\n}' \"http://localhost:5000/transactions/new\"\n```\n\nI have restarted the server, mined two blocks, to give 3 in total.  So let's inspect the full chain by requesting http://localhost:5000/chain:\n\n```json\n{\n  \"chain\": [\n    {\n      \"index\": 1,\n      \"previous_hash\": 1,\n      \"proof\": 100,\n      \"timestamp\": 1506280650.770839,\n      \"transactions\": []\n    },\n    {\n      \"index\": 2,\n      \"previous_hash\": \"c099bc...bfb7\",\n      \"proof\": 35293,\n      \"timestamp\": 1506280664.717925,\n      \"transactions\": [\n        {\n          \"amount\": 1,\n          \"recipient\": \"8bbcb347e0631231...e152b\",\n          \"sender\": \"0\"\n        }\n      ]\n    },\n    {\n      \"index\": 3,\n      \"previous_hash\": \"eff91a...10f2\",\n      \"proof\": 35089,\n      \"timestamp\": 1506280666.1086972,\n      \"transactions\": [\n        {\n          \"amount\": 1,\n          \"recipient\": \"9e2e234e12e0631231...e152b\",\n          \"sender\": \"0\"\n        }\n      ]\n    }\n  ],\n  \"length\": 3\n}\n```\n\n## Contribute\nHey there! New ideas are welcome: open/close issues, fork the repo and share your code with a Pull Request.\n\nClone this project to your computer:\n\n```bash\n$ git clone https://github.com/rahulraiwkar00/blockchain1\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frahulraikwar00%2Fblockchain1","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frahulraikwar00%2Fblockchain1","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frahulraikwar00%2Fblockchain1/lists"}