{"id":219,"date":"2015-05-18T19:04:00","date_gmt":"2015-05-18T19:04:00","guid":{"rendered":"https:\/\/santiagomarquezsolis.com\/index.php\/2026\/04\/20\/building-a-basic-blockchain-in-python-part-1\/"},"modified":"2026-04-20T16:12:41","modified_gmt":"2026-04-20T16:12:41","slug":"building-a-basic-blockchain-in-python-part-1","status":"publish","type":"post","link":"https:\/\/santiagomarquezsolis.com\/index.php\/en\/2015\/05\/18\/building-a-basic-blockchain-in-python-part-1\/","title":{"rendered":"Building a Basic Blockchain in Python. Part 1."},"content":{"rendered":"<p>One of the best ways to understand how blockchain technology works is to build one yourself. In this first part of a two-part series, we&#8217;ll build a simple blockchain from scratch in Python. By the end, you&#8217;ll have a solid understanding of the core concepts that make blockchain technology work.<\/p>\n<h2>What We&#8217;ll Build<\/h2>\n<p>Our simple blockchain will include:<\/p>\n<ul>\n<li>A Block class to represent each block<\/li>\n<li>A Blockchain class to manage the chain<\/li>\n<li>Cryptographic hashing using SHA-256<\/li>\n<li>A proof-of-work mechanism<\/li>\n<li>Chain validation<\/li>\n<\/ul>\n<h2>Understanding the Basics<\/h2>\n<p>A blockchain is, at its core, a linked list of blocks where each block contains data and a cryptographic hash that includes the hash of the previous block. This creates an unbreakable chain \u2014 modifying any block invalidates all subsequent blocks.<\/p>\n<h2>Setting Up the Environment<\/h2>\n<p>You&#8217;ll need Python 3.x and the <code>hashlib<\/code> module (included in Python&#8217;s standard library).<\/p>\n<h2>The Block Class<\/h2>\n<pre><code>import hashlib\r\nimport json\r\nfrom datetime import datetime\r\n\r\nclass Block:\r\n    def __init__(self, index, data, previous_hash):\r\n        self.index = index\r\n        self.timestamp = datetime.now().isoformat()\r\n        self.data = data\r\n        self.previous_hash = previous_hash\r\n        self.hash = self.calculate_hash()\r\n    \r\n    def calculate_hash(self):\r\n        block_string = json.dumps({\r\n            'index': self.index,\r\n            'timestamp': self.timestamp,\r\n            'data': self.data,\r\n            'previous_hash': self.previous_hash\r\n        }, sort_keys=True)\r\n        return hashlib.sha256(block_string.encode()).hexdigest()\r\n    \r\n    def __repr__(self):\r\n        return f\"Block(index={self.index}, hash={self.hash[:10]}...)\"<\/code><\/pre>\n<p>Let&#8217;s break down what each part does:<\/p>\n<ul>\n<li><code>index<\/code>: Position of the block in the chain<\/li>\n<li><code>timestamp<\/code>: When the block was created<\/li>\n<li><code>data<\/code>: The actual content of the block (transactions, etc.)<\/li>\n<li><code>previous_hash<\/code>: Hash of the previous block \u2014 this is what creates the \u00abchain\u00bb<\/li>\n<li><code>hash<\/code>: The block&#8217;s own hash, calculated from all other fields<\/li>\n<\/ul>\n<h2>The Blockchain Class<\/h2>\n<pre><code>class Blockchain:\r\n    def __init__(self):\r\n        self.chain = [self.create_genesis_block()]\r\n    \r\n    def create_genesis_block(self):\r\n        return Block(0, \"Genesis Block\", \"0\")\r\n    \r\n    @property\r\n    def last_block(self):\r\n        return self.chain[-1]\r\n    \r\n    def add_block(self, data):\r\n        new_block = Block(\r\n            index=len(self.chain),\r\n            data=data,\r\n            previous_hash=self.last_block.hash\r\n        )\r\n        self.chain.append(new_block)\r\n        return new_block\r\n    \r\n    def is_valid(self):\r\n        for i in range(1, len(self.chain)):\r\n            current = self.chain[i]\r\n            previous = self.chain[i-1]\r\n            \r\n            # Check if hash is correct\r\n            if current.hash != current.calculate_hash():\r\n                return False\r\n            \r\n            # Check if chain is properly linked\r\n            if current.previous_hash != previous.hash:\r\n                return False\r\n        \r\n        return True<\/code><\/pre>\n<h2>Testing Our Blockchain<\/h2>\n<pre><code># Create a blockchain\r\nblockchain = Blockchain()\r\n\r\n# Add some blocks\r\nblockchain.add_block({\"from\": \"Alice\", \"to\": \"Bob\", \"amount\": 50})\r\nblockchain.add_block({\"from\": \"Bob\", \"to\": \"Charlie\", \"amount\": 25})\r\nblockchain.add_block({\"from\": \"Charlie\", \"to\": \"Alice\", \"amount\": 10})\r\n\r\n# Print the chain\r\nfor block in blockchain.chain:\r\n    print(f\"Block {block.index}: {block.hash[:20]}...\")\r\n\r\n# Validate\r\nprint(f\"Is valid: {blockchain.is_valid()}\")\r\n\r\n# Try to tamper with the chain\r\nblockchain.chain[1].data = {\"from\": \"Alice\", \"to\": \"Bob\", \"amount\": 9999}\r\nprint(f\"After tampering - Is valid: {blockchain.is_valid()}\")<\/code><\/pre>\n<h2>What This Demonstrates<\/h2>\n<p>When you run this code, you&#8217;ll see that:<\/p>\n<ol>\n<li>Each block has a unique hash based on its contents<\/li>\n<li>Changing any block&#8217;s data changes its hash<\/li>\n<li>This breaks the chain because the next block&#8217;s <code>previous_hash<\/code> no longer matches<\/li>\n<li>The <code>is_valid()<\/code> method detects this tampering<\/li>\n<\/ol>\n<p>This is the fundamental security property of blockchain: <strong>you can&#8217;t change historical data without detection<\/strong>.<\/p>\n<h2>Next Steps<\/h2>\n<p>In Part 2, we&#8217;ll add a proof-of-work mechanism (mining), making our blockchain resistant to easy modification. We&#8217;ll also look at how multiple nodes can maintain consensus on the same chain.<\/p>\n<p>Stay tuned, and feel free to experiment with the code above!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>One of the best ways to understand how blockchain technology works is to build one yourself. In this first part of a two-part series, we&#8217;ll build a simple blockchain from scratch in Python. By the end, you&#8217;ll have a solid understanding of the core concepts that make blockchain technology work. What We&#8217;ll Build Our simple [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[180,162,182],"tags":[184,186,266],"class_list":["post-219","post","type-post","status-publish","format-standard","hentry","category-blockchain-en","category-blog-en","category-cripto-en","tag-blockchain-en","tag-cripto-en","tag-python-en"],"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/santiagomarquezsolis.com\/index.php\/wp-json\/wp\/v2\/posts\/219","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/santiagomarquezsolis.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/santiagomarquezsolis.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/santiagomarquezsolis.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/santiagomarquezsolis.com\/index.php\/wp-json\/wp\/v2\/comments?post=219"}],"version-history":[{"count":1,"href":"https:\/\/santiagomarquezsolis.com\/index.php\/wp-json\/wp\/v2\/posts\/219\/revisions"}],"predecessor-version":[{"id":245,"href":"https:\/\/santiagomarquezsolis.com\/index.php\/wp-json\/wp\/v2\/posts\/219\/revisions\/245"}],"wp:attachment":[{"href":"https:\/\/santiagomarquezsolis.com\/index.php\/wp-json\/wp\/v2\/media?parent=219"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/santiagomarquezsolis.com\/index.php\/wp-json\/wp\/v2\/categories?post=219"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/santiagomarquezsolis.com\/index.php\/wp-json\/wp\/v2\/tags?post=219"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}