Skip to content

Instantly share code, notes, and snippets.

@stkubr stkubr/tangle.py
Last active Jul 2, 2019

Embed
What would you like to do?
Simple Directed Acyclic Graph (IOTA-like) implementation in Python
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.