-
Notifications
You must be signed in to change notification settings - Fork 663
/
pox_3.rs
443 lines (402 loc) · 15.9 KB
/
pox_3.rs
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020-2023 Stacks Open Internet Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use clarity::boot_util::boot_code_id;
use clarity::vm::contexts::GlobalContext;
use clarity::vm::costs::cost_functions::ClarityCostFunction;
use clarity::vm::costs::runtime_cost;
use clarity::vm::database::{ClarityDatabase, STXBalance};
use clarity::vm::errors::{Error as ClarityError, RuntimeErrorType};
use clarity::vm::events::{STXEventType, STXLockEventData, StacksTransactionEvent};
use clarity::vm::types::{PrincipalData, QualifiedContractIdentifier};
use clarity::vm::{Environment, Value};
use slog::{slog_debug, slog_error};
use stacks_common::{debug, error};
use crate::events::synthesize_pox_event_info;
// Note: PoX-3 uses the same contract-call result parsing routines as PoX-2
use crate::pox_2::{parse_pox_extend_result, parse_pox_increase, parse_pox_stacking_result};
use crate::{LockingError, POX_3_NAME};
/////////////////////// PoX-3 /////////////////////////////////
/// is a PoX-3 function call read only?
pub(crate) fn is_read_only(func_name: &str) -> bool {
"get-pox-rejection" == func_name
|| "is-pox-active" == func_name
|| "burn-height-to-reward-cycle" == func_name
|| "reward-cycle-to-burn-height" == func_name
|| "current-pox-reward-cycle" == func_name
|| "get-stacker-info" == func_name
|| "get-check-delegation" == func_name
|| "get-reward-set-size" == func_name
|| "next-cycle-rejection-votes" == func_name
|| "get-total-ustx-stacked" == func_name
|| "get-reward-set-pox-address" == func_name
|| "get-stacking-minimum" == func_name
|| "check-pox-addr-version" == func_name
|| "check-pox-addr-hashbytes" == func_name
|| "check-pox-lock-period" == func_name
|| "can-stack-stx" == func_name
|| "minimal-can-stack-stx" == func_name
|| "get-pox-info" == func_name
|| "get-delegation-info" == func_name
|| "get-allowance-contract-callers" == func_name
|| "get-num-reward-set-pox-addresses" == func_name
|| "get-partial-stacked-by-cycle" == func_name
|| "get-total-pox-rejection" == func_name
}
/// Lock up STX for PoX for a time. Does NOT touch the account nonce.
pub fn pox_lock_v3(
db: &mut ClarityDatabase,
principal: &PrincipalData,
lock_amount: u128,
unlock_burn_height: u64,
) -> Result<(), LockingError> {
assert!(unlock_burn_height > 0);
assert!(lock_amount > 0);
let mut snapshot = db.get_stx_balance_snapshot(principal)?;
if snapshot.has_locked_tokens()? {
return Err(LockingError::PoxAlreadyLocked);
}
if !snapshot.can_transfer(lock_amount)? {
return Err(LockingError::PoxInsufficientBalance);
}
snapshot.lock_tokens_v3(lock_amount, unlock_burn_height)?;
debug!(
"PoX v3 lock applied";
"pox_locked_ustx" => snapshot.balance().amount_locked(),
"available_ustx" => snapshot.balance().amount_unlocked(),
"unlock_burn_height" => unlock_burn_height,
"account" => %principal,
);
snapshot.save()?;
Ok(())
}
/// Extend a STX lock up for PoX for a time. Does NOT touch the account nonce.
/// Returns Ok(lock_amount) when successful
///
/// # Errors
/// - Returns Error::PoxExtendNotLocked if this function was called on an account
/// which isn't locked. This *should* have been checked by the PoX v3 contract,
/// so this should surface in a panic.
pub fn pox_lock_extend_v3(
db: &mut ClarityDatabase,
principal: &PrincipalData,
unlock_burn_height: u64,
) -> Result<u128, LockingError> {
assert!(unlock_burn_height > 0);
let mut snapshot = db.get_stx_balance_snapshot(principal)?;
if !snapshot.has_locked_tokens()? {
return Err(LockingError::PoxExtendNotLocked);
}
snapshot.extend_lock_v3(unlock_burn_height)?;
let amount_locked = snapshot.balance().amount_locked();
debug!(
"PoX v3 lock applied";
"pox_locked_ustx" => amount_locked,
"available_ustx" => snapshot.balance().amount_unlocked(),
"unlock_burn_height" => unlock_burn_height,
"account" => %principal,
);
snapshot.save()?;
Ok(amount_locked)
}
/// Increase a STX lock up for PoX-3. Does NOT touch the account nonce.
/// Returns Ok( account snapshot ) when successful
///
/// # Errors
/// - Returns Error::PoxExtendNotLocked if this function was called on an account
/// which isn't locked. This *should* have been checked by the PoX v3 contract,
/// so this should surface in a panic.
pub fn pox_lock_increase_v3(
db: &mut ClarityDatabase,
principal: &PrincipalData,
new_total_locked: u128,
) -> Result<STXBalance, LockingError> {
assert!(new_total_locked > 0);
let mut snapshot = db.get_stx_balance_snapshot(principal)?;
if !snapshot.has_locked_tokens()? {
return Err(LockingError::PoxExtendNotLocked);
}
let bal = snapshot.canonical_balance_repr()?;
let total_amount = bal
.amount_unlocked()
.checked_add(bal.amount_locked())
.expect("STX balance overflowed u128");
if total_amount < new_total_locked {
return Err(LockingError::PoxInsufficientBalance);
}
if bal.amount_locked() > new_total_locked {
return Err(LockingError::PoxInvalidIncrease);
}
snapshot.increase_lock_v3(new_total_locked)?;
let out_balance = snapshot.canonical_balance_repr()?;
debug!(
"PoX v3 lock increased";
"pox_locked_ustx" => out_balance.amount_locked(),
"available_ustx" => out_balance.amount_unlocked(),
"unlock_burn_height" => out_balance.unlock_height(),
"account" => %principal,
);
snapshot.save()?;
Ok(out_balance)
}
/////////////// PoX-3 //////////////////////////////////////////
/// Handle responses from stack-stx and delegate-stack-stx in pox-3 -- functions that *lock up* STX
#[allow(clippy::needless_return)]
fn handle_stack_lockup_pox_v3(
global_context: &mut GlobalContext,
function_name: &str,
value: &Value,
) -> Result<Option<StacksTransactionEvent>, ClarityError> {
debug!(
"Handle special-case contract-call to {:?} {} (which returned {:?})",
boot_code_id(POX_3_NAME, global_context.mainnet),
function_name,
value
);
// applying a pox lock at this point is equivalent to evaluating a transfer
runtime_cost(
ClarityCostFunction::StxTransfer,
&mut global_context.cost_track,
1,
)?;
let (stacker, locked_amount, unlock_height) = match parse_pox_stacking_result(value) {
Ok(x) => x,
Err(_) => {
// nothing to do -- the function failed
return Ok(None);
}
};
match pox_lock_v3(
&mut global_context.database,
&stacker,
locked_amount,
unlock_height,
) {
Ok(_) => {
let event =
StacksTransactionEvent::STXEvent(STXEventType::STXLockEvent(STXLockEventData {
locked_amount,
unlock_height,
locked_address: stacker,
contract_identifier: boot_code_id(POX_3_NAME, global_context.mainnet),
}));
return Ok(Some(event));
}
Err(LockingError::DefunctPoxContract) => {
return Err(ClarityError::Runtime(
RuntimeErrorType::DefunctPoxContract,
None,
));
}
Err(LockingError::PoxAlreadyLocked) => {
// the caller tried to lock tokens into multiple pox contracts
return Err(ClarityError::Runtime(
RuntimeErrorType::PoxAlreadyLocked,
None,
));
}
Err(e) => {
panic!(
"FATAL: failed to lock {} from {} until {}: '{:?}'",
locked_amount, stacker, unlock_height, &e
);
}
}
}
/// Handle responses from stack-extend and delegate-stack-extend in pox-3 -- functions that *extend
/// already-locked* STX.
#[allow(clippy::needless_return)]
fn handle_stack_lockup_extension_pox_v3(
global_context: &mut GlobalContext,
function_name: &str,
value: &Value,
) -> Result<Option<StacksTransactionEvent>, ClarityError> {
// in this branch case, the PoX-3 contract has stored the extension information
// and performed the extension checks. Now, the VM needs to update the account locks
// (because the locks cannot be applied directly from the Clarity code itself)
// applying a pox lock at this point is equivalent to evaluating a transfer
debug!(
"Handle special-case contract-call to {:?} {} (which returned {:?})",
boot_code_id("pox-3", global_context.mainnet),
function_name,
value
);
runtime_cost(
ClarityCostFunction::StxTransfer,
&mut global_context.cost_track,
1,
)?;
let (stacker, unlock_height) = match parse_pox_extend_result(value) {
Ok(x) => x,
Err(_) => {
// The stack-extend function returned an error: we do not need to apply a lock
// in this case, and can just return and let the normal VM codepath surface the
// error response type.
return Ok(None);
}
};
match pox_lock_extend_v3(&mut global_context.database, &stacker, unlock_height) {
Ok(locked_amount) => {
let event =
StacksTransactionEvent::STXEvent(STXEventType::STXLockEvent(STXLockEventData {
locked_amount,
unlock_height,
locked_address: stacker,
contract_identifier: boot_code_id(POX_3_NAME, global_context.mainnet),
}));
return Ok(Some(event));
}
Err(LockingError::DefunctPoxContract) => {
return Err(ClarityError::Runtime(
RuntimeErrorType::DefunctPoxContract,
None,
));
}
Err(e) => {
// Error results *other* than a DefunctPoxContract panic, because
// those errors should have been caught by the PoX contract before
// getting to this code path.
panic!(
"FATAL: failed to extend lock from {} until {}: '{:?}'",
stacker, unlock_height, &e
);
}
}
}
/// Handle responses from stack-increase and delegate-stack-increase in PoX-3 -- functions
/// that *increase already-locked* STX amounts.
#[allow(clippy::needless_return)]
fn handle_stack_lockup_increase_pox_v3(
global_context: &mut GlobalContext,
function_name: &str,
value: &Value,
) -> Result<Option<StacksTransactionEvent>, ClarityError> {
// in this branch case, the PoX-3 contract has stored the increase information
// and performed the increase checks. Now, the VM needs to update the account locks
// (because the locks cannot be applied directly from the Clarity code itself)
// applying a pox lock at this point is equivalent to evaluating a transfer
debug!(
"Handle special-case contract-call";
"contract" => ?boot_code_id("pox-3", global_context.mainnet),
"function" => function_name,
"return-value" => %value,
);
runtime_cost(
ClarityCostFunction::StxTransfer,
&mut global_context.cost_track,
1,
)?;
let (stacker, total_locked) = match parse_pox_increase(value) {
Ok(x) => x,
Err(_) => {
// nothing to do -- function failed
return Ok(None);
}
};
match pox_lock_increase_v3(&mut global_context.database, &stacker, total_locked) {
Ok(new_balance) => {
let event =
StacksTransactionEvent::STXEvent(STXEventType::STXLockEvent(STXLockEventData {
locked_amount: new_balance.amount_locked(),
unlock_height: new_balance.unlock_height(),
locked_address: stacker,
contract_identifier: boot_code_id(POX_3_NAME, global_context.mainnet),
}));
return Ok(Some(event));
}
Err(LockingError::DefunctPoxContract) => {
return Err(ClarityError::Runtime(
RuntimeErrorType::DefunctPoxContract,
None,
));
}
Err(e) => {
// Error results *other* than a DefunctPoxContract panic, because
// those errors should have been caught by the PoX contract before
// getting to this code path.
panic!(
"FATAL: failed to increase lock from {}: '{:?}'",
stacker, &e
);
}
}
}
/// Handle special cases when calling into the PoX-3 API contract
pub fn handle_contract_call(
global_context: &mut GlobalContext,
sender_opt: Option<&PrincipalData>,
contract_id: &QualifiedContractIdentifier,
function_name: &str,
args: &[Value],
value: &Value,
) -> Result<(), ClarityError> {
// Generate a synthetic print event for all functions that alter stacking state
let print_event_opt = if let Value::Response(response) = value {
if response.committed {
// method succeeded. Synthesize event info, but default to no event report if we fail
// for some reason.
// Failure to synthesize an event due to a bug is *NOT* an excuse to crash the whole
// network! Event capture is not consensus-critical.
let event_info_opt = match synthesize_pox_event_info(
global_context,
contract_id,
sender_opt,
function_name,
args,
response,
) {
Ok(Some(event_info)) => Some(event_info),
Ok(None) => None,
Err(e) => {
error!("Failed to synthesize PoX-3 event info: {:?}", &e);
None
}
};
if let Some(event_info) = event_info_opt {
let event_response =
Value::okay(event_info).expect("FATAL: failed to construct (ok event-info)");
let tx_event =
Environment::construct_print_transaction_event(contract_id, &event_response);
Some(tx_event)
} else {
None
}
} else {
None
}
} else {
None
};
// Execute function specific logic to complete the lock-up
let lock_event_opt = if function_name == "stack-stx" || function_name == "delegate-stack-stx" {
handle_stack_lockup_pox_v3(global_context, function_name, value)?
} else if function_name == "stack-extend" || function_name == "delegate-stack-extend" {
handle_stack_lockup_extension_pox_v3(global_context, function_name, value)?
} else if function_name == "stack-increase" || function_name == "delegate-stack-increase" {
handle_stack_lockup_increase_pox_v3(global_context, function_name, value)?
} else {
None
};
// append the lockup event, so it looks as if the print event happened before the lock-up
if let Some(batch) = global_context.event_batches.last_mut() {
if let Some(print_event) = print_event_opt {
batch.events.push(print_event);
}
if let Some(lock_event) = lock_event_opt {
batch.events.push(lock_event);
}
}
Ok(())
}