Spaces:
Sleeping
Sleeping
File size: 3,470 Bytes
4efcb9e 140dac2 981cbed 140dac2 981cbed 140dac2 ca87255 140dac2 981cbed 140dac2 aaaf4da 140dac2 ca87255 140dac2 ca87255 140dac2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
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():
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() |