forked from romanz/electrs
-
Notifications
You must be signed in to change notification settings - Fork 169
Expand file tree
/
Copy pathrest.rs
More file actions
1500 lines (1276 loc) · 54.1 KB
/
Copy pathrest.rs
File metadata and controls
1500 lines (1276 loc) · 54.1 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 bitcoin::hashes::{sha256, Hash};
use bitcoin::hex::FromHex;
use serde_json::Value;
use std::collections::HashSet;
use std::net;
#[cfg(feature = "liquid")]
use elementsd::bitcoincore_rpc::RpcApi;
#[cfg(not(feature = "liquid"))]
use {bitcoin::Amount, serde_json::from_value};
use electrs::chain::Txid;
pub mod common;
use common::Result;
fn get(
rest_addr: net::SocketAddr,
path: &str,
) -> std::result::Result<ureq::http::Response<ureq::Body>, ureq::Error> {
ureq::get(&format!("http://{}{}", rest_addr, path)).call()
}
fn get_json(rest_addr: net::SocketAddr, path: &str) -> Result<Value> {
Ok(get(rest_addr, path)?.into_body().read_json()?)
}
fn get_plain(rest_addr: net::SocketAddr, path: &str) -> Result<String> {
Ok(get(rest_addr, path)?.into_body().read_to_string()?)
}
#[test]
fn test_rest_tx() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
// Send transaction and confirm it
let addr1 = tester.newaddress()?;
let txid1_confirmed = tester.send(&addr1, "1.19123 BTC".parse().unwrap())?;
tester.mine()?;
let mine_height = tester.get_block_count()?;
// Send transaction and leave it unconfirmed
let txid2_mempool = tester.send(&addr1, "0.7113 BTC".parse().unwrap())?;
// Test GET /tx/:txid
let res = get_json(rest_addr, &format!("/tx/{}", txid1_confirmed))?;
log::debug!("tx: {:#?}", res);
// Verify TransactionValue fields with actual values
assert_eq!(
res["txid"].as_str(),
Some(txid1_confirmed.to_string().as_str())
);
assert_eq!(res["version"].as_u64(), Some(2));
assert!(res["locktime"].as_u64().is_some());
assert!(res["size"].as_u64().unwrap() > 0);
assert!(res["weight"].as_u64().unwrap() > 0);
assert!(res["fee"].as_u64().unwrap() > 0);
#[cfg(feature = "liquid")]
{
assert_eq!(res["discount_vsize"].as_u64().unwrap(), 228);
assert_eq!(res["discount_weight"].as_u64().unwrap(), 912);
}
// Verify status on the TransactionValue itself
assert_eq!(res["status"]["confirmed"].as_bool(), Some(true));
assert_eq!(res["status"]["block_height"].as_u64(), Some(mine_height));
assert!(res["status"]["block_hash"].is_string());
assert!(res["status"]["block_time"].as_u64().unwrap() > 0);
// Verify vout fields and find our target output
let outs = res["vout"].as_array().expect("array of outs");
assert!(outs.iter().any(|vout| {
vout["scriptpubkey_address"].as_str() == Some(&addr1.to_string())
&& vout["value"].as_u64() == Some(119123000)
}));
for vout in outs {
assert!(vout["scriptpubkey"].is_string());
assert!(vout["scriptpubkey_asm"].is_string());
assert!(vout["scriptpubkey_type"].is_string());
}
// Verify our target output's scriptpubkey_type (Bitcoin uses segwit address types)
#[cfg(not(feature = "liquid"))]
{
let target_vout = outs
.iter()
.find(|v| v["scriptpubkey_address"].as_str() == Some(&addr1.to_string()))
.unwrap();
let spk_type = target_vout["scriptpubkey_type"].as_str().unwrap();
assert!(
spk_type == "v0_p2wpkh" || spk_type == "v1_p2tr",
"unexpected scriptpubkey_type: {}",
spk_type
);
}
// Verify vin fields (non-coinbase input)
let vin0 = &res["vin"][0];
assert!(vin0["txid"].is_string());
assert!(vin0["vout"].is_u64());
assert_eq!(vin0["is_coinbase"].as_bool(), Some(false));
assert!(vin0["sequence"].as_u64().is_some());
assert!(vin0["scriptsig"].is_string());
assert!(vin0["scriptsig_asm"].is_string());
// prevout should be present for non-coinbase inputs
assert!(vin0["prevout"].is_object());
assert!(vin0["prevout"]["scriptpubkey"].is_string());
assert!(vin0["prevout"]["scriptpubkey_type"].is_string());
#[cfg(not(feature = "liquid"))]
assert!(vin0["prevout"]["value"].as_u64().unwrap() > 0);
// Verify coinbase tx input
let block_hash = res["status"]["block_hash"].as_str().unwrap();
let block_txs = get_json(rest_addr, &format!("/block/{}/txs", block_hash))?;
let coinbase_tx = &block_txs.as_array().unwrap()[0];
let cb_vin = &coinbase_tx["vin"][0];
assert_eq!(cb_vin["is_coinbase"].as_bool(), Some(true));
assert!(cb_vin["scriptsig"].is_string());
assert!(cb_vin["scriptsig_asm"].is_string());
assert!(cb_vin["prevout"].is_null());
// Test GET /tx/:txid/status (confirmed)
let res = get_json(rest_addr, &format!("/tx/{}/status", txid1_confirmed))?;
assert_eq!(res["confirmed"].as_bool(), Some(true));
assert_eq!(res["block_height"].as_u64(), Some(mine_height));
assert!(res["block_hash"].is_string());
assert!(res["block_time"].as_u64().unwrap() > 0);
// Test GET /tx/:txid/status (unconfirmed)
let res = get_json(rest_addr, &format!("/tx/{}/status", txid2_mempool))?;
assert_eq!(res["confirmed"].as_bool(), Some(false));
assert_eq!(res["block_height"].as_u64(), None);
assert!(res["block_hash"].is_null());
assert!(res["block_time"].is_null());
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_address() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let addr1 = tester.newaddress()?;
let txid1_confirmed = tester.send(&addr1, "1.19123 BTC".parse().unwrap())?;
tester.mine()?;
let txid2_mempool = tester.send(&addr1, "0.7113 BTC".parse().unwrap())?;
// Test GET /address/:address
let res = get_json(rest_addr, &format!("/address/{}", addr1))?;
assert_eq!(res["address"].as_str(), Some(addr1.to_string().as_str()));
// chain_stats: 1 confirmed funding tx, nothing spent
assert_eq!(res["chain_stats"]["tx_count"].as_u64(), Some(1));
assert_eq!(res["chain_stats"]["funded_txo_count"].as_u64(), Some(1));
assert_eq!(res["chain_stats"]["spent_txo_count"].as_u64(), Some(0));
#[cfg(not(feature = "liquid"))]
{
assert_eq!(
res["chain_stats"]["funded_txo_sum"].as_u64(),
Some(119123000)
);
assert_eq!(res["chain_stats"]["spent_txo_sum"].as_u64(), Some(0));
}
// mempool_stats: 1 unconfirmed funding tx; the wallet may also spend
// addr1's confirmed UTXO as an input, so spent_txo_count can be 0 or 1
assert!(res["mempool_stats"]["tx_count"].as_u64().unwrap() >= 1);
assert_eq!(res["mempool_stats"]["funded_txo_count"].as_u64(), Some(1));
assert!(res["mempool_stats"]["spent_txo_count"].is_u64());
#[cfg(not(feature = "liquid"))]
{
assert_eq!(
res["mempool_stats"]["funded_txo_sum"].as_u64(),
Some(71130000)
);
assert!(res["mempool_stats"]["spent_txo_sum"].is_u64());
}
// Test GET /address/:address/txs
let res = get_json(rest_addr, &format!("/address/{}/txs", addr1))?;
let txs = res.as_array().expect("array of transactions");
let mut txids = txs
.iter()
.map(|tx| tx["txid"].as_str().unwrap().parse().unwrap())
.collect::<HashSet<Txid>>();
assert!(txids.remove(&txid1_confirmed));
assert!(txids.remove(&txid2_mempool));
assert!(txids.is_empty());
// Test GET /address-prefix/:prefix
let addr1_prefix = &addr1.to_string()[0..8];
let res = get_json(rest_addr, &format!("/address-prefix/{}", addr1_prefix))?;
let found = res.as_array().expect("array of matching addresses");
assert_eq!(found.len(), 1);
assert_eq!(found[0].as_str(), Some(addr1.to_string().as_str()));
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_blocks() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
// Test GET /blocks/tip/hash
let bestblockhash = tester.get_best_block_hash()?;
let res = get_plain(rest_addr, "/blocks/tip/hash")?;
assert_eq!(res, bestblockhash.to_string());
let bestblockhash = tester.mine()?;
let res = get_plain(rest_addr, "/blocks/tip/hash")?;
assert_eq!(res, bestblockhash.to_string());
// Test GET /blocks/tip/height
let bestblockheight = tester.get_block_count()?;
let res = get_plain(rest_addr, "/blocks/tip/height")?;
assert_eq!(
res.parse::<u64>().expect("tip block height as an int"),
bestblockheight
);
// Test GET /block-height/:height
let res = get_plain(rest_addr, &format!("/block-height/{}", bestblockheight))?;
assert_eq!(res, bestblockhash.to_string());
// Test GET /blocks
let res = get_json(rest_addr, "/blocks")?;
let last_blocks = res.as_array().unwrap();
assert_eq!(last_blocks.len(), 10); // limited to 10 per page
assert_eq!(
last_blocks[0]["id"].as_str(),
Some(bestblockhash.to_string().as_str())
);
// Verify first block (tip) has correct height
assert_eq!(
last_blocks[0]["height"].as_u64(),
Some(bestblockheight)
);
// Verify block list entries have all BlockValue fields with value checks
for block in last_blocks {
assert!(block["id"].is_string());
assert!(block["height"].is_u64());
assert!(block["version"].is_u64());
assert!(block["timestamp"].as_u64().unwrap() > 0);
assert!(block["tx_count"].as_u64().unwrap() >= 1); // coinbase at minimum
assert!(block["size"].as_u64().unwrap() > 0);
assert!(block["weight"].as_u64().unwrap() > 0);
assert!(block["merkle_root"].is_string());
assert!(block["mediantime"].as_u64().unwrap() > 0);
#[cfg(not(feature = "liquid"))]
{
assert!(block["nonce"].is_u64());
assert!(block["bits"].is_u64());
assert!(block["difficulty"].is_f64());
}
}
// Verify previousblockhash links blocks together correctly
for i in 0..last_blocks.len() - 1 {
assert_eq!(
last_blocks[i]["previousblockhash"].as_str(),
last_blocks[i + 1]["id"].as_str()
);
}
let bestblockhash = tester.mine()?;
let res = get_json(rest_addr, "/blocks")?;
let last_blocks = res.as_array().unwrap();
assert_eq!(
last_blocks[0]["id"].as_str(),
Some(bestblockhash.to_string().as_str())
);
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_block() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let addr1 = tester.newaddress()?;
// Test GET /block/:hash
let txid = tester.send(&addr1, "0.98765432 BTC".parse().unwrap())?;
let blockhash = tester.mine()?;
let res = get_json(rest_addr, &format!("/block/{}", blockhash))?;
assert_eq!(res["id"].as_str(), Some(blockhash.to_string().as_str()));
assert_eq!(res["height"].as_u64(), Some(tester.get_block_count()?));
assert_eq!(res["tx_count"].as_u64(), Some(2));
// Cross-reference BlockValue fields against bitcoind's getblockheader
let node_header: Value = tester
.node_client()
.call("getblockheader", &[blockhash.to_string().into()])?;
assert_eq!(res["version"].as_u64(), node_header["version"].as_u64());
assert_eq!(res["timestamp"].as_u64(), node_header["time"].as_u64());
assert_eq!(
res["merkle_root"].as_str(),
node_header["merkleroot"].as_str()
);
assert_eq!(
res["previousblockhash"].as_str(),
node_header["previousblockhash"].as_str()
);
assert_eq!(res["mediantime"].as_u64(), node_header["mediantime"].as_u64());
assert!(res["size"].as_u64().unwrap() > 0);
assert!(res["weight"].as_u64().unwrap() > 0);
#[cfg(not(feature = "liquid"))]
{
assert_eq!(res["nonce"].as_u64(), node_header["nonce"].as_u64());
// bits is serialized differently (compact target int vs hex string), just check presence
assert!(res["bits"].is_u64());
assert!(res["difficulty"].is_f64());
}
// Test GET /block/:hash/raw
let rest_rawblock = get(rest_addr, &format!("/block/{}/raw", blockhash))?
.into_body()
.read_to_vec()?;
let node_hexblock = // uses low-level call() to support Elements
tester.node_client().call::<String>("getblock", &[blockhash.to_string().into(), 0.into()])?;
assert_eq!(rest_rawblock, Vec::from_hex(&node_hexblock).unwrap());
// Test GET /block/:hash/txid/:index
let res = get_plain(rest_addr, &format!("/block/{}/txid/1", blockhash))?;
assert_eq!(res, txid.to_string());
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_block_txs() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let addr1 = tester.newaddress()?;
let txid = tester.send(&addr1, "0.98765432 BTC".parse().unwrap())?;
let blockhash = tester.mine()?;
// Test GET /block/:hash/txs
let res = get_json(rest_addr, &format!("/block/{}/txs", blockhash))?;
let block_txs = res.as_array().expect("list of txs");
assert_eq!(block_txs.len(), 2);
assert_eq!(block_txs[0]["vin"][0]["is_coinbase"].as_bool(), Some(true));
assert_eq!(
block_txs[1]["txid"].as_str(),
Some(txid.to_string().as_str())
);
// Test GET /block/:hash/txs/:index
let res = get_json(rest_addr, &format!("/block/{}/txs/0", blockhash))?;
let block_txs = res.as_array().expect("list of txs");
assert_eq!(block_txs.len(), 2);
assert_eq!(block_txs[0]["vin"][0]["is_coinbase"].as_bool(), Some(true));
assert_eq!(
block_txs[1]["txid"].as_str(),
Some(txid.to_string().as_str())
);
// Test GET /block/:hash/txs/:index
// Should fail with 404 code when block isn't found
let invalid_resp = ureq::get(&format!("http://{}/block/{}/txs/0", rest_addr, "0000000000000000000000000000000000000000000000000000000000000000"))
.config()
.http_status_as_error(false)
.build()
.call()?;
assert_eq!(invalid_resp.status(), 404);
assert_eq!(invalid_resp.into_body().read_to_string()?, "Block not found");
// Test GET /block/:hash/txs/:index
// Should fail with 400 code when block hash is invalid
let invalid_resp = ureq::get(&format!("http://{}/block/{}/txs/0", rest_addr, "invalid_hash"))
.config()
.http_status_as_error(false)
.build()
.call()?;
assert_eq!(invalid_resp.status(), 400);
assert_eq!(invalid_resp.into_body().read_to_string()?, "Invalid hex string");
// Test GET /block/:hash/txs/:index
// Should fail with 400 code when `(index % 25) != 0`
let invalid_hash_resp = ureq::get(&format!("http://{}/block/{}/txs/1", rest_addr, blockhash))
.config()
.http_status_as_error(false)
.build()
.call()?;
assert_eq!(invalid_hash_resp.status(), 400);
assert_eq!(invalid_hash_resp.into_body().read_to_string()?, "start index must be a multiple of 25");
// Test GET /block/:hash/txs/:index
// Should fail with 400 code when index is out of range
let invalid_hash_resp = ureq::get(&format!("http://{}/block/{}/txs/25", rest_addr, blockhash))
.config()
.http_status_as_error(false)
.build()
.call()?;
assert_eq!(invalid_hash_resp.status(), 400);
assert_eq!(invalid_hash_resp.into_body().read_to_string()?, "start index out of range");
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_mempool() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let addr1 = tester.newaddress()?;
// Test GET /mempool/txids
let txid = tester.send(&addr1, "3.21 BTC".parse().unwrap())?;
let res = get_json(rest_addr, "/mempool/txids")?;
let mempool_txids = res.as_array().expect("list of txids");
assert_eq!(mempool_txids.len(), 1);
assert_eq!(mempool_txids[0].as_str(), Some(txid.to_string().as_str()));
tester.send(&addr1, "0.0001 BTC".parse().unwrap())?;
let res = get_json(rest_addr, "/mempool/txids")?;
let mempool_txids = res.as_array().expect("list of txids");
assert_eq!(mempool_txids.len(), 2);
// Test GET /mempool
let mempool_stats = get_json(rest_addr, "/mempool")?;
assert_eq!(mempool_stats["count"].as_u64(), Some(2));
assert!(mempool_stats["vsize"].as_u64().unwrap() > 0);
assert!(mempool_stats["total_fee"].as_u64().unwrap() > 0);
assert!(mempool_stats["fee_histogram"].is_array());
tester.send(&addr1, "0.00022 BTC".parse().unwrap())?;
assert_eq!(get_json(rest_addr, "/mempool")?["count"].as_u64(), Some(3));
tester.mine()?;
let mempool_after = get_json(rest_addr, "/mempool")?;
assert_eq!(mempool_after["count"].as_u64(), Some(0));
assert_eq!(mempool_after["vsize"].as_u64(), Some(0));
assert_eq!(mempool_after["total_fee"].as_u64(), Some(0));
assert_eq!(
mempool_after["fee_histogram"].as_array().unwrap().len(),
0
);
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_broadcast_tx() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let addr1 = tester.newaddress()?;
// Test POST /tx
let txid = tester.send(&addr1, "9.9 BTC".parse().unwrap())?;
let tx_hex = get_plain(rest_addr, &format!("/tx/{}/hex", txid))?;
// Re-send the tx created by send(). It'll be accepted again since its still in the mempool.
let broadcast1_resp = ureq::post(&format!("http://{}/tx", rest_addr)).send(&tx_hex)?;
assert_eq!(broadcast1_resp.status(), 200);
assert_eq!(
broadcast1_resp.into_body().read_to_string()?,
txid.to_string()
);
// Mine the tx then submit it again. Should now fail.
tester.mine()?;
let broadcast2_resp = ureq::post(&format!("http://{}/tx", rest_addr))
.config()
.http_status_as_error(false)
.build()
.send(&tx_hex)?;
assert_eq!(broadcast2_resp.status(), 400);
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_package_validation() -> Result<()> {
let (rest_handle, rest_addr, _tester) = common::init_rest_tester().unwrap();
// Test POST /txs/package - simple validation test
// Test with invalid JSON first to verify the endpoint exists
let invalid_package_resp = ureq::post(&format!("http://{}/txs/package", rest_addr))
.header("Content-Type", "application/json")
.config()
.http_status_as_error(false)
.build()
.send("invalid json")?;
// Should be 400 for bad JSON, not 404 for missing endpoint
assert_eq!(
invalid_package_resp.status(),
400,
"Endpoint should exist and return 400 for invalid JSON"
);
// Now test with valid but empty package, should fail
let empty_package_resp = ureq::post(&format!("http://{}/txs/package", rest_addr))
.header("Content-Type", "application/json")
.config()
.http_status_as_error(false)
.build()
.send("[]")?;
assert_eq!(empty_package_resp.status(), 400);
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_block_status() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let addr1 = tester.newaddress()?;
tester.send(&addr1, "0.5 BTC".parse().unwrap())?;
let blockhash1 = tester.mine()?;
let blockhash2 = tester.mine()?; // tip
let block_count = tester.get_block_count()?;
// Non-tip block should have next_best pointing to next block
let res = get_json(rest_addr, &format!("/block/{}/status", blockhash1))?;
assert_eq!(res["in_best_chain"].as_bool(), Some(true));
assert_eq!(res["height"].as_u64(), Some(block_count - 1));
assert_eq!(
res["next_best"].as_str(),
Some(blockhash2.to_string().as_str())
);
// Tip block should have next_best as null
let res = get_json(rest_addr, &format!("/block/{}/status", blockhash2))?;
assert_eq!(res["in_best_chain"].as_bool(), Some(true));
assert_eq!(res["height"].as_u64(), Some(block_count));
assert!(res["next_best"].is_null());
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_block_txids() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let addr1 = tester.newaddress()?;
let txid = tester.send(&addr1, "0.5 BTC".parse().unwrap())?;
let blockhash = tester.mine()?;
let res = get_json(rest_addr, &format!("/block/{}/txids", blockhash))?;
let txids = res.as_array().expect("array of txids");
// Should match tx_count from /block/:hash
let block = get_json(rest_addr, &format!("/block/{}", blockhash))?;
assert_eq!(txids.len(), block["tx_count"].as_u64().unwrap() as usize);
// First txid should be the coinbase (not our user txid)
assert_ne!(
txids[0].as_str(),
Some(txid.to_string().as_str()),
"first txid should be coinbase, not user tx"
);
// Our txid should be present
assert!(txids
.iter()
.any(|t| t.as_str() == Some(&txid.to_string())));
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_block_header() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let blockhash = tester.mine()?;
let header_hex = get_plain(rest_addr, &format!("/block/{}/header", blockhash))?;
// Verify it's valid hex
let header_bytes = Vec::from_hex(&header_hex).expect("valid hex");
assert!(!header_bytes.is_empty());
// On Bitcoin, verify the header is 80 bytes and its hash matches the block hash
#[cfg(not(feature = "liquid"))]
{
assert_eq!(header_bytes.len(), 80);
let header: bitcoin::block::Header =
bitcoin::consensus::deserialize(&header_bytes).expect("valid header");
assert_eq!(header.block_hash().to_string(), blockhash.to_string());
}
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_address_mempool_txs() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let addr1 = tester.newaddress()?;
// Send tx to address but don't mine
let txid = tester.send(&addr1, "0.5 BTC".parse().unwrap())?;
// Verify it appears in mempool txs
let res = get_json(rest_addr, &format!("/address/{}/txs/mempool", addr1))?;
let txs = res.as_array().expect("array of txs");
assert_eq!(txs.len(), 1);
assert_eq!(txs[0]["txid"].as_str(), Some(txid.to_string().as_str()));
assert_eq!(txs[0]["status"]["confirmed"].as_bool(), Some(false));
assert!(txs[0]["fee"].as_u64().unwrap() > 0);
// Mine and verify mempool list is now empty
tester.mine()?;
let res = get_json(rest_addr, &format!("/address/{}/txs/mempool", addr1))?;
let txs = res.as_array().expect("array of txs");
assert!(txs.is_empty());
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_address_utxo() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let addr1 = tester.newaddress()?;
// Send to address and mine - verify confirmed UTXO
let sent_txid = tester.send(&addr1, "0.5 BTC".parse().unwrap())?;
tester.mine()?;
let mine_height = tester.get_block_count()?;
let res = get_json(rest_addr, &format!("/address/{}/utxo", addr1))?;
let utxos = res.as_array().expect("array of utxos");
assert_eq!(utxos.len(), 1);
assert_eq!(
utxos[0]["txid"].as_str(),
Some(sent_txid.to_string().as_str())
);
assert!(utxos[0]["vout"].is_u64());
assert_eq!(utxos[0]["status"]["confirmed"].as_bool(), Some(true));
assert_eq!(utxos[0]["status"]["block_height"].as_u64(), Some(mine_height));
assert!(utxos[0]["status"]["block_hash"].is_string());
assert!(utxos[0]["status"]["block_time"].as_u64().unwrap() > 0);
#[cfg(not(feature = "liquid"))]
assert_eq!(utxos[0]["value"].as_u64(), Some(50000000));
// Send again without mining - the wallet may spend the existing UTXO as input,
// so we just verify that UTXOs exist and have correct fields
tester.send(&addr1, "0.3 BTC".parse().unwrap())?;
let res = get_json(rest_addr, &format!("/address/{}/utxo", addr1))?;
let utxos = res.as_array().expect("array of utxos");
assert!(!utxos.is_empty());
for utxo in utxos {
assert!(utxo["txid"].is_string());
assert!(utxo["vout"].is_u64());
assert!(utxo["status"].is_object());
assert!(utxo["status"]["confirmed"].is_boolean());
}
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_scripthash() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let addr1 = tester.newaddress()?;
tester.send(&addr1, "0.5 BTC".parse().unwrap())?;
tester.mine()?;
tester.send(&addr1, "0.3 BTC".parse().unwrap())?; // mempool tx
// Get the scriptpubkey from a tx to addr1
let addr_txs = get_json(rest_addr, &format!("/address/{}/txs", addr1))?;
let txs = addr_txs.as_array().unwrap();
let vout = txs[0]["vout"]
.as_array()
.unwrap()
.iter()
.find(|v| v["scriptpubkey_address"].as_str() == Some(&addr1.to_string()))
.expect("vout to our address");
let scriptpubkey_hex = vout["scriptpubkey"].as_str().unwrap();
let scriptpubkey_bytes = Vec::from_hex(scriptpubkey_hex).unwrap();
// Compute scripthash (SHA256 of scriptpubkey bytes)
let scripthash = sha256::Hash::hash(&scriptpubkey_bytes).to_string();
// Verify /scripthash/:hash matches /address/:address
// (the top-level objects differ by "address" vs "scripthash" key, so compare stats)
let addr_stats = get_json(rest_addr, &format!("/address/{}", addr1))?;
let sh_stats = get_json(rest_addr, &format!("/scripthash/{}", scripthash))?;
assert_eq!(addr_stats["chain_stats"], sh_stats["chain_stats"]);
assert_eq!(addr_stats["mempool_stats"], sh_stats["mempool_stats"]);
// Verify /scripthash/:hash/txs matches /address/:address/txs
let addr_txs = get_json(rest_addr, &format!("/address/{}/txs", addr1))?;
let sh_txs = get_json(rest_addr, &format!("/scripthash/{}/txs", scripthash))?;
assert_eq!(addr_txs, sh_txs);
// Verify /scripthash/:hash/txs/chain matches /address/:address/txs/chain
let addr_chain = get_json(rest_addr, &format!("/address/{}/txs/chain", addr1))?;
let sh_chain = get_json(rest_addr, &format!("/scripthash/{}/txs/chain", scripthash))?;
assert_eq!(addr_chain, sh_chain);
// Verify /scripthash/:hash/txs/mempool matches /address/:address/txs/mempool
let addr_mempool = get_json(rest_addr, &format!("/address/{}/txs/mempool", addr1))?;
let sh_mempool = get_json(rest_addr, &format!("/scripthash/{}/txs/mempool", scripthash))?;
assert_eq!(addr_mempool, sh_mempool);
// Verify /scripthash/:hash/utxo matches /address/:address/utxo
let addr_utxo = get_json(rest_addr, &format!("/address/{}/utxo", addr1))?;
let sh_utxo = get_json(rest_addr, &format!("/scripthash/{}/utxo", scripthash))?;
assert_eq!(addr_utxo, sh_utxo);
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_tx_outspends() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let addr1 = tester.newaddress()?;
let txid = tester.send(&addr1, "0.5 BTC".parse().unwrap())?;
tester.mine()?;
let mine_height = tester.get_block_count()?;
// Check outspends of a freshly mined tx - outputs should be unspent
let res = get_json(rest_addr, &format!("/tx/{}/outspends", txid))?;
let outspends = res.as_array().expect("array of outspends");
assert!(!outspends.is_empty());
for outspend in outspends {
assert_eq!(outspend["spent"].as_bool(), Some(false));
assert!(outspend["txid"].is_null());
assert!(outspend["vin"].is_null());
assert!(outspend["status"].is_null());
}
// The send tx spent some input. Check that the parent tx shows a spent output.
let tx_detail = get_json(rest_addr, &format!("/tx/{}", txid))?;
let spent_txid = tx_detail["vin"][0]["txid"].as_str().unwrap();
let spent_vout = tx_detail["vin"][0]["vout"].as_u64().unwrap();
let spent_vin = 0u64; // our tx is the spender, using vin index 0
let res = get_json(rest_addr, &format!("/tx/{}/outspends", spent_txid))?;
let outspends = res.as_array().expect("array of outspends");
let spent_entry = &outspends[spent_vout as usize];
assert_eq!(spent_entry["spent"].as_bool(), Some(true));
assert_eq!(
spent_entry["txid"].as_str(),
Some(txid.to_string().as_str())
);
assert_eq!(spent_entry["vin"].as_u64(), Some(spent_vin));
assert_eq!(spent_entry["status"]["confirmed"].as_bool(), Some(true));
assert_eq!(spent_entry["status"]["block_height"].as_u64(), Some(mine_height));
assert!(spent_entry["status"]["block_hash"].is_string());
assert!(spent_entry["status"]["block_time"].as_u64().unwrap() > 0);
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_tx_merkle_proof() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let addr1 = tester.newaddress()?;
let txid = tester.send(&addr1, "0.5 BTC".parse().unwrap())?;
tester.mine()?;
let mine_height = tester.get_block_count()?;
let res = get_json(rest_addr, &format!("/tx/{}/merkle-proof", txid))?;
assert_eq!(res["block_height"].as_u64(), Some(mine_height));
let merkle = res["merkle"].as_array().expect("merkle array");
assert!(!merkle.is_empty());
for entry in merkle {
let hex = entry.as_str().expect("merkle entry is string");
assert_eq!(hex.len(), 64, "merkle hash should be 64 hex chars");
assert!(
hex.chars().all(|c| c.is_ascii_hexdigit()),
"merkle hash should be valid hex"
);
}
assert!(res["pos"].as_u64().is_some());
rest_handle.stop();
Ok(())
}
#[cfg(not(feature = "liquid"))]
#[test]
fn test_rest_tx_merkleblock_proof() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let addr1 = tester.newaddress()?;
let txid = tester.send(&addr1, "0.5 BTC".parse().unwrap())?;
tester.mine()?;
let hex = get_plain(rest_addr, &format!("/tx/{}/merkleblock-proof", txid))?;
assert!(!hex.is_empty());
// Verify it's valid hex
let bytes = Vec::from_hex(&hex).expect("valid hex");
assert!(!bytes.is_empty());
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_mempool_recent() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let addr1 = tester.newaddress()?;
let txid1 = tester.send(&addr1, "0.5 BTC".parse().unwrap())?;
let txid2 = tester.send(&addr1, "0.3 BTC".parse().unwrap())?;
let res = get_json(rest_addr, "/mempool/recent")?;
let recent = res.as_array().expect("array of recent txs");
assert!(recent.len() >= 2);
for entry in recent {
assert!(entry["txid"].is_string());
assert!(entry["fee"].as_u64().unwrap() > 0);
assert!(entry["vsize"].as_u64().unwrap() > 0);
#[cfg(not(feature = "liquid"))]
assert!(entry["value"].as_u64().unwrap() > 0);
}
// Verify our sent txids are included
let recent_txids: HashSet<&str> = recent
.iter()
.map(|e| e["txid"].as_str().unwrap())
.collect();
assert!(recent_txids.contains(txid1.to_string().as_str()));
assert!(recent_txids.contains(txid2.to_string().as_str()));
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_fee_estimates() -> Result<()> {
let (rest_handle, rest_addr, _tester) = common::init_rest_tester().unwrap();
let res = get_json(rest_addr, "/fee-estimates")?;
// On regtest, may be empty but should be a JSON object
assert!(res.is_object());
rest_handle.stop();
Ok(())
}
#[test]
fn test_rest_broadcast_get() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let addr1 = tester.newaddress()?;
let txid = tester.send(&addr1, "0.5 BTC".parse().unwrap())?;
let tx_hex = get_plain(rest_addr, &format!("/tx/{}/hex", txid))?;
// Re-send via GET /broadcast?tx=:txhex (legacy endpoint)
let res = get_plain(rest_addr, &format!("/broadcast?tx={}", tx_hex))?;
assert_eq!(res, txid.to_string());
rest_handle.stop();
Ok(())
}
#[cfg(not(feature = "liquid"))]
#[test]
fn test_rest_reorg() -> Result<()> {
let (rest_handle, rest_addr, mut tester) = common::init_rest_tester().unwrap();
let get_conf_height = |txid| -> Result<Option<u64>> {
Ok(get_json(rest_addr, &format!("/tx/{}/status", txid))?["block_height"].as_u64())
};
let get_chain_stats = |addr| -> Result<Value> {
Ok(get_json(rest_addr, &format!("/address/{}", addr))?["chain_stats"].take())
};
let get_chain_txs = |addr| -> Result<Vec<Value>> {
Ok(from_value(get_json(
rest_addr,
&format!("/address/{}/txs/chain", addr),
)?)?)
};
let get_outspend = |outpoint: &bitcoin::OutPoint| -> Result<Value> {
get_json(
rest_addr,
&format!("/tx/{}/outspend/{}", outpoint.txid, outpoint.vout),
)
};
let init_height = tester.get_block_count()?;
let address = tester.newaddress()?;
let miner_address = tester.newaddress()?;
let txid_a = tester.send(&address, Amount::from_sat(100000))?;
let txid_b = tester.send(&address, Amount::from_sat(200000))?;
let txid_c = tester.send(&address, Amount::from_sat(500000))?;
let tx_a = tester.get_raw_transaction(txid_a)?;
let tx_b = tester.get_raw_transaction(txid_b)?;
let tx_c = tester.get_raw_transaction(txid_c)?;
// Confirm tx_a, tx_b and tx_c
let blockhash_1 = tester.mine()?;
assert_eq!(
get_plain(rest_addr, "/blocks/tip/height")?,
(init_height + 1).to_string()
);
assert_eq!(
get_plain(rest_addr, "/blocks/tip/hash")?,
blockhash_1.to_string()
);
assert_eq!(get_conf_height(&txid_a)?, Some(init_height + 1));
assert_eq!(get_conf_height(&txid_b)?, Some(init_height + 1));
assert_eq!(get_conf_height(&txid_c)?, Some(init_height + 1));
assert_eq!(
get_chain_stats(&address)?["funded_txo_sum"].as_u64(),
Some(800000)
);
assert_eq!(get_chain_txs(&address)?.len(), 3);
let c_outspend = get_outspend(&tx_c.input[0].previous_output)?;
assert_eq!(
c_outspend["txid"].as_str(),
Some(txid_c.to_string().as_str())
);
assert_eq!(
c_outspend["status"]["block_height"].as_u64(),
Some(init_height + 1)
);
// Reorg the last block, re-confirm tx_a at the same height
tester.node_client().invalidate_block(blockhash_1)?;
tester.node_client().call::<Value>(
"generateblock",
&[
miner_address.to_string().into(),
[txid_a.to_string()].into(),
],
)?;
// Re-confirm tx_b at a different height
tester.node_client().call::<Value>(
"generateblock",
&[
miner_address.to_string().into(),
[txid_b.to_string()].into(),
],
)?;
// Don't re-confirm tx_c at all
let blockhash_2 = tester.get_best_block_hash()?;
tester.sync()?;
assert_eq!(
get_plain(rest_addr, "/blocks/tip/height")?,
(init_height + 2).to_string()
);
assert_eq!(
get_plain(rest_addr, "/blocks/tip/hash")?,
blockhash_2.to_string()
);
// Test address stats (GET /address/:address)
assert_eq!(
get_chain_stats(&address)?["funded_txo_sum"].as_u64(),
Some(300000)
);
// Test address history (GET /address/:address/txs/chain)
let addr_txs = get_chain_txs(&address)?;
assert_eq!(addr_txs.len(), 2);
assert_eq!(
addr_txs[0]["txid"].as_str(),
Some(txid_b.to_string().as_str())
);
assert_eq!(
addr_txs[0]["status"]["block_height"].as_u64(),
Some(init_height + 2)
);
assert_eq!(
addr_txs[1]["txid"].as_str(),
Some(txid_a.to_string().as_str())
);
assert_eq!(
addr_txs[1]["status"]["block_height"].as_u64(),
Some(init_height + 1)
);
// Test transaction status lookup (GET /tx/:txid/status)
assert_eq!(get_conf_height(&txid_a)?, Some(init_height + 1));
assert_eq!(get_conf_height(&txid_b)?, Some(init_height + 2));