api_for_unity / Blockchain.py
ldhldh's picture
Rename BlockChain.py to Blockchain.py
0a0197b
raw
history blame
2.98 kB
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: ์ƒˆ๋กœ ์ƒ์„ฑ๋œ ๋ธ”๋ก
"""
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์œผ๋กœ ์„ค์ •
else:
# inference ์š”์ฒญ ์‹œ ์ฐจ๊ฐ
self.user_wallets[id] -= 1
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, 0)
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
@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()