Spaces:
Sleeping
Sleeping
import hashlib | |
import json | |
from time import time | |
class Blockchain: | |
def __init__(self): | |
self.chain = [] | |
self.current_transactions = [] | |
self.user_wallets = {} | |
self.user_gpus = {} | |
# Genesis ๋ธ๋ก ์์ฑ | |
self.new_block(previous_hash="1") | |
def new_block(self, previous_hash=None): | |
""" | |
๋ธ๋ก์ฒด์ธ์ ์๋ก์ด ๋ธ๋ก ์ถ๊ฐ | |
:param previous_hash: ์ด์ ๋ธ๋ก์ ํด์ ๊ฐ | |
:return: ์๋ก ์์ฑ๋ ๋ธ๋ก | |
""" | |
for id, mem in self.user_gpus.items(): | |
if id in self.user_wallets: | |
self.user_wallets[id] += mem//2 | |
else: | |
self.user_wallets[id] = 10 | |
self.user_wallets[id] += mem//2 | |
block = { | |
'index': len(self.chain) + 1, | |
'timestamp': time(), | |
'transactions': self.current_transactions, | |
'previous_hash': previous_hash or self.hash(self.chain[-1]), | |
} | |
# ํ์ฌ ํธ๋์ญ์ ์ด๊ธฐํ | |
self.current_transactions = [] | |
# ๋ธ๋ก์ ์ฒด์ธ์ ์ถ๊ฐ | |
self.chain.append(block) | |
return block | |
def new_transaction(self, id, kind, data): | |
""" | |
์๋ก์ด ํธ๋์ญ์ ์์ฑ ๋ฐ ์ถ๊ฐ | |
id: ์์ฒญ์ | |
kind: ์์ฒญ ์ข ๋ฅ (inference, add, out) | |
data: inference ์ [์ ๋ ฅ prompt, output], peer add ์ gpu mem, out ์ ๋ํ gpu mem | |
return: ํด๋น ํธ๋์ญ์ ์ ํฌํจํ ๋ธ๋ก์ ์ธ๋ฑ์ค | |
""" | |
transaction = { | |
'id': id, | |
'kind': kind, | |
'data': data, | |
} | |
self.current_transactions.append(transaction) | |
# ๊ฐ ์ ์ ์ ํ๋๋ ฅ ์ ๋ฐ์ดํธ | |
if kind == "inference": | |
if id not in self.user_wallets: | |
# ์๋ก์ด ์ ์ ์ธ ๊ฒฝ์ฐ ์ด๊ธฐ ํ๋๋ ฅ ์ค์ | |
self.user_wallets[id] = 10 # ์ด๊ธฐ ํ๋๋ ฅ์ 10์ผ๋ก ์ค์ | |
self.user_wallets[id] -= 1 | |
else: | |
# inference ์์ฒญ ์ ์ฐจ๊ฐ | |
self.user_wallets[id] -= 1 | |
if self.user_wallets[id]<0: | |
self.user_wallets[id] = 0 | |
elif kind == "add": | |
if id not in self.user_gpus: | |
self.user_gpus[id] = int(data) | |
else: | |
self.user_gpus[id] += int(data) | |
elif kind == "out": | |
if id in self.user_gpus: | |
del(self.user_gpus[id]) | |
return self.last_block['index'] + 1 | |
def get_user_balance(self, id): | |
# ํน์ ์ ์ ์ ํ๋๋ ฅ์ ์กฐํ | |
return self.user_wallets.get(id, 10) | |
def get_user_gpu_mem(self, id): | |
# ํน์ ์ ์ ์ ๊ธฐ์ฌ gpu๋ฅผ ์กฐํ | |
return self.user_gpus.get(id, 0) | |
def get_total_gpu_mem(self): | |
# ์ ์ฒด ๋ฉ๋ชจ๋ฆฌ ๋ฐํ | |
result = 0 | |
for mem in self.user_gpus.values(): | |
result += int(mem) | |
return result | |
def get_total_coin(self): | |
# ์ ์ฒด ์ฝ์ธ(ํ๋๋ ฅ) ์ ๋ฐํ | |
result = 0 | |
for coin in self.user_wallets.values(): | |
result += int(coin) | |
return result | |
def last_block(self): | |
""" | |
์ฒด์ธ์ ๋ง์ง๋ง ๋ธ๋ก ๋ฐํ | |
""" | |
return self.chain[-1] | |
def hash(block): | |
""" | |
๋ธ๋ก์ SHA-256์ผ๋ก ํด์ฑ | |
:param block: ๋ธ๋ก | |
:return: ํด์ ๊ฐ | |
""" | |
block_string = json.dumps(block, sort_keys=True).encode() | |
return hashlib.sha256(block_string).hexdigest() |