Last active
April 5, 2024 23:24
-
-
Save stkubr/0469ab30b1f992e2817f6060e4bf576f to your computer and use it in GitHub Desktop.
Simple Directed Acyclic Graph (IOTA-like) implementation in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# published in https://medium.com/@stkubr/simple-directed-acyclic-graph-iota-like-implementation-in-python-8e07677c55b5 | |
import hashlib | |
import random | |
import string | |
import time | |
from collections import OrderedDict | |
tangle_graph = {'genesis_branch': [], | |
'genesis_trunk': [] | |
} | |
tangle_data = {} | |
tangle_ledger = {'iota_satoshi': 100} | |
def calc_hash(msg): | |
hasher = hashlib.sha1(msg.encode()) | |
return hasher.hexdigest() | |
def get_random_string(): | |
return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(5)) | |
class Block: | |
def __init__(self, branch, trunk): | |
self.branch = branch | |
self.trunk = trunk | |
self.timestamp = time.time() | |
self.data_payload = get_random_string() | |
self.value_tx = None | |
def add_value_tx(self, sender, receiver, amount, signature): | |
self.value_tx = {'sender': sender, | |
'receiver': receiver, | |
'amount': amount, | |
'signature': signature | |
} | |
def get_hash(self): | |
return calc_hash(str(OrderedDict(self.__dict__))) | |
def add_tx(block: Block): | |
if block.branch in tangle_graph and block.trunk in tangle_graph: | |
if block.value_tx: | |
if check_value_tx(block.value_tx): | |
move_money(block.value_tx['sender'], | |
block.value_tx['receiver'], | |
block.value_tx['amount']) | |
tangle_graph[block.get_hash()] = [block.branch, block.trunk] | |
tangle_data[block.get_hash()] = {'data_payload': block.data_payload, | |
'value_payload': block.value_tx } | |
else: | |
tangle_graph[block.get_hash()] = [block.branch, block.trunk] | |
tangle_data[block.get_hash()] = block.data_payload | |
def find_tips(): | |
return tuple(random.sample(set(tangle_graph.keys()), 2)) | |
def check_value_tx(value_tx): | |
if value_tx['sender'] in tangle_ledger: | |
if value_tx['amount'] <= tangle_ledger[value_tx['sender']]: | |
# if signature is valid too | |
res = True | |
return res | |
def move_money(sender, receiver, amount): | |
tangle_ledger[sender] -= amount | |
if receiver in tangle_ledger: | |
tangle_ledger[receiver] += amount | |
else: | |
tangle_ledger[receiver] = amount |
Hi, I am doing a PhD. My topic is somewhat similar to you.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi.
I am pursuing my Ph.D in Computer engineering. My topic is Security in IoT networks and I am planning to implement tangle in IoT networks. If you can help me on how to start with, then it would be so grateful.