Skip to content

Commit

Permalink
blockchain v0.2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
smartlegionlab committed Oct 29, 2024
1 parent 64a5ad6 commit 7477fee
Show file tree
Hide file tree
Showing 5 changed files with 318 additions and 53 deletions.
39 changes: 34 additions & 5 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
Expand Down Expand Up @@ -50,6 +49,7 @@ coverage.xml
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
Expand All @@ -72,6 +72,7 @@ instance/
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
Expand All @@ -82,7 +83,9 @@ profile_default/
ipython_config.py

# pyenv
.python-version
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
Expand All @@ -91,7 +94,22 @@ ipython_config.py
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
Expand Down Expand Up @@ -127,5 +145,16 @@ dmypy.json

# Pyre type checker
.pyre/
.idea
.idea/*

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/
167 changes: 164 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,184 @@
# BlockChain
# Blockchain in Python

***
---

This project is an implementation of a blockchain in Python,
which includes core features such as block creation, transaction processing, and a consensus algorithm.
It consists of two modules: one implements the blockchain using Flask to create an API,
while the other represents a simpler implementation of the blockchain using classes.

---

> Warning! This is a fairly old version that I moved to my historical repository and may continue to develop.
> So this version is still in development and research phase.
## Modules:

### 1. Flask Blockchain

This module creates a blockchain using Flask, allowing you to interact with it via HTTP requests. Key features include:

- **Creating a new block**: The `/mine` method runs the proof-of-work algorithm and creates a new block.
- **Creating a new transaction**: The `/transactions/new` method allows you to add new transactions to the blockchain.
- **Getting the full chain of blocks**: The `/chain` method returns the current chain of blocks and its length.
- **Registering new nodes**: The `/nodes/register` method allows you to add new nodes to the network.
- **Consensus algorithm**: The `/nodes/resolve` method checks and resolves conflicts in the chain of blocks.

### 2. Simple Blockchain Implementation

This module implements the basic structure of a blockchain with the `Block` and `Blockchain` classes.
The main functions include:

- **Creating a genesis block**: The `create_genesis_block` method creates the first block in the chain.
- **Adding a new block**: The `add_block` method adds a new block to the chain, setting the correct hash of the previous block.

---

- `pip install -r requirements.txt`


- `python3 blockchain.py`
- `python blockchain.py`


- `curl http://localhost:5000/mine`

```json
{
"index": 2,
"message": "New Block Forged",
"previous_hash": "5d9d222c768d6c501ae28670a7333e0ae39c14d7884650bf12cf32d3961e2682",
"proof": 35293,
"transactions": [
{
"amount": 1,
"recipient": "902a4bd96aa44abcb0d9a097bd78c462",
"sender": "0"
}
]
}

```

- `curl http://localhost:5000/mine`

```json
{
"index": 3,
"message": "New Block Forged",
"previous_hash": "c67d3b156c5c3db264331196bb48efb5e6fa0fcfb31f98cf663e38d69089ffb4",
"proof": 35089,
"transactions": [
{
"amount": 1,
"recipient": "902a4bd96aa44abcb0d9a097bd78c462",
"sender": "0"
}
]
}

```


- `curl http://localhost:5000/chain`

```json
{
"chain": [
{
"index": 1,
"previous_hash": 1,
"proof": 100,
"timestamp": 1730220820.929162,
"transactions": []
},
{
"index": 2,
"previous_hash": "5d9d222c768d6c501ae28670a7333e0ae39c14d7884650bf12cf32d3961e2682",
"proof": 35293,
"timestamp": 1730220836.4981325,
"transactions": [
{
"amount": 1,
"recipient": "902a4bd96aa44abcb0d9a097bd78c462",
"sender": "0"
}
]
},
{
"index": 3,
"previous_hash": "c67d3b156c5c3db264331196bb48efb5e6fa0fcfb31f98cf663e38d69089ffb4",
"proof": 35089,
"timestamp": 1730220846.5631032,
"transactions": [
{
"amount": 1,
"recipient": "902a4bd96aa44abcb0d9a097bd78c462",
"sender": "0"
}
]
}
],
"length": 3
}

```


- `curl -X POST -H "Content-Type: application/json" -d '{
"sender": "d4ee26eee15148ee92c6cd394edd974e",
"recipient": "someone-other-address",
"amount": 5
}' "http://localhost:5000/transactions/new"`

```json
{
"message": "Transaction will be added to Block 4"
}

```

- `python blockchain_base.py`

```text
Index: 0
Timestamp: 2024-10-30 00:01:20.180414
Data: Genesis Block
Previous Hash: 0
Hash: 02a478085aca11b94a6ea0b5c2cfe9df56dffbe5153df269f3609faa19fc5641
Index: 1
Timestamp: 2024-10-30 00:01:20.180433
Data: Transaction Data
Previous Hash: 02a478085aca11b94a6ea0b5c2cfe9df56dffbe5153df269f3609faa19fc5641
Hash: 3a7bc11cc8e213468fc25b6708b39e41780d5673ffffb995bbfdaa909d37b73e
Index: 2
Timestamp: 2024-10-30 00:01:20.180441
Data: Another Transaction
Previous Hash: 3a7bc11cc8e213468fc25b6708b39e41780d5673ffffb995bbfdaa909d37b73e
Hash: 477333623f8b9819e23412dfda01aee127d63a2744b32515cc2d0678fcf7fac1
```

***

Author and developer: ___A.A. Suvorov.___

***

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

***

Licensed under the terms of the BSD 3-Clause License
(see LICENSE for details).
Copyright © 2018-2024, A.A. Suvorov
All rights reserved.
59 changes: 59 additions & 0 deletions blockchain_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# --------------------------------------------------------
# Licensed under the terms of the BSD 3-Clause License
# (see LICENSE for details).
# Copyright © 2018-2024, A.A. Suvorov
# All rights reserved.
# --------------------------------------------------------
import datetime
import hashlib


class Block:
def __init__(self, index, timestamp, data, previous_hash):
self.index = index
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.hash = self.calculate_hash()

def calculate_hash(self):
return hashlib.sha256(
str(self.index).encode() +
str(self.timestamp).encode() +
str(self.data).encode() +
str(self.previous_hash).encode()
).hexdigest()


class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]

def create_genesis_block(self):
return Block(0, datetime.datetime.now(), "Genesis Block", "0")

def get_latest_block(self):
return self.chain[-1]

def add_block(self, new_block):
new_block.previous_hash = self.get_latest_block().hash
new_block.hash = new_block.calculate_hash()
self.chain.append(new_block)


def main():
my_blockchain = Blockchain()
my_blockchain.add_block(Block(1, datetime.datetime.now(), "Transaction Data", ""))
my_blockchain.add_block(Block(2, datetime.datetime.now(), "Another Transaction", ""))

for block in my_blockchain.chain:
print("Index:", block.index)
print("Timestamp:", block.timestamp)
print("Data:", block.data)
print("Previous Hash:", block.previous_hash)
print("Hash:", block.hash)
print()


if __name__ == '__main__':
main()
Loading

0 comments on commit 7477fee

Please sign in to comment.