/
Builder.py
63 lines (51 loc) · 2.13 KB
/
Builder.py
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
import os
import hashlib
import binascii
import RandomIO
import partialhash
# config vars
my_address = "1CutsncbjcCtZKeRfvQ7bnYFVj28zeU6fo"
my_store_path = "C:\\Farm\\"
my_shard_size = 1024*1024*128 # 128 MB
my_max_size = 1024*1024*1024 # 1024 MB
class Builder:
def __init__(self, address, shard_size, max_size):
self.address = address
self.shard_size = shard_size
self.max_size = max_size
@staticmethod
def sha256(content):
"""Finds the SHA-256 hash of the content."""
content = content.encode('utf-8')
return hashlib.sha256(content).hexdigest()
def build_seed(self, height):
"""Deterministically build a seed."""
seed = self.sha256(self.address)
for i in range(height):
seed = self.sha256(seed)
return seed
def generate_shard(self, seed, store_path, cleanup=False):
"""Save a shard, and return its SHA-256 hash."""
tmp_file = RandomIO.RandomIO(seed).read(self.shard_size) # temporarily generate file
file_hash = hashlib.sha256(tmp_file).hexdigest() # get SHA-256 hash
RandomIO.RandomIO(seed).genfile(self.shard_size, store_path+seed) # save the shard
if cleanup:
os.remove(store_path+seed)
return file_hash
def build(self, store_path, debug=False, cleanup=False):
"""Fill the farmer with data up to their max."""
for shard_num in range(int(self.max_size/self.shard_size)):
seed = self.build_seed(shard_num)
file_hash = self.generate_shard(seed, store_path, cleanup)
if debug:
print("Saving seed {0} with SHA-256 hash {1}.".format(seed, file_hash))
def challenge(self, seed, height):
for i in range(height):
seed_data = self.build_seed(i)
seed_path = my_store_path + seed_data
digest = partialhash.sample(seed_path, 1024, sample_count=3, seed=seed)
print(binascii.hexlify(digest))
if __name__ == "__main__": # pragma: no cover
bucket = Builder(my_address, my_shard_size, my_max_size)
#bucket.build(my_store_path, True)
bucket.challenge(b"test",10)