-
Notifications
You must be signed in to change notification settings - Fork 2k
/
farmer.py
343 lines (304 loc) · 13.5 KB
/
farmer.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
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import logging
import os
from hashlib import sha256
from typing import Any, Dict, List, Set
from blspy import PrependSignature, PrivateKey, Util
from yaml import safe_load
from definitions import ROOT_DIR
from src.consensus.block_rewards import calculate_block_reward
from src.consensus.constants import constants
from src.consensus.pot_iterations import calculate_iterations_quality
from src.protocols import farmer_protocol, harvester_protocol
from src.server.outbound_message import Delivery, Message, NodeType, OutboundMessage
from src.types.coinbase import CoinbaseInfo
from src.types.proof_of_space import ProofOfSpace
from src.types.sized_bytes import bytes32
from src.util.api_decorators import api_request
from src.util.ints import uint32, uint64
log = logging.getLogger(__name__)
"""
HARVESTER PROTOCOL (FARMER <-> HARVESTER)
"""
class Farmer:
def __init__(self):
config_filename = os.path.join(ROOT_DIR, "config", "config.yaml")
key_config_filename = os.path.join(ROOT_DIR, "config", "keys.yaml")
if not os.path.isfile(key_config_filename):
raise RuntimeError(
"Keys not generated. Run python3.7 ./scripts/regenerate_keys.py."
)
self.config = safe_load(open(config_filename, "r"))["farmer"]
self.key_config = safe_load(open(key_config_filename, "r"))
self.harvester_responses_header_hash: Dict[bytes32, bytes32] = {}
self.harvester_responses_challenge: Dict[bytes32, bytes32] = {}
self.harvester_responses_proofs: Dict[bytes32, ProofOfSpace] = {}
self.harvester_responses_proof_hash_to_qual: Dict[bytes32, bytes32] = {}
self.challenges: Dict[uint64, List[farmer_protocol.ProofOfSpaceFinalized]] = {}
self.challenge_to_weight: Dict[bytes32, uint64] = {}
self.challenge_to_height: Dict[bytes32, uint32] = {}
self.challenge_to_best_iters: Dict[bytes32, uint64] = {}
self.seen_challenges: Set[bytes32] = set()
self.unfinished_challenges: Dict[uint64, List[bytes32]] = {}
self.current_weight: uint64 = uint64(0)
self.coinbase_rewards: Dict[uint32, Any] = {}
self.proof_of_time_estimate_ips: uint64 = uint64(10000)
@api_request
async def challenge_response(
self, challenge_response: harvester_protocol.ChallengeResponse
):
"""
This is a response from the harvester, for a NewChallenge. Here we check if the proof
of space is sufficiently good, and if so, we ask for the whole proof.
"""
if challenge_response.quality in self.harvester_responses_challenge:
log.warning(f"Have already seen quality {challenge_response.quality}")
return
weight: uint64 = self.challenge_to_weight[challenge_response.challenge_hash]
height: uint32 = self.challenge_to_height[challenge_response.challenge_hash]
difficulty: uint64 = uint64(0)
for posf in self.challenges[weight]:
if posf.challenge_hash == challenge_response.challenge_hash:
difficulty = posf.difficulty
if difficulty == 0:
raise RuntimeError("Did not find challenge")
number_iters: uint64 = calculate_iterations_quality(
challenge_response.quality,
challenge_response.plot_size,
difficulty,
self.proof_of_time_estimate_ips,
constants["MIN_BLOCK_TIME"],
)
if height < 1000: # As the difficulty adjusts, don't fetch all qualities
if challenge_response.challenge_hash not in self.challenge_to_best_iters:
self.challenge_to_best_iters[
challenge_response.challenge_hash
] = number_iters
elif (
number_iters
< self.challenge_to_best_iters[challenge_response.challenge_hash]
):
self.challenge_to_best_iters[
challenge_response.challenge_hash
] = number_iters
else:
return
estimate_secs: float = number_iters / self.proof_of_time_estimate_ips
log.info(f"Estimate: {estimate_secs}, rate: {self.proof_of_time_estimate_ips}")
if (
estimate_secs < self.config["pool_share_threshold"]
or estimate_secs < self.config["propagate_threshold"]
):
self.harvester_responses_challenge[
challenge_response.quality
] = challenge_response.challenge_hash
request = harvester_protocol.RequestProofOfSpace(challenge_response.quality)
yield OutboundMessage(
NodeType.HARVESTER,
Message("request_proof_of_space", request),
Delivery.RESPOND,
)
@api_request
async def respond_proof_of_space(
self, response: harvester_protocol.RespondProofOfSpace
):
"""
This is a response from the harvester with a proof of space. We check it's validity,
and request a pool partial, a header signature, or both, if the proof is good enough.
"""
pool_sks: List[PrivateKey] = [
PrivateKey.from_bytes(bytes.fromhex(ce))
for ce in self.key_config["pool_sks"]
]
assert response.proof.pool_pubkey in [sk.get_public_key() for sk in pool_sks]
challenge_hash: bytes32 = self.harvester_responses_challenge[response.quality]
challenge_weight: uint64 = self.challenge_to_weight[challenge_hash]
challenge_height: uint32 = self.challenge_to_height[challenge_hash]
new_proof_height: uint32 = uint32(challenge_height + 1)
difficulty: uint64 = uint64(0)
for posf in self.challenges[challenge_weight]:
if posf.challenge_hash == challenge_hash:
difficulty = posf.difficulty
if difficulty == 0:
raise RuntimeError("Did not find challenge")
computed_quality = response.proof.verify_and_get_quality()
assert response.quality == computed_quality
self.harvester_responses_proofs[response.quality] = response.proof
self.harvester_responses_proof_hash_to_qual[
response.proof.get_hash()
] = response.quality
number_iters: uint64 = calculate_iterations_quality(
computed_quality,
response.proof.size,
difficulty,
self.proof_of_time_estimate_ips,
constants["MIN_BLOCK_TIME"],
)
estimate_secs: float = number_iters / self.proof_of_time_estimate_ips
if estimate_secs < self.config["pool_share_threshold"]:
request1 = harvester_protocol.RequestPartialProof(
response.quality,
sha256(bytes.fromhex(self.key_config["farmer_target"])).digest(),
)
yield OutboundMessage(
NodeType.HARVESTER,
Message("request_partial_proof", request1),
Delivery.RESPOND,
)
if estimate_secs < self.config["propagate_threshold"]:
if new_proof_height not in self.coinbase_rewards:
log.error(
f"Don't have coinbase transaction for height {new_proof_height}, cannot submit PoS"
)
return
coinbase, signature = self.coinbase_rewards[new_proof_height]
request2 = farmer_protocol.RequestHeaderHash(
challenge_hash,
coinbase,
signature,
bytes.fromhex(self.key_config["farmer_target"]),
response.proof,
)
yield OutboundMessage(
NodeType.FULL_NODE,
Message("request_header_hash", request2),
Delivery.BROADCAST,
)
@api_request
async def respond_header_signature(
self, response: harvester_protocol.RespondHeaderSignature
):
"""
Receives a signature on a block header hash, which is required for submitting
a block to the blockchain.
"""
header_hash: bytes32 = self.harvester_responses_header_hash[response.quality]
proof_of_space: bytes32 = self.harvester_responses_proofs[response.quality]
plot_pubkey = self.harvester_responses_proofs[response.quality].plot_pubkey
assert response.header_hash_signature.verify(
[Util.hash256(header_hash)], [plot_pubkey]
)
pos_hash: bytes32 = proof_of_space.get_hash()
request = farmer_protocol.HeaderSignature(
pos_hash, header_hash, response.header_hash_signature
)
yield OutboundMessage(
NodeType.FULL_NODE, Message("header_signature", request), Delivery.BROADCAST
)
@api_request
async def respond_partial_proof(
self, response: harvester_protocol.RespondPartialProof
):
"""
Receives a signature on the hash of the farmer payment target, which is used in a pool
share, to tell the pool where to pay the farmer.
"""
farmer_target_hash = sha256(
bytes.fromhex(self.key_config["farmer_target"])
).digest()
plot_pubkey = self.harvester_responses_proofs[response.quality].plot_pubkey
assert response.farmer_target_signature.verify(
[Util.hash256(farmer_target_hash)], [plot_pubkey]
)
# TODO: Send partial to pool
"""
FARMER PROTOCOL (FARMER <-> FULL NODE)
"""
@api_request
async def header_hash(self, response: farmer_protocol.HeaderHash):
"""
Full node responds with the hash of the created header
"""
header_hash: bytes32 = response.header_hash
quality: bytes32 = self.harvester_responses_proof_hash_to_qual[
response.pos_hash
]
self.harvester_responses_header_hash[quality] = header_hash
# TODO: only send to the harvester who made the proof of space, not all harvesters
request = harvester_protocol.RequestHeaderSignature(quality, header_hash)
yield OutboundMessage(
NodeType.HARVESTER,
Message("request_header_signature", request),
Delivery.BROADCAST,
)
@api_request
async def proof_of_space_finalized(
self, proof_of_space_finalized: farmer_protocol.ProofOfSpaceFinalized
):
"""
Full node notifies farmer that a proof of space has been completed. It gets added to the
challenges list at that weight, and weight is updated if necessary
"""
get_proofs: bool = False
if (
proof_of_space_finalized.weight >= self.current_weight
and proof_of_space_finalized.challenge_hash not in self.seen_challenges
):
# Only get proofs for new challenges, at a current or new weight
get_proofs = True
if proof_of_space_finalized.weight > self.current_weight:
self.current_weight = proof_of_space_finalized.weight
# TODO: ask the pool for this information
coinbase: CoinbaseInfo = CoinbaseInfo(
uint32(proof_of_space_finalized.height + 1),
calculate_block_reward(proof_of_space_finalized.height),
bytes.fromhex(self.key_config["pool_target"]),
)
pool_sks: List[PrivateKey] = [
PrivateKey.from_bytes(bytes.fromhex(ce))
for ce in self.key_config["pool_sks"]
]
coinbase_signature: PrependSignature = pool_sks[0].sign_prepend(
bytes(coinbase)
)
self.coinbase_rewards[uint32(proof_of_space_finalized.height + 1)] = (
coinbase,
coinbase_signature,
)
log.info(f"\tCurrent weight set to {self.current_weight}")
self.seen_challenges.add(proof_of_space_finalized.challenge_hash)
if proof_of_space_finalized.weight not in self.challenges:
self.challenges[proof_of_space_finalized.weight] = [
proof_of_space_finalized
]
else:
self.challenges[proof_of_space_finalized.weight].append(
proof_of_space_finalized
)
self.challenge_to_weight[
proof_of_space_finalized.challenge_hash
] = proof_of_space_finalized.weight
self.challenge_to_height[
proof_of_space_finalized.challenge_hash
] = proof_of_space_finalized.height
if get_proofs:
message = harvester_protocol.NewChallenge(
proof_of_space_finalized.challenge_hash
)
yield OutboundMessage(
NodeType.HARVESTER,
Message("new_challenge", message),
Delivery.BROADCAST,
)
@api_request
async def proof_of_space_arrived(
self, proof_of_space_arrived: farmer_protocol.ProofOfSpaceArrived
):
"""
Full node notifies the farmer that a new proof of space was created. The farmer can use this
information to decide whether to propagate a proof.
"""
if proof_of_space_arrived.weight not in self.unfinished_challenges:
self.unfinished_challenges[proof_of_space_arrived.weight] = []
else:
self.unfinished_challenges[proof_of_space_arrived.weight].append(
proof_of_space_arrived.quality
)
@api_request
async def proof_of_time_rate(
self, proof_of_time_rate: farmer_protocol.ProofOfTimeRate
):
"""
Updates our internal etimate of the iterations per second for the fastest proof of time
in the network.
"""
self.proof_of_time_estimate_ips = proof_of_time_rate.pot_estimate_ips