https://github.com/lostincompilation/stl-blockchain
A STL container like implementation of a blockchain for C++.
https://github.com/lostincompilation/stl-blockchain
Last synced: 9 months ago
JSON representation
A STL container like implementation of a blockchain for C++.
- Host: GitHub
- URL: https://github.com/lostincompilation/stl-blockchain
- Owner: LostInCompilation
- License: zlib
- Created: 2023-01-15T04:15:18.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2023-01-18T23:20:50.000Z (almost 3 years ago)
- Last Synced: 2025-04-12T22:56:49.313Z (9 months ago)
- Language: C++
- Size: 8.79 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# Blockchain C++ STL-Like Container
## Usage
Include the `Blockchain.h` header. Requires C++20.
```cpp
#include "Blockchain.h"
```
#### Creating a Blockchain
Create a Blockchain with `std::string` Blocks and add the Genesis Block:
```cpp
Blockchain blockchain("Genesis");
```
#### Pushing new blocks/transactions
```cpp
blockchain.push_back("Transaction 1");
blockchain.push_back("Transaction 2");
blockchain.push_back("Last transaction");
```
#### Iterating the Blockchain and print the Hash of each Block/Transaction
* Range-Based for loop:
```cpp
for(auto& block : blockchain)
std::cout << block.GetTransaction() << ":\t" << block.GetHash() << std::endl;
```
* Indexed for loop:
```cpp
for(int i = 0; i < blockchain.size(); I++)
std::cout << blockchain[i].GetTransaction() << ":\t" << blockchain[i].GetHash() << std::endl;
```
* Iterators:
```cpp
for (Blockchain::iterator iter = blockchain.begin(); iter != blockchain.end(); iter++)
std::cout << iter->GetTransaction() << ":\t" << iter->GetHash() << std::endl;
```
#### Checking the Blockchain
* `Blockchain<...>::Check()` checks if the hashes are consistent:
```cpp
if(blockchain.Check())
std::cout << "Blockchain hashes checked. ALL GOOD" << std::endl;
```
* `Blockchain<...>::Revalidate()` checks if the hashes and transactions are consistent:
```cpp
if(blockchain.Revalidate())
std::cout << "Blockchain hashes and transactions revalidated. ALL GOOD" << std::endl;
```
If a transaction or hash in the chain would be altered, the corresponding check/revalidate function would fail.
## Using a custom Hash-Function
The Blockchain uses std::hash<...> by default. You can use a custom hash function for the chain. Your custom Hasher can return any data type as the hash and must overload the `()` operator:
```cpp
template
class MyHashFunction
{
public:
std::string operator()(T input)
{
// Here calculate your hash based on the input
// and return your calculated hash
return "MyCalculatedHashFromInput";
}
};
```
To use the custom Hasher, simply specify it as a template argument when creating the Blockchain:
```cpp
Blockchain> customBlockchain("Genesis");
```