liotbchain


Nameliotbchain JSON
Version 0.0.8 PyPI version JSON
download
home_pagehttps://github.com/sharhan-alhassan/liotbchain
SummaryPython Lightweight IOT Blockchain framework
upload_time2024-06-10 01:22:36
maintainerNone
docs_urlNone
authorSharhan Alhassan
requires_python>=3.6
licenseNone
keywords blockchain python iot framework
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # liotbchain
liotbchain is a lightweight, versatile blockchain framework designed for both IoT and non-IoT applications. It provides a robust and flexible solution for creating, managing, and interacting with blockchains, leveraging Python's simplicity and the efficiency of PostgreSQL for data storage. With configurable parameters for mining difficulty, transaction grouping, and proof-of-work limits, liotbchain adapts to various use cases, ensuring secure and efficient data management across distributed systems.

Disclaimer: liotbchain is not intended for real production environments but aims to leverage the core principles of blockchain technology for running a local, self-created blockchain. It is ideal for educational purposes, prototyping, and small-scale projects


# Installation
To install the liotbchain framework, use the following command:
```sh
pip install liotbchain
```

# Configuration
## Environment Variables
You can configure the liotbchain framework using environment variables:

### Option 1: Set environment variables
```sh
1. Export using the os utility
DATABASE_URL = os.getenv("DATABASE_URL", "default_db_url")

# Number of transactions to be grouped into a single block
# Default is 1 transaction per block
TRANSACTIONS_PER_BLOCK = int(os.getenv("TRANSACTIONS_PER_BLOCK", 1))

# Mining difficulty: the number of leading zeros required in the block hash
# Default is 4
# Warning: Setting a high value increases the time and computational resources needed for mining
DIFFICULTY = int(os.getenv("DIFFICULTY", 3))

# Nonce limit to prevent infinite loops during the mining process
# Default is 1000000
# Warning: Setting a very high value can lead to long mining times and excessive computational resource usage
NONCE_LIMIT = int(os.getenv("NONCE_LIMIT", 1000000))

2. Export variables directly to your working shell/terminal
# Set environment variables before running your script:
# Set the PostgreSQL database URL
export DATABASE_URL="postgresql://username:password@hostname:port/database_name"

# Set the number of transactions per block
export TRANSACTIONS_PER_BLOCK=2

# Set the mining difficulty
export DIFFICULTY=5

# Set the nonce limit to prevent infinite loops during mining
export NONCE_LIMIT=500000

3. Directly set the environment variables in a .env file
DATABASE_URL=
TRANSACTIONS_PER_BLOCK=
DIFFICULTY=
NONCE_LIMIT=

# Then instantiate the Blockchain() without passing any parameters
from liotbchain import Blockchain
blockchain = Blockchain()

```

### Option 2: Instantiate the Blockchain class with parameters:
```sh
from liotbchain import Blockchain

# Instantiate the Blockchain with custom parameters
blockchain = Blockchain(difficulty=5, nonce_limit=500000, db_url="postgresql://username:password@hostname:port/database_name", transactions_per_block=2)

```

# Usage
Adding Transactions and Mining Blocks
You can add transactions to the blockchain and mine blocks:
```py
# Add transactions
transaction1 = {"device": "Raspberry Pi 1", "distance": 120, "timestamp": time.time()}
transaction2 = {"device": "Raspberry Pi 2", "distance": 150, "timestamp": time.time()}
transaction3 = {"device": "Raspberry Pi 3", "distance": 130, "timestamp": time.time()}

blockchain.add_transaction(transaction1)
blockchain.add_transaction(transaction2)
blockchain.add_transaction(transaction3)

# Mine a block when the number of transactions reaches the configured limit
blockchain.mine_block()
```

# Displaying the Blockchain
You can display the entire blockchain:
```py
# Display the blockchain
for block in blockchain.get_chain():
    print(f"Block {block.index}: Transactions={block.data}, Nonce={block.nonce}, Hash={block.hash}, Merkle Root={block.merkle_root}")
```

# Validating the Blockchain
You can validate the integrity of the blockchain:
```py
if blockchain.is_chain_valid():
    print("The blockchain is valid.")
else:
    print("The blockchain is not valid.")
```

# API Reference
Block Class
The Block class represents a block in the blockchain.

## Attributes:
```sh
index (int): The block's index within the blockchain.
timestamp (float): The timestamp of when the block was created.
data (list): The transactions stored within the block.
previous_hash (str): The hash of the block's predecessor.
nonce (int): The nonce used for the proof-of-work.
hash (str): The hash of the block.
merkle_root (str): The Merkle root hash of the block's transactions.
```

## Methods:
```sh
calculate_hash() -> str: Calculates the SHA-256 hash of the block.
calculate_merkle_root() -> str: Calculates the Merkle root hash of the block's transactions.
```

## Blockchain Class
The Blockchain class implements the blockchain with proof-of-work mechanism.

Attributes:
```sh
chain (list): A list of blocks that form the blockchain.
difficulty (int): The number of leading zeros required in the hash.
transactions (list): A list to hold transactions temporarily until a block is created.
nonce_limit (int): The maximum limit for nonce to prevent infinite loops.
```

# Methods:
```sh
__init__(difficulty=None, nonce_limit=None, db_url=None, transactions_per_block=None): Initializes the blockchain with optional configuration parameters.
create_genesis_block(): Generates the genesis block and appends it to the blockchain.
initialize_blockchain(): Initializes the blockchain by creating the database and loading existing blocks from the database.
save_blockchain(): Saves the entire blockchain to the database.
add_block(block): Adds a new block to the blockchain after performing proof-of-work.
proof_of_work(block) -> str: Performs the proof of work to adjust the block's nonce until the hash meets the blockchain difficulty.
is_chain_valid() -> bool: Validates the blockchain's integrity by ensuring each block's link and proof-of-work are correct.
get_latest_block() -> Block: Retrieves the most recent block in the blockchain.
add_transaction(transaction): Adds a transaction to the temporary storage. When the number of transactions reaches the configured limit, a new block is mined and added to the blockchain.
mine_block() -> Block: Mines a new block with the current transactions and adds it to the blockchain.
get_chain() -> list: Retrieves the entire blockchain.
```

- Refer to `docs/example.py` for a sample code

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/sharhan-alhassan/liotbchain",
    "name": "liotbchain",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": null,
    "keywords": "blockchain python iot framework",
    "author": "Sharhan Alhassan",
    "author_email": "sharhanalhassan@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/ee/ac/c32846f9dd16a5a13c9d635d4aeb2e536004c858f469e45a5cc6d3fb1d03/liotbchain-0.0.8.tar.gz",
    "platform": null,
    "description": "# liotbchain\nliotbchain is a lightweight, versatile blockchain framework designed for both IoT and non-IoT applications. It provides a robust and flexible solution for creating, managing, and interacting with blockchains, leveraging Python's simplicity and the efficiency of PostgreSQL for data storage. With configurable parameters for mining difficulty, transaction grouping, and proof-of-work limits, liotbchain adapts to various use cases, ensuring secure and efficient data management across distributed systems.\n\nDisclaimer: liotbchain is not intended for real production environments but aims to leverage the core principles of blockchain technology for running a local, self-created blockchain. It is ideal for educational purposes, prototyping, and small-scale projects\n\n\n# Installation\nTo install the liotbchain framework, use the following command:\n```sh\npip install liotbchain\n```\n\n# Configuration\n## Environment Variables\nYou can configure the liotbchain framework using environment variables:\n\n### Option 1: Set environment variables\n```sh\n1. Export using the os utility\nDATABASE_URL = os.getenv(\"DATABASE_URL\", \"default_db_url\")\n\n# Number of transactions to be grouped into a single block\n# Default is 1 transaction per block\nTRANSACTIONS_PER_BLOCK = int(os.getenv(\"TRANSACTIONS_PER_BLOCK\", 1))\n\n# Mining difficulty: the number of leading zeros required in the block hash\n# Default is 4\n# Warning: Setting a high value increases the time and computational resources needed for mining\nDIFFICULTY = int(os.getenv(\"DIFFICULTY\", 3))\n\n# Nonce limit to prevent infinite loops during the mining process\n# Default is 1000000\n# Warning: Setting a very high value can lead to long mining times and excessive computational resource usage\nNONCE_LIMIT = int(os.getenv(\"NONCE_LIMIT\", 1000000))\n\n2. Export variables directly to your working shell/terminal\n# Set environment variables before running your script:\n# Set the PostgreSQL database URL\nexport DATABASE_URL=\"postgresql://username:password@hostname:port/database_name\"\n\n# Set the number of transactions per block\nexport TRANSACTIONS_PER_BLOCK=2\n\n# Set the mining difficulty\nexport DIFFICULTY=5\n\n# Set the nonce limit to prevent infinite loops during mining\nexport NONCE_LIMIT=500000\n\n3. Directly set the environment variables in a .env file\nDATABASE_URL=\nTRANSACTIONS_PER_BLOCK=\nDIFFICULTY=\nNONCE_LIMIT=\n\n# Then instantiate the Blockchain() without passing any parameters\nfrom liotbchain import Blockchain\nblockchain = Blockchain()\n\n```\n\n### Option 2: Instantiate the Blockchain class with parameters:\n```sh\nfrom liotbchain import Blockchain\n\n# Instantiate the Blockchain with custom parameters\nblockchain = Blockchain(difficulty=5, nonce_limit=500000, db_url=\"postgresql://username:password@hostname:port/database_name\", transactions_per_block=2)\n\n```\n\n# Usage\nAdding Transactions and Mining Blocks\nYou can add transactions to the blockchain and mine blocks:\n```py\n# Add transactions\ntransaction1 = {\"device\": \"Raspberry Pi 1\", \"distance\": 120, \"timestamp\": time.time()}\ntransaction2 = {\"device\": \"Raspberry Pi 2\", \"distance\": 150, \"timestamp\": time.time()}\ntransaction3 = {\"device\": \"Raspberry Pi 3\", \"distance\": 130, \"timestamp\": time.time()}\n\nblockchain.add_transaction(transaction1)\nblockchain.add_transaction(transaction2)\nblockchain.add_transaction(transaction3)\n\n# Mine a block when the number of transactions reaches the configured limit\nblockchain.mine_block()\n```\n\n# Displaying the Blockchain\nYou can display the entire blockchain:\n```py\n# Display the blockchain\nfor block in blockchain.get_chain():\n    print(f\"Block {block.index}: Transactions={block.data}, Nonce={block.nonce}, Hash={block.hash}, Merkle Root={block.merkle_root}\")\n```\n\n# Validating the Blockchain\nYou can validate the integrity of the blockchain:\n```py\nif blockchain.is_chain_valid():\n    print(\"The blockchain is valid.\")\nelse:\n    print(\"The blockchain is not valid.\")\n```\n\n# API Reference\nBlock Class\nThe Block class represents a block in the blockchain.\n\n## Attributes:\n```sh\nindex (int): The block's index within the blockchain.\ntimestamp (float): The timestamp of when the block was created.\ndata (list): The transactions stored within the block.\nprevious_hash (str): The hash of the block's predecessor.\nnonce (int): The nonce used for the proof-of-work.\nhash (str): The hash of the block.\nmerkle_root (str): The Merkle root hash of the block's transactions.\n```\n\n## Methods:\n```sh\ncalculate_hash() -> str: Calculates the SHA-256 hash of the block.\ncalculate_merkle_root() -> str: Calculates the Merkle root hash of the block's transactions.\n```\n\n## Blockchain Class\nThe Blockchain class implements the blockchain with proof-of-work mechanism.\n\nAttributes:\n```sh\nchain (list): A list of blocks that form the blockchain.\ndifficulty (int): The number of leading zeros required in the hash.\ntransactions (list): A list to hold transactions temporarily until a block is created.\nnonce_limit (int): The maximum limit for nonce to prevent infinite loops.\n```\n\n# Methods:\n```sh\n__init__(difficulty=None, nonce_limit=None, db_url=None, transactions_per_block=None): Initializes the blockchain with optional configuration parameters.\ncreate_genesis_block(): Generates the genesis block and appends it to the blockchain.\ninitialize_blockchain(): Initializes the blockchain by creating the database and loading existing blocks from the database.\nsave_blockchain(): Saves the entire blockchain to the database.\nadd_block(block): Adds a new block to the blockchain after performing proof-of-work.\nproof_of_work(block) -> str: Performs the proof of work to adjust the block's nonce until the hash meets the blockchain difficulty.\nis_chain_valid() -> bool: Validates the blockchain's integrity by ensuring each block's link and proof-of-work are correct.\nget_latest_block() -> Block: Retrieves the most recent block in the blockchain.\nadd_transaction(transaction): Adds a transaction to the temporary storage. When the number of transactions reaches the configured limit, a new block is mined and added to the blockchain.\nmine_block() -> Block: Mines a new block with the current transactions and adds it to the blockchain.\nget_chain() -> list: Retrieves the entire blockchain.\n```\n\n- Refer to `docs/example.py` for a sample code\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Python Lightweight IOT Blockchain framework",
    "version": "0.0.8",
    "project_urls": {
        "Homepage": "https://github.com/sharhan-alhassan/liotbchain"
    },
    "split_keywords": [
        "blockchain",
        "python",
        "iot",
        "framework"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1b011ef1027dc45012b143581ddee7209791a84b73f6a31bf0acf582f599a9df",
                "md5": "d83e305dd26d99a00208399917a0b481",
                "sha256": "d9841fde3934c2dadf7765677ccffa21460522a802b5c9ef3df5813197a2b513"
            },
            "downloads": -1,
            "filename": "liotbchain-0.0.8-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "d83e305dd26d99a00208399917a0b481",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 11090,
            "upload_time": "2024-06-10T01:22:34",
            "upload_time_iso_8601": "2024-06-10T01:22:34.774378Z",
            "url": "https://files.pythonhosted.org/packages/1b/01/1ef1027dc45012b143581ddee7209791a84b73f6a31bf0acf582f599a9df/liotbchain-0.0.8-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "eeacc32846f9dd16a5a13c9d635d4aeb2e536004c858f469e45a5cc6d3fb1d03",
                "md5": "6ba5eca61faa5bd1eb8be348c91400b5",
                "sha256": "9e92bc93942a1253ce64c53e97af6f69b9fe12116bc9974d4dec9e50d5da69c5"
            },
            "downloads": -1,
            "filename": "liotbchain-0.0.8.tar.gz",
            "has_sig": false,
            "md5_digest": "6ba5eca61faa5bd1eb8be348c91400b5",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 11742,
            "upload_time": "2024-06-10T01:22:36",
            "upload_time_iso_8601": "2024-06-10T01:22:36.030148Z",
            "url": "https://files.pythonhosted.org/packages/ee/ac/c32846f9dd16a5a13c9d635d4aeb2e536004c858f469e45a5cc6d3fb1d03/liotbchain-0.0.8.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-10 01:22:36",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "sharhan-alhassan",
    "github_project": "liotbchain",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "liotbchain"
}
        
Elapsed time: 0.34410s