api_for_unity / Blockchain.py
ldhldh's picture
Update Blockchain.py (#4)
79cf827
raw
history blame
3.63 kB
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
@property
def last_block(self):
"""
์ฒด์ธ์˜ ๋งˆ์ง€๋ง‰ ๋ธ”๋ก ๋ฐ˜ํ™˜
"""
return self.chain[-1]
@staticmethod
def hash(block):
"""
๋ธ”๋ก์„ SHA-256์œผ๋กœ ํ•ด์‹ฑ
:param block: ๋ธ”๋ก
:return: ํ•ด์‹œ ๊ฐ’
"""
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()