-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathevents_observer.rs
More file actions
1198 lines (1126 loc) · 42.9 KB
/
events_observer.rs
File metadata and controls
1198 lines (1126 loc) · 42.9 KB
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::DevnetEvent;
use crate::integrate::{MempoolAdmissionData, ServiceStatusData, Status};
use crate::poke::load_session;
use crate::publish::{publish_contract, Network};
use crate::types::{self, AccountConfig, DevnetConfig};
use crate::types::{
AccountIdentifier, Amount, BitcoinBlockData, BitcoinBlockMetadata, BitcoinTransactionData,
BitcoinTransactionMetadata, BlockIdentifier, Currency, CurrencyMetadata, CurrencyStandard,
Operation, OperationIdentifier, OperationStatusKind, OperationType, StacksBlockData,
StacksBlockMetadata, StacksTransactionData, StacksTransactionMetadata, TransactionIdentifier,
};
use crate::utils;
use crate::utils::stacks::{transactions, StacksRpc};
use base58::FromBase58;
use clarity_repl::clarity::codec::transaction::TransactionPayload;
use clarity_repl::clarity::codec::{StacksMessageCodec, StacksTransaction};
use clarity_repl::clarity::representations::ClarityName;
use clarity_repl::clarity::types::{BuffData, SequenceData, TupleData, Value as ClarityValue};
use clarity_repl::clarity::util::address::AddressHashMode;
use clarity_repl::clarity::util::hash::{hex_bytes, Hash160};
use clarity_repl::repl::settings::InitialContract;
use clarity_repl::repl::Session;
use rocket::config::{Config, LogLevel};
use rocket::serde::json::{json, Json, Value as JsonValue};
use rocket::serde::Deserialize;
use rocket::State;
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::convert::{TryFrom, TryInto};
use std::error::Error;
use std::io::Cursor;
use std::iter::FromIterator;
use std::net::{IpAddr, Ipv4Addr};
use std::path::PathBuf;
use std::str;
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Mutex, RwLock};
use tracing::info;
#[cfg(feature = "cli")]
use crate::runnner::deno;
#[allow(dead_code)]
#[derive(Deserialize)]
pub struct NewBurnBlock {
burn_block_hash: String,
burn_block_height: u64,
reward_slot_holders: Vec<String>,
burn_amount: u64,
}
#[derive(Deserialize)]
pub struct NewBlock {
block_height: u64,
block_hash: String,
burn_block_height: u64,
burn_block_hash: String,
parent_block_hash: String,
index_block_hash: String,
parent_index_block_hash: String,
transactions: Vec<NewTransaction>,
// reward_slot_holders: Vec<String>,
// burn_amount: u32,
}
#[derive(Deserialize)]
pub struct NewMicroBlock {
transactions: Vec<NewTransaction>,
}
#[derive(Deserialize)]
pub struct NewTransaction {
pub txid: String,
pub status: String,
pub raw_result: String,
pub raw_tx: String,
pub events: Vec<NewEvent>,
}
#[derive(Deserialize)]
pub struct NewEvent {
pub stx_transfer_event: Option<JsonValue>,
pub stx_mint_event: Option<JsonValue>,
pub stx_burn_event: Option<JsonValue>,
pub stx_lock_event: Option<JsonValue>,
pub nft_transfer_event: Option<JsonValue>,
pub nft_mint_event: Option<JsonValue>,
pub nft_burn_event: Option<JsonValue>,
pub ft_transfer_event: Option<JsonValue>,
pub ft_mint_event: Option<JsonValue>,
pub ft_burn_event: Option<JsonValue>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct STXTransferEventData {
pub sender: String,
pub recipient: String,
pub amount: u128,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct STXMintEventData {
pub recipient: String,
pub amount: u128,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct STXLockEventData {
pub locked_amount: u128,
pub unlock_height: u64,
pub locked_address: String,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct STXBurnEventData {
pub sender: String,
pub amount: u128,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct NFTTransferEventData {
#[serde(rename = "asset_identifier")]
pub asset_class_identifier: String,
#[serde(rename = "value")]
pub asset_identifier: String,
pub sender: String,
pub recipient: String,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct NFTMintEventData {
#[serde(rename = "asset_identifier")]
pub asset_class_identifier: String,
#[serde(rename = "value")]
pub asset_identifier: String,
pub recipient: String,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct NFTBurnEventData {
#[serde(rename = "asset_identifier")]
pub asset_class_identifier: String,
#[serde(rename = "value")]
pub asset_identifier: String,
pub sender: String,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct FTTransferEventData {
#[serde(rename = "asset_identifier")]
pub asset_class_identifier: String,
pub sender: String,
pub recipient: String,
pub amount: u128,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct FTMintEventData {
#[serde(rename = "asset_identifier")]
pub asset_class_identifier: String,
pub recipient: String,
pub amount: u128,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct FTBurnEventData {
#[serde(rename = "asset_identifier")]
pub asset_class_identifier: String,
pub sender: String,
pub amount: u128,
}
#[derive(Clone, Debug)]
pub struct EventObserverConfig {
pub devnet_config: DevnetConfig,
pub accounts: BTreeMap<String, AccountConfig>,
pub contracts_to_deploy: VecDeque<InitialContract>,
pub manifest_path: PathBuf,
pub pox_info: PoxInfo,
pub session: Session,
pub deployer_nonce: u64,
}
impl EventObserverConfig {
pub fn new(
devnet_config: DevnetConfig,
manifest_path: PathBuf,
accounts: BTreeMap<String, AccountConfig>,
) -> Self {
info!("Checking contracts...");
let session = match load_session(manifest_path.clone(), false, &Network::Devnet) {
Ok((session, _)) => session,
Err(e) => {
println!("{}", e);
std::process::exit(1);
}
};
EventObserverConfig {
devnet_config,
accounts,
manifest_path,
pox_info: PoxInfo::default(),
contracts_to_deploy: VecDeque::from_iter(
session.settings.initial_contracts.iter().map(|c| c.clone()),
),
session,
deployer_nonce: 0,
}
}
pub async fn execute_scripts(&self) {
if self.devnet_config.execute_script.len() > 0 {
for _cmd in self.devnet_config.execute_script.iter() {
#[cfg(feature = "cli")]
let _ = deno::do_run_scripts(
vec![_cmd.script.clone()],
false,
false,
false,
_cmd.allow_wallets,
_cmd.allow_write,
self.manifest_path.clone(),
Some(self.session.clone()),
)
.await;
}
}
}
}
#[derive(Deserialize, Debug, Clone, Default)]
pub struct PoxInfo {
contract_id: String,
pox_activation_threshold_ustx: u64,
first_burnchain_block_height: u64,
prepare_phase_block_length: u32,
reward_phase_block_length: u32,
reward_slots: u32,
total_liquid_supply_ustx: u64,
next_cycle: PoxCycle,
}
impl PoxInfo {
pub fn default() -> PoxInfo {
PoxInfo {
contract_id: "ST000000000000000000002AMW42H.pox".into(),
pox_activation_threshold_ustx: 0,
first_burnchain_block_height: 100,
prepare_phase_block_length: 1,
reward_phase_block_length: 4,
reward_slots: 8,
total_liquid_supply_ustx: 1000000000000000,
..Default::default()
}
}
}
#[derive(Deserialize, Debug, Clone, Default)]
pub struct PoxCycle {
min_threshold_ustx: u64,
}
#[derive(Deserialize, Debug, Clone, Default)]
pub struct AssetClassCache {
symbol: String,
decimals: u8,
}
pub async fn start_events_observer(
events_config: EventObserverConfig,
devnet_event_tx: Sender<DevnetEvent>,
terminator_rx: Receiver<bool>,
) -> Result<(), Box<dyn Error>> {
let _ = events_config.execute_scripts().await;
let port = events_config.devnet_config.orchestrator_port;
let manifest_path = events_config.manifest_path.clone();
let rw_lock = Arc::new(RwLock::new(events_config));
let asset_class_ids_map: HashMap<String, AssetClassCache> = HashMap::new();
let moved_rw_lock = rw_lock.clone();
let moved_tx = Arc::new(Mutex::new(devnet_event_tx.clone()));
let moved_cached_asset_class_ids_map = Arc::new(RwLock::new(asset_class_ids_map));
let config = Config {
port: port,
workers: 4,
address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)),
keep_alive: 5,
temp_dir: std::env::temp_dir(),
log_level: LogLevel::Off,
..Config::default()
};
let _ = std::thread::spawn(move || {
let future = rocket::custom(config)
.manage(moved_rw_lock)
.manage(moved_tx)
.manage(moved_cached_asset_class_ids_map)
.mount(
"/",
routes![
handle_new_burn_block,
handle_new_block,
handle_new_microblocks,
handle_new_mempool_tx,
handle_drop_mempool_tx,
],
)
.launch();
let rt = utils::create_basic_runtime();
rt.block_on(future).expect("Unable to spawn event observer");
});
loop {
match terminator_rx.recv() {
Ok(true) => {
devnet_event_tx
.send(DevnetEvent::info("Terminating event observer".into()))
.expect("Unable to terminate event observer");
break;
}
Ok(false) => {
// Restart
devnet_event_tx
.send(DevnetEvent::info("Reloading contracts".into()))
.expect("Unable to terminate event observer");
let session = match load_session(manifest_path.clone(), false, &Network::Devnet) {
Ok((session, _)) => session,
Err(e) => {
devnet_event_tx
.send(DevnetEvent::error(format!("Contracts invalid: {}", e)))
.expect("Unable to terminate event observer");
continue;
}
};
let contracts_to_deploy = VecDeque::from_iter(
session.settings.initial_contracts.iter().map(|c| c.clone()),
);
devnet_event_tx
.send(DevnetEvent::success(format!(
"{} contracts to deploy",
contracts_to_deploy.len()
)))
.expect("Unable to terminate event observer");
if let Ok(mut config_writer) = rw_lock.write() {
config_writer.contracts_to_deploy = contracts_to_deploy;
config_writer.session = session;
config_writer.deployer_nonce = 0;
}
}
Err(_) => {
break;
}
}
}
Ok(())
}
#[post("/new_burn_block", format = "json", data = "<new_burn_block>")]
pub fn handle_new_burn_block(
devnet_events_tx: &State<Arc<Mutex<Sender<DevnetEvent>>>>,
new_burn_block: Json<NewBurnBlock>,
) -> Json<JsonValue> {
let devnet_events_tx = devnet_events_tx.inner();
match devnet_events_tx.lock() {
Ok(tx) => {
let _ = tx.send(DevnetEvent::debug(format!(
"Bitcoin block #{} received",
new_burn_block.burn_block_height
)));
let _ = tx.send(DevnetEvent::ServiceStatus(ServiceStatusData {
order: 0,
status: Status::Green,
name: "bitcoin-node".into(),
comment: format!(
"mining blocks (chaintip = #{})",
new_burn_block.burn_block_height
),
}));
let _ = tx.send(DevnetEvent::BitcoinBlock(BitcoinBlockData {
block_identifier: BlockIdentifier {
hash: new_burn_block.burn_block_hash.clone(),
index: new_burn_block.burn_block_height,
},
parent_block_identifier: BlockIdentifier {
hash: "".into(), // todo(ludo): open a PR on stacks-blockchain to get this field.
index: new_burn_block.burn_block_height - 1,
},
timestamp: 0, // todo(ludo): open a PR on stacks-blockchain to get this field.
metadata: BitcoinBlockMetadata {},
transactions: vec![],
}));
}
_ => {}
};
Json(json!({
"status": 200,
"result": "Ok",
}))
}
#[post("/new_block", format = "application/json", data = "<new_block>")]
pub fn handle_new_block(
config: &State<Arc<RwLock<EventObserverConfig>>>,
devnet_events_tx: &State<Arc<Mutex<Sender<DevnetEvent>>>>,
asset_class_ids_map: &State<Arc<RwLock<HashMap<String, AssetClassCache>>>>,
new_block: Json<NewBlock>,
) -> Json<JsonValue> {
let devnet_events_tx = devnet_events_tx.inner();
let config = config.inner();
if let Ok(tx) = devnet_events_tx.lock() {
let _ = tx.send(DevnetEvent::ServiceStatus(ServiceStatusData {
order: 1,
status: Status::Green,
name: "stacks-node".into(),
comment: format!("mining blocks (chaintip = #{})", new_block.block_height),
}));
let _ = tx.send(DevnetEvent::info(format!(
"Block #{} anchored in Bitcoin block #{} includes {} transactions",
new_block.block_height,
new_block.burn_block_height,
new_block.transactions.len(),
)));
}
let (
updated_config,
first_burnchain_block_height,
prepare_phase_block_length,
reward_phase_block_length,
node,
) = if let Ok(config_reader) = config.read() {
let node = format!(
"http://localhost:{}",
config_reader.devnet_config.stacks_node_rpc_port
);
if config_reader.contracts_to_deploy.len() > 0 {
let mut updated_config = config_reader.clone();
// How many contracts left?
let contracts_left = updated_config.contracts_to_deploy.len();
let tx_chaining_limit = 25;
let blocks_required = 1 + (contracts_left / tx_chaining_limit);
let contracts_to_deploy_in_blocks = if blocks_required == 1 {
contracts_left
} else {
contracts_left / blocks_required
};
let mut contracts_to_deploy = vec![];
for _ in 0..contracts_to_deploy_in_blocks {
let contract = updated_config.contracts_to_deploy.pop_front().unwrap();
contracts_to_deploy.push(contract);
}
let node_clone = node.clone();
let mut deployers_lookup = BTreeMap::new();
for account in updated_config.session.settings.initial_accounts.iter() {
if account.name == "deployer" {
deployers_lookup.insert("*".into(), account.clone());
}
}
// TODO(ludo): one day, we will get rid of this shortcut
let mut deployers_nonces = BTreeMap::new();
deployers_nonces.insert("deployer".to_string(), config_reader.deployer_nonce);
updated_config.deployer_nonce += contracts_to_deploy.len() as u64;
if let Ok(tx) = devnet_events_tx.lock() {
let _ = tx.send(DevnetEvent::success(format!(
"Will broadcast {} transactions",
contracts_to_deploy.len()
)));
}
// Move the transactions submission to another thread, the clock on that thread is ticking,
// and blocking our stacks-node
std::thread::spawn(move || {
for contract in contracts_to_deploy.into_iter() {
match publish_contract(
&contract,
&deployers_lookup,
&mut deployers_nonces,
&node_clone,
1,
&Network::Devnet,
) {
Ok((_txid, _nonce)) => {
// let _ = tx_clone.send(DevnetEvent::success(format!(
// "Contract {} broadcasted in mempool (txid: {}, nonce: {})",
// contract.name.unwrap(), txid, nonce
// )));
}
Err(_err) => {
// let _ = tx_clone.send(DevnetEvent::error(err.to_string()));
break;
}
}
}
});
(
Some(updated_config),
config_reader.pox_info.first_burnchain_block_height,
config_reader.pox_info.prepare_phase_block_length,
config_reader.pox_info.reward_phase_block_length,
node,
)
} else {
(
None,
config_reader.pox_info.first_burnchain_block_height,
config_reader.pox_info.prepare_phase_block_length,
config_reader.pox_info.reward_phase_block_length,
node,
)
}
} else {
(None, 0, 0, 0, "".into())
};
if let Some(updated_config) = updated_config {
if let Ok(mut config_writer) = config.write() {
*config_writer = updated_config;
}
}
let pox_cycle_length: u64 = (prepare_phase_block_length + reward_phase_block_length).into();
let current_len = new_block.burn_block_height - first_burnchain_block_height;
let pox_cycle_id: u32 = (current_len / pox_cycle_length).try_into().unwrap();
let transactions = if let Ok(mut asset_class_ids_map) = asset_class_ids_map.inner().write() {
new_block
.transactions
.iter()
.map(|t| {
let description = get_tx_description(&t.raw_tx);
StacksTransactionData {
transaction_identifier: TransactionIdentifier {
hash: t.txid.clone(),
},
operations: get_standardized_stacks_operations(t, &mut asset_class_ids_map),
metadata: StacksTransactionMetadata {
success: t.status == "success",
result: get_value_description(&t.raw_result),
events: vec![],
description,
},
}
})
.collect()
} else {
vec![]
};
if let Ok(tx) = devnet_events_tx.lock() {
let _ = tx.send(DevnetEvent::StacksBlock(StacksBlockData {
block_identifier: BlockIdentifier {
hash: new_block.index_block_hash.clone(),
index: new_block.block_height,
},
parent_block_identifier: BlockIdentifier {
hash: new_block.parent_index_block_hash.clone(),
index: new_block.block_height,
},
timestamp: 0,
metadata: StacksBlockMetadata {
bitcoin_anchor_block_identifier: BlockIdentifier {
hash: new_block.burn_block_hash.clone(),
index: new_block.burn_block_height,
},
bitcoin_genesis_block_identifier: BlockIdentifier {
hash: "".into(),
index: first_burnchain_block_height,
},
pox_cycle_index: pox_cycle_id,
pox_cycle_length: pox_cycle_length.try_into().unwrap(),
},
transactions,
}));
}
// Every penultimate block, we check if some stacking orders should be submitted before the next
// cycle starts.
if new_block.burn_block_height % pox_cycle_length == (pox_cycle_length - 2) {
if let Ok(config_reader) = config.read() {
// let tx_clone = tx.clone();
let accounts = config_reader.accounts.clone();
let mut pox_info = config_reader.pox_info.clone();
let pox_stacking_orders = config_reader.devnet_config.pox_stacking_orders.clone();
std::thread::spawn(move || {
let pox_url = format!("{}/v2/pox", node);
if let Ok(reponse) = reqwest::blocking::get(pox_url) {
if let Ok(update) = reponse.json() {
pox_info = update
}
}
for pox_stacking_order in pox_stacking_orders.into_iter() {
if pox_stacking_order.start_at_cycle == (pox_cycle_id + 1) {
let account = match accounts.get(&pox_stacking_order.wallet) {
None => continue,
Some(account) => account,
};
let stacks_rpc = StacksRpc::new(node.clone());
let default_fee = 1000;
let nonce = stacks_rpc
.get_nonce(account.address.to_string())
.expect("Unable to retrieve nonce");
let stx_amount =
pox_info.next_cycle.min_threshold_ustx * pox_stacking_order.slots;
let (_, _, account_secret_keu) = types::compute_addresses(
&account.mnemonic,
&account.derivation,
account.is_mainnet,
);
let addr_bytes = pox_stacking_order
.btc_address
.from_base58()
.expect("Unable to get bytes from btc address");
let addr_bytes = Hash160::from_bytes(&addr_bytes[1..21]).unwrap();
let addr_version = AddressHashMode::SerializeP2PKH;
let stack_stx_tx = transactions::build_contrat_call_transaction(
pox_info.contract_id.clone(),
"stack-stx".into(),
vec![
ClarityValue::UInt(stx_amount.into()),
ClarityValue::Tuple(
TupleData::from_data(vec![
(
ClarityName::try_from("version".to_owned()).unwrap(),
ClarityValue::buff_from_byte(addr_version as u8),
),
(
ClarityName::try_from("hashbytes".to_owned()).unwrap(),
ClarityValue::Sequence(SequenceData::Buffer(
BuffData {
data: addr_bytes.as_bytes().to_vec(),
},
)),
),
])
.unwrap(),
),
ClarityValue::UInt((new_block.burn_block_height - 1).into()),
ClarityValue::UInt(pox_stacking_order.duration.into()),
],
nonce,
default_fee,
&hex_bytes(&account_secret_keu).unwrap(),
);
let _ = stacks_rpc
.post_transaction(stack_stx_tx)
.expect("Unable to broadcast transaction");
}
}
});
}
}
Json(json!({
"status": 200,
"result": "Ok",
}))
}
#[post(
"/new_microblocks",
format = "application/json",
data = "<new_microblock>"
)]
pub fn handle_new_microblocks(
_config: &State<Arc<RwLock<EventObserverConfig>>>,
devnet_events_tx: &State<Arc<Mutex<Sender<DevnetEvent>>>>,
new_microblock: Json<NewMicroBlock>,
) -> Json<JsonValue> {
let devnet_events_tx = devnet_events_tx.inner();
if let Ok(tx) = devnet_events_tx.lock() {
let _ = tx.send(DevnetEvent::info(format!(
"Microblock received including {} transactions",
new_microblock.transactions.len(),
)));
}
// let transactions = new_block
// .transactions
// .iter()
// .map(|t| {
// let description = get_tx_description(&t.raw_tx);
// StacksTransactionData {
// transaction_identifier: TransactionIdentifier {
// hash: t.txid.clone(),
// },
// metadata: {
// success: t.status == "success",
// result: get_value_description(&t.raw_result),
// events: vec![],
// description,
// }
// }
// })
// .collect();
Json(json!({
"status": 200,
"result": "Ok",
}))
}
#[post("/new_mempool_tx", format = "application/json", data = "<raw_txs>")]
pub fn handle_new_mempool_tx(
devnet_events_tx: &State<Arc<Mutex<Sender<DevnetEvent>>>>,
raw_txs: Json<Vec<String>>,
) -> Json<JsonValue> {
let decoded_transactions = raw_txs
.iter()
.map(|t| get_tx_description(t))
.collect::<Vec<String>>();
if let Ok(tx_sender) = devnet_events_tx.lock() {
for tx in decoded_transactions.into_iter() {
let _ = tx_sender.send(DevnetEvent::MempoolAdmission(MempoolAdmissionData { tx }));
}
}
Json(json!({
"status": 200,
"result": "Ok",
}))
}
#[post("/drop_mempool_tx", format = "application/json")]
pub fn handle_drop_mempool_tx() -> Json<JsonValue> {
Json(json!({
"status": 200,
"result": "Ok",
}))
}
fn get_value_description(raw_value: &str) -> String {
let raw_value = match raw_value.strip_prefix("0x") {
Some(raw_value) => raw_value,
_ => return raw_value.to_string(),
};
let value_bytes = match hex_bytes(&raw_value) {
Ok(bytes) => bytes,
_ => return raw_value.to_string(),
};
let value = match ClarityValue::consensus_deserialize(&mut Cursor::new(&value_bytes)) {
Ok(value) => format!("{}", value),
Err(e) => {
println!("{:?}", e);
return raw_value.to_string();
}
};
value
}
pub fn get_tx_description(raw_tx: &str) -> String {
let raw_tx = match raw_tx.strip_prefix("0x") {
Some(raw_tx) => raw_tx,
_ => return raw_tx.to_string(),
};
let tx_bytes = match hex_bytes(&raw_tx) {
Ok(bytes) => bytes,
_ => return raw_tx.to_string(),
};
let tx = match StacksTransaction::consensus_deserialize(&mut Cursor::new(&tx_bytes)) {
Ok(bytes) => bytes,
Err(e) => {
println!("{:?}", e);
return raw_tx.to_string();
}
};
let description = match tx.payload {
TransactionPayload::TokenTransfer(ref addr, ref amount, ref _memo) => {
format!(
"transfered: {} µSTX from {} to {}",
amount,
tx.origin_address(),
addr
)
}
TransactionPayload::ContractCall(ref contract_call) => {
let formatted_args = contract_call
.function_args
.iter()
.map(|v| format!("{}", v))
.collect::<Vec<String>>()
.join(", ");
format!(
"invoked: {}.{}::{}({})",
contract_call.address,
contract_call.contract_name,
contract_call.function_name,
formatted_args
)
}
TransactionPayload::SmartContract(ref smart_contract) => {
format!("deployed: {}.{}", tx.origin_address(), smart_contract.name)
}
_ => {
format!("coinbase")
}
};
description
}
fn get_standardized_stacks_operations(
transaction: &NewTransaction,
asset_class_cache: &mut HashMap<String, AssetClassCache>,
) -> Vec<Operation> {
let mut operations = vec![];
let mut operation_id = 0;
for event in transaction.events.iter() {
if let Some(ref event_data) = event.stx_mint_event {
let data: STXMintEventData =
serde_json::from_value(event_data.clone()).expect("Unable to decode event_data");
operations.push(Operation {
operation_identifier: OperationIdentifier {
index: operation_id,
network_index: None,
},
related_operations: None,
type_: OperationType::Credit,
status: Some(OperationStatusKind::Success),
account: AccountIdentifier {
address: data.recipient,
sub_account: None,
},
amount: Some(Amount {
value: data.amount,
currency: get_stacks_currency(),
}),
metadata: None,
});
operation_id += 1;
} else if let Some(ref event_data) = event.stx_lock_event {
let data: STXLockEventData =
serde_json::from_value(event_data.clone()).expect("Unable to decode event_data");
operations.push(Operation {
operation_identifier: OperationIdentifier {
index: operation_id,
network_index: None,
},
related_operations: None,
type_: OperationType::Lock,
status: Some(OperationStatusKind::Success),
account: AccountIdentifier {
address: data.locked_address,
sub_account: None,
},
amount: Some(Amount {
value: data.locked_amount,
currency: get_stacks_currency(),
}),
metadata: None,
});
operation_id += 1;
} else if let Some(ref event_data) = event.stx_burn_event {
let data: STXBurnEventData =
serde_json::from_value(event_data.clone()).expect("Unable to decode event_data");
operations.push(Operation {
operation_identifier: OperationIdentifier {
index: operation_id,
network_index: None,
},
related_operations: None,
type_: OperationType::Debit,
status: Some(OperationStatusKind::Success),
account: AccountIdentifier {
address: data.sender,
sub_account: None,
},
amount: Some(Amount {
value: data.amount,
currency: get_stacks_currency(),
}),
metadata: None,
});
operation_id += 1;
} else if let Some(ref event_data) = event.stx_transfer_event {
let data: STXTransferEventData =
serde_json::from_value(event_data.clone()).expect("Unable to decode event_data");
operations.push(Operation {
operation_identifier: OperationIdentifier {
index: operation_id,
network_index: None,
},
related_operations: Some(vec![OperationIdentifier {
index: operation_id + 1,
network_index: None,
}]),
type_: OperationType::Debit,
status: Some(OperationStatusKind::Success),
account: AccountIdentifier {
address: data.sender,
sub_account: None,
},
amount: Some(Amount {
value: data.amount,
currency: get_stacks_currency(),
}),
metadata: None,
});
operation_id += 1;
operations.push(Operation {
operation_identifier: OperationIdentifier {
index: operation_id,
network_index: None,
},
related_operations: Some(vec![OperationIdentifier {
index: operation_id - 1,
network_index: None,
}]),
type_: OperationType::Credit,
status: Some(OperationStatusKind::Success),
account: AccountIdentifier {
address: data.recipient,
sub_account: None,
},
amount: Some(Amount {
value: data.amount,
currency: get_stacks_currency(),
}),
metadata: None,
});
operation_id += 1;
} else if let Some(ref event_data) = event.nft_mint_event {
let data: NFTMintEventData =
serde_json::from_value(event_data.clone()).expect("Unable to decode event_data");
let currency = get_standardized_non_fungible_currency_from_asset_class_id(
&data.asset_class_identifier,
&data.asset_identifier,
asset_class_cache,
);
operations.push(Operation {
operation_identifier: OperationIdentifier {
index: operation_id,
network_index: None,
},
related_operations: None,
type_: OperationType::Credit,
status: Some(OperationStatusKind::Success),
account: AccountIdentifier {
address: data.recipient,
sub_account: None,
},
amount: Some(Amount { value: 1, currency }),
metadata: None,
});
operation_id += 1;
} else if let Some(ref event_data) = event.nft_burn_event {
let data: NFTBurnEventData =
serde_json::from_value(event_data.clone()).expect("Unable to decode event_data");
let currency = get_standardized_non_fungible_currency_from_asset_class_id(
&data.asset_class_identifier,
&data.asset_identifier,
asset_class_cache,
);
operations.push(Operation {
operation_identifier: OperationIdentifier {
index: operation_id,
network_index: None,
},
related_operations: None,
type_: OperationType::Debit,
status: Some(OperationStatusKind::Success),
account: AccountIdentifier {
address: data.sender,
sub_account: None,
},
amount: Some(Amount { value: 1, currency }),
metadata: None,
});
operation_id += 1;
} else if let Some(ref event_data) = event.nft_transfer_event {
let data: NFTTransferEventData =
serde_json::from_value(event_data.clone()).expect("Unable to decode event_data");
let currency = get_standardized_non_fungible_currency_from_asset_class_id(
&data.asset_class_identifier,
&data.asset_identifier,
asset_class_cache,
);
operations.push(Operation {
operation_identifier: OperationIdentifier {
index: operation_id,