-
Notifications
You must be signed in to change notification settings - Fork 122
/
spv_rpc.cpp
1618 lines (1375 loc) · 61.1 KB
/
spv_rpc.cpp
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
// Copyright (c) DeFi Blockchain Developers
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
#include <base58.h>
#include <chainparams.h>
#include <core_io.h>
#include <rpc/server.h>
#include <rpc/protocol.h>
#include <rpc/util.h>
#include <masternodes/anchors.h>
#include <masternodes/mn_rpc.h>
#include <spv/btctransaction.h>
#include <spv/spv_wrapper.h>
#include <univalue/include/univalue.h>
//#ifdef ENABLE_WALLET
#include <wallet/rpcwallet.h>
#include <wallet/wallet.h>
//#endif
#include <stdexcept>
#include <future>
// Minimum allowed block count in HTLC contract
const uint32_t HTLC_MINIMUM_BLOCK_COUNT{9};
UniValue spv_sendrawtx(const JSONRPCRequest& request)
{
RPCHelpMan{"spv_sendrawtx",
"\nSending raw tx to Bitcoin blockchain\n",
{
{"rawtx", RPCArg::Type::STR, RPCArg::Optional::NO, "The hex-encoded raw transaction with signature" },
},
RPCResult{
"\"none\" Returns nothing\n"
},
RPCExamples{
HelpExampleCli("spv_sendrawtx", "\"rawtx\"")
+ HelpExampleRpc("spv_sendrawtx", "\"rawtx\"")
},
}.Check(request);
if (!spv::pspv)
throw JSONRPCError(RPC_INVALID_REQUEST, "spv module disabled");
std::promise<int> promise;
if (spv::pspv->SendRawTx(ParseHexV(request.params[0], "rawtx"), &promise)) {
int sendResult = promise.get_future().get();
if (sendResult != 0)
throw JSONRPCError(RPC_INVALID_REQUEST, DecodeSendResult(sendResult));
}
else {
throw JSONRPCError(RPC_INVALID_REQUEST, "Can't parse transaction");
}
return UniValue("");
}
extern CAmount GetAnchorSubsidy(int anchorHeight, int prevAnchorHeight, const Consensus::Params& consensusParams);
/*
* Create, sign and send (optional) anchor tx using only spv api
* Issued by: any
*/
UniValue spv_createanchor(const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWallet(request);
RPCHelpMan{"spv_createanchor",
"\nCreates (and optional submits to bitcoin blockchain) an anchor tx with latest possible (every 15th) authorized blockhash.\n"
"The first argument is the specific UTXOs to spend." +
HelpRequiringPassphrase(pwallet) + "\n",
{
{"inputs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "A json array of json objects",
{
{"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
{
{"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id of the bitcoin UTXO to spend"},
{"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output index to spend in UTXO"},
{"amount", RPCArg::Type::NUM, RPCArg::Optional::NO, "Amount of output in satoshis"},
{"privkey", RPCArg::Type::STR, RPCArg::Optional::NO, "WIF private key of bitcoin for signing this output"},
},
},
},
},
{"rewardAddress", RPCArg::Type::STR, RPCArg::Optional::NO, "User's P2PKH address (in DeFi chain) for reward"},
{"send", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED, "Send it to btc network (Default = true)"},
{"feerate", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "Feerate (satoshis) per 1000 bytes (Default = " + std::to_string(spv::DEFAULT_BTC_FEERATE) + ")"},
},
RPCResult{
"\"txHex\" (string) The hex-encoded raw transaction with signature(s)\n"
"\"txHash\" (string) The hex-encoded transaction hash\n"
},
RPCExamples{
HelpExampleCli("spv_createanchor", "\"[{\\\"txid\\\":\\\"id\\\",\\\"vout\\\":0,\\\"amount\\\":10000,\\\"privkey\\\":\\\"WIFprivkey\\\"}]\" "
"\\\"rewardAddress\\\" True 2000"
)
+ HelpExampleRpc("spv_createanchor", "\"[{\\\"txid\\\":\\\"id\\\",\\\"vout\\\":0,\\\"amount\\\":10000,\\\"privkey\\\":\\\"WIFprivkey\\\"}]\" "
"\\\"rewardAddress\\\" True 2000"
)
},
}.Check(request);
if (!spv::pspv)
throw JSONRPCError(RPC_INVALID_REQUEST, "spv module disabled");
if (pwallet->chain().isInitialBlockDownload()) {
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Cannot create anchor while still in Initial Block Download");
}
RPCTypeCheck(request.params, { UniValue::VARR, UniValue::VSTR, UniValue::VBOOL }, true);
if (request.params[0].isNull() || request.params[1].isNull())
{
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameters, arguments 1 and 2 must be non-null");
}
const UniValue inputs = request.params[0].get_array();
if (inputs.empty())
{
throw JSONRPCError(RPC_INVALID_PARAMETER, "Transaction input cannot be empty");
}
std::vector<spv::TxInputData> inputsData;
for (size_t idx = 0; idx < inputs.size(); ++idx)
{
UniValue const & input = inputs[idx].get_obj();
ParseHashV(input["txid"], "txid");
inputsData.push_back({ input["txid"].getValStr(), input["vout"].get_int(), (uint64_t) input["amount"].get_int64(), input["privkey"].getValStr() });
}
std::string rewardAddress = request.params[1].getValStr();
CTxDestination rewardDest = DecodeDestination(rewardAddress);
if (rewardDest.which() != 1 && rewardDest.which() != 4)
{
throw JSONRPCError(RPC_INVALID_PARAMETER, "rewardAddress (" + rewardAddress + ") does not refer to a P2PKH or P2WPKH address");
}
bool const send = request.params[2].isNull() ? true : request.params[2].getBool();
int64_t const feerate = request.params[3].isNull() ? spv::DEFAULT_BTC_FEERATE : request.params[3].get_int64();
if (feerate <= 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Feerate should be > 0!");
}
THeight prevAnchorHeight{0};
CAnchor anchor;
{
auto locked_chain = pwallet->chain().lock();
LOCK(locked_chain->mutex());
anchor = panchorauths->CreateBestAnchor(rewardDest);
prevAnchorHeight = panchors->GetActiveAnchor() ? panchors->GetActiveAnchor()->anchor.height : 0;
}
if (anchor.sigs.empty()) {
throw JSONRPCError(RPC_VERIFY_ERROR, "Min anchor quorum was not reached!");
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << anchor;
uint256 hash;
spv::TBytes rawtx;
uint64_t cost;
try {
std::tie(hash, rawtx, cost) = spv::CreateAnchorTx(inputsData, ToByteVector(ss), (uint64_t) feerate);
}
catch (std::runtime_error const & e) {
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
// after successful tx creation we does not throw!
int sendResult = 0;
if (send) {
if (spv::pspv) {
std::promise<int> promise;
if (spv::pspv->SendRawTx(rawtx, &promise)) {
sendResult = promise.get_future().get();
}
else {
sendResult = EPARSINGTX;
}
}
else
sendResult = ENOSPV;
}
UniValue result(UniValue::VOBJ);
result.pushKV("txHex", HexStr(rawtx));
result.pushKV("txHash", hash.ToString());
result.pushKV("defiHash", anchor.blockHash.ToString());
result.pushKV("defiHeight", (int) anchor.height);
result.pushKV("estimatedReward", ValueFromAmount(GetAnchorSubsidy(anchor.height, prevAnchorHeight, Params().GetConsensus())));
result.pushKV("cost", cost);
if (send) {
result.pushKV("sendResult", sendResult);
result.pushKV("sendMessage", sendResult != 0 ? DecodeSendResult(sendResult) : "");
}
return result;
}
UniValue spv_createanchortemplate(const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWallet(request);
RPCHelpMan{"spv_createanchortemplate",
"\nCreates an anchor tx template with latest possible (every 15th) authorized blockhash.\n" +
HelpRequiringPassphrase(pwallet) + "\n",
{
{"rewardAddress", RPCArg::Type::STR, RPCArg::Optional::NO, "User's P2PKH address (in DeFi chain) for reward"},
},
RPCResult{
"\"txHex\" (string) The hex-encoded raw transaction with signature(s)\n"
},
RPCExamples{
HelpExampleCli("spv_createanchortemplate", "\\\"rewardAddress\\\"")
},
}.Check(request);
if (!spv::pspv) {
throw JSONRPCError(RPC_INVALID_REQUEST, "spv module disabled");
}
if (pwallet->chain().isInitialBlockDownload()) {
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Cannot create anchor while still in Initial Block Download");
}
std::string rewardAddress = request.params[0].getValStr();
CTxDestination rewardDest = DecodeDestination(rewardAddress);
if (rewardDest.which() != 1 && rewardDest.which() != 4) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "rewardAddress (" + rewardAddress + ") does not refer to a P2PKH or P2WPKH address");
}
THeight prevAnchorHeight{0};
CAnchor anchor;
{
auto locked_chain = pwallet->chain().lock();
LOCK(locked_chain->mutex());
anchor = panchorauths->CreateBestAnchor(rewardDest);
prevAnchorHeight = panchors->GetActiveAnchor() ? panchors->GetActiveAnchor()->anchor.height : 0;
}
if (anchor.sigs.empty()) {
throw JSONRPCError(RPC_VERIFY_ERROR, "Min anchor quorum was not reached!");
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << anchor;
auto metaScripts = spv::EncapsulateMeta(ToByteVector(ss));
auto consensus = Params().GetConsensus();
spv::TBytes scriptBytes{spv::CreateScriptForAddress(consensus.spv.anchors_address.c_str())};
if (scriptBytes.empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Can't create script for chainparam's 'spv.anchors_address' = '" + consensus.spv.anchors_address + "'");
}
CMutableBtcTransaction mtx;
// output[0] - anchor address with creation fee
mtx.vout.push_back(CBtcTxOut(spv::P2PKH_DUST, CScript(scriptBytes.begin(), scriptBytes.end())));
// output[1] - metadata (first part with OP_RETURN)
mtx.vout.push_back(CBtcTxOut(0, metaScripts[0]));
// output[2..n-1] - metadata (rest of the data in p2wsh keys)
for (size_t i = 1; i < metaScripts.size(); ++i) {
mtx.vout.push_back(CBtcTxOut(spv::P2WSH_DUST, metaScripts[i]));
}
UniValue result(UniValue::VOBJ);
result.pushKV("txHex", EncodeHexBtcTx(CBtcTransaction(mtx)));
result.pushKV("defiHash", anchor.blockHash.ToString());
result.pushKV("defiHeight", (int) anchor.height);
result.pushKV("estimatedReward", ValueFromAmount(GetAnchorSubsidy(anchor.height, prevAnchorHeight, consensus)));
result.pushKV("anchorAddress", Params().GetConsensus().spv.anchors_address);
return result;
}
UniValue spv_estimateanchorcost(const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWallet(request);
RPCHelpMan{"spv_estimateanchorcost",
"\nEstimates current anchor cost with default fee, one input and one change output.\n",
{
{"feerate", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "Feerate (satoshis) per 1000 bytes (Default = " + std::to_string(spv::DEFAULT_BTC_FEERATE) + ")"},
},
RPCResult{
"\"cost\" (numeric) Estimated anchor cost (satoshis)\n"
},
RPCExamples{
HelpExampleCli("spv_estimateanchorcost", "")
+ HelpExampleRpc("spv_estimateanchorcost", "")
},
}.Check(request);
int64_t const feerate = request.params[0].isNull() ? spv::DEFAULT_BTC_FEERATE : request.params[0].get_int64();
if (feerate <= 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Feerate should be > 0!");
}
auto locked_chain = pwallet->chain().lock();
LOCK(locked_chain->mutex());
// it is unable to create "pure" dummy anchor, cause it needs signing with real key
CAnchor const anchor = panchorauths->CreateBestAnchor(CTxDestination(PKHash()));
if (anchor.sigs.empty()) {
throw JSONRPCError(RPC_VERIFY_ERROR, "No potential anchor, can't estimate!");
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << anchor;
return UniValue(spv::EstimateAnchorCost(ToByteVector(ss), (uint64_t) feerate));
}
UniValue spv_rescan(const JSONRPCRequest& request)
{
RPCHelpMan{"spv_rescan",
"\nRescan from block height...\n",
{
{"height", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "Block height or ('tip' minus 'height') if negative)."},
},
RPCResult{
"\"none\" Returns nothing\n"
},
RPCExamples{
HelpExampleCli("spv_rescan", "600000")
+ HelpExampleRpc("spv_rescan", "600000")
},
}.Check(request);
int height = request.params[0].isNull() ? 0 : request.params[0].get_int();
if (!spv::pspv)
throw JSONRPCError(RPC_INVALID_REQUEST, "spv module disabled");
if (!spv::pspv->Rescan(height))
throw JSONRPCError(RPC_MISC_ERROR, "SPV not connected");
return {};
}
UniValue spv_syncstatus(const JSONRPCRequest& request)
{
RPCHelpMan{"spv_syncstatus",
"\nReturns spv sync status\n",
{
},
RPCResult{
"{ (json object)\n"
" \"connected\" (bool) Connection status\n"
" \"current\" (num) Last synced block\n"
" \"estimated\" (num) Estimated chain height (as reported by peers)\n"
"}\n"
},
RPCExamples{
HelpExampleCli("spv_syncstatus", "")
+ HelpExampleRpc("spv_syncstatus", "")
},
}.Check(request);
if (!spv::pspv)
throw JSONRPCError(RPC_INVALID_REQUEST, "spv module disabled");
UniValue result(UniValue::VOBJ);
result.pushKV("connected", spv::pspv->IsConnected());
result.pushKV("current", static_cast<int>(spv::pspv->GetLastBlockHeight()));
result.pushKV("estimated", static_cast<int>(spv::pspv->GetEstimatedBlockHeight()));
return result;
}
UniValue spv_gettxconfirmations(const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWallet(request);
RPCHelpMan{"spv_gettxconfirmations",
"\nReports tx confirmations (if any)...\n",
{
{"txhash", RPCArg::Type::STR, RPCArg::Optional::NO, "Hash of tx to look for"},
},
RPCResult{
"count (num) Tx confirmations. Zero if not confirmed yet (mempooled?) and -1 if not found\n"
},
RPCExamples{
HelpExampleCli("spv_gettxconfirmations", "\\\"txid\\\"")
+ HelpExampleRpc("spv_gettxconfirmations", "\\\"txid\\\"")
},
}.Check(request);
uint256 txHash;
ParseHashStr(request.params[0].getValStr(), txHash);
// ! before cs_main lock
// uint32_t const spvLastHeight = spv::pspv ? spv::pspv->GetLastBlockHeight() : 0;
auto locked_chain = pwallet->chain().lock();
LOCK(locked_chain->mutex());
// panchors->UpdateLastHeight(spvLastHeight);
return UniValue(panchors->GetAnchorConfirmations(txHash));
}
// Populate anchors in listanchors, listanchorspending and listanchorsunrewarded
void AnchorToUniv(const CAnchorIndex::AnchorRec& rec, UniValue& anchor)
{
CTxDestination rewardDest = rec.anchor.rewardKeyType == 1 ? CTxDestination(PKHash(rec.anchor.rewardKeyID)) : CTxDestination(WitnessV0KeyHash(rec.anchor.rewardKeyID));
anchor.pushKV("btcBlockHeight", static_cast<int>(rec.btcHeight));
anchor.pushKV("btcBlockHash", panchors->ReadBlockHash(rec.btcHeight).ToString());
anchor.pushKV("btcTxHash", rec.txHash.ToString());
anchor.pushKV("previousAnchor", rec.anchor.previousAnchor.ToString());
anchor.pushKV("defiBlockHeight", static_cast<int>(rec.anchor.height));
anchor.pushKV("defiBlockHash", rec.anchor.blockHash.ToString());
anchor.pushKV("rewardAddress", EncodeDestination(rewardDest));
anchor.pushKV("confirmations", panchors->GetAnchorConfirmations(&rec));
anchor.pushKV("signatures", static_cast<int>(rec.anchor.sigs.size()));
// If post-fork show creation height
uint64_t anchorCreationHeight{0};
std::shared_ptr<std::vector<unsigned char>> prefix;
if (rec.anchor.nextTeam.size() == 1 && GetAnchorEmbeddedData(*rec.anchor.nextTeam.begin(), anchorCreationHeight, prefix))
{
anchor.pushKV("anchorCreationHeight", static_cast<int>(anchorCreationHeight));
}
}
UniValue spv_listanchors(const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWallet(request);
RPCHelpMan{"spv_listanchors",
"\nList anchors (if any)\n",
{
{"minBtcHeight", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "min btc height, optional (default = -1)"},
{"maxBtcHeight", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "max btc height, optional (default = -1)"},
{"minConfs", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "min anchor confirmations, optional (default = -1)"},
{"maxConfs", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "max anchor confirmations, optional (default = -1)"},
{"startBtcHeight", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "max anchor confirmations, optional (default = -1)"},
{"limit", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "number of records to return (default = unlimited)"},
},
RPCResult{
"\"array\" Returns array of anchors\n"
},
RPCExamples{
HelpExampleCli("spv_listanchors", "1500000 -1 6 -1") // list completely confirmed anchors not older than 1500000 height
+ HelpExampleRpc("spv_listanchors", "-1 -1 0 0") // list anchors in mempool (or -1 -1 -1 0)
},
}.Check(request);
if (!spv::pspv)
throw JSONRPCError(RPC_INVALID_REQUEST, "spv module disabled");
RPCTypeCheck(request.params, { UniValue::VNUM, UniValue::VNUM, UniValue::VNUM, UniValue::VNUM, UniValue::VNUM, UniValue::VNUM }, true);
const int minBtcHeight = request.params.size() > 0 ? request.params[0].get_int() : -1;
const int maxBtcHeight = request.params.size() > 1 ? request.params[1].get_int() : -1;
const int minConfs = request.params.size() > 2 ? request.params[2].get_int() : -1;
const int maxConfs = request.params.size() > 3 ? request.params[3].get_int() : -1;
const int startBtcHeight = request.params.size() > 4 ? request.params[4].get_int() : -1;
const int limit = request.params.size() > 5 ? request.params[5].get_int() : std::numeric_limits<int>::max();
// ! before cs_main lock
uint32_t const tmp = spv::pspv->GetLastBlockHeight();
auto locked_chain = pwallet->chain().lock();
LOCK(locked_chain->mutex());
panchors->UpdateLastHeight(tmp); // may be unnecessary but for sure
auto const * cur = panchors->GetActiveAnchor();
auto count = limit;
UniValue result(UniValue::VARR);
panchors->ForEachAnchorByBtcHeight([&](const CAnchorIndex::AnchorRec & rec) {
// from tip to genesis:
auto confs = panchors->GetAnchorConfirmations(&rec);
if ((maxBtcHeight >= 0 && (int)rec.btcHeight > maxBtcHeight) || (minConfs >= 0 && confs < minConfs))
return true; // continue
if ((minBtcHeight >= 0 && (int)rec.btcHeight < minBtcHeight) ||
(maxConfs >= 0 && confs > maxConfs) ||
(startBtcHeight >= 0 && static_cast<THeight>(rec.btcHeight) < startBtcHeight))
return false; // break
UniValue anchor(UniValue::VOBJ);
AnchorToUniv(rec, anchor);
bool const isActive = cur && cur->txHash == rec.txHash;
anchor.pushKV("active", isActive);
if (isActive) {
cur = panchors->GetAnchorByBtcTx(cur->anchor.previousAnchor);
}
result.push_back(anchor);
return --count != 0;
});
return result;
}
UniValue spv_listanchorspending(const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWallet(request);
RPCHelpMan{"spv_listanchorspending",
"\nList pending anchors (if any). Pending anchors are waiting on\n"
"chain context to be fully validated, for example, anchors read\n"
"from SPV while the blockchain is still syncing.",
{},
RPCResult{
"\"array\" Returns array of pending anchors\n"
},
RPCExamples{
HelpExampleCli("spv_listanchorspending", "") // list completely confirmed anchors not older than 1500000 height
+ HelpExampleRpc("spv_listanchorspending", "") // list anchors in mempool (or -1 -1 -1 0)
},
}.Check(request);
if (!spv::pspv)
throw JSONRPCError(RPC_INVALID_REQUEST, "spv module disabled");
auto locked_chain = pwallet->chain().lock();
LOCK(locked_chain->mutex());
UniValue result(UniValue::VARR);
panchors->ForEachPending([&result](uint256 const &, CAnchorIndex::AnchorRec & rec)
{
UniValue anchor(UniValue::VOBJ);
AnchorToUniv(rec, anchor);
result.push_back(anchor);
return true;
});
return result;
}
UniValue spv_listanchorauths(const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWallet(request);
RPCHelpMan{"spv_listanchorauths",
"\nList anchor auths (if any)\n",
{
},
RPCResult{
"\"array\" Returns array of anchor auths\n"
},
RPCExamples{
HelpExampleCli("spv_listanchorauths", "")
+ HelpExampleRpc("spv_listanchorauths", "")
},
}.Check(request);
auto locked_chain = pwallet->chain().lock();
LOCK(locked_chain->mutex());
UniValue result(UniValue::VARR);
CAnchorAuthIndex::Auth const * prev = nullptr;
std::vector<CKeyID> signers;
std::vector<std::string> signatories;
const CKeyID* teamData{nullptr};
uint64_t anchorCreationHeight{0};
panchorauths->ForEachAnchorAuthByHeight([&](const CAnchorAuthIndex::Auth & auth) {
if (!prev)
prev = &auth;
if (prev->GetSignHash() != auth.GetSignHash()) {
// flush group
UniValue item(UniValue::VOBJ);
item.pushKV("previousAnchor", prev->previousAnchor.ToString());
item.pushKV("blockHeight", static_cast<int>(prev->height));
item.pushKV("blockHash", prev->blockHash.ToString());
item.pushKV("creationHeight", static_cast<int>(anchorCreationHeight));
item.pushKV("signers", (uint64_t)signers.size());
UniValue signees(UniValue::VARR);
for (const auto& sigs : signatories) {
signees.push_back(sigs);
}
if (!signees.empty()) {
item.pushKV("signees", signees);
}
result.push_back(item);
// clear
signers.clear();
signatories.clear();
teamData = nullptr;
anchorCreationHeight = 0;
prev = &auth;
}
auto hash160 = auth.GetSigner();
signers.push_back(hash160);
const auto id = pcustomcsview->GetMasternodeIdByOperator(auth.GetSigner());
if (id) {
const auto mn = pcustomcsview->GetMasternode(*id);
if (mn) {
auto dest = mn->operatorType == 1 ? CTxDestination(PKHash(hash160)) : CTxDestination(WitnessV0KeyHash(hash160));
signatories.push_back(EncodeDestination(dest));
}
}
if (!teamData && prev->nextTeam.size() == 1) {
// Team entry
teamData = &(*prev->nextTeam.begin());
std::shared_ptr<std::vector<unsigned char>> prefix;
GetAnchorEmbeddedData(*teamData, anchorCreationHeight, prefix);
}
return true;
});
if (prev) {
// place last auth group
UniValue item(UniValue::VOBJ);
item.pushKV("previousAnchor", prev->previousAnchor.ToString());
item.pushKV("blockHeight", static_cast<int>(prev->height));
item.pushKV("blockHash", prev->blockHash.ToString());
item.pushKV("creationHeight", static_cast<int>(anchorCreationHeight));
item.pushKV("signers", (uint64_t)signers.size());
UniValue signees(UniValue::VARR);
for (const auto& sigs : signatories) {
signees.push_back(sigs);
}
if (!signees.empty()) {
item.pushKV("signees", signees);
}
result.push_back(item);
}
return result;
}
UniValue spv_listanchorrewardconfirms(const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWallet(request);
RPCHelpMan{"spv_listanchorrewardconfirms",
"\nList anchor reward confirms (if any)\n",
{
},
RPCResult{
"\"array\" Returns array of anchor confirms\n"
},
RPCExamples{
HelpExampleCli("spv_listanchorrewardconfirms", "")
+ HelpExampleRpc("spv_listanchorrewardconfirms", "")
},
}.Check(request);
auto locked_chain = pwallet->chain().lock();
LOCK(locked_chain->mutex());
UniValue result(UniValue::VARR);
CAnchorConfirmMessage const * prev = nullptr;
std::vector<CKeyID> signers;
panchorAwaitingConfirms->ForEachConfirm([&result, &prev, &signers](const CAnchorConfirmMessage & confirm) {
if (!prev)
prev = &confirm;
if (prev->GetSignHash() != confirm.GetSignHash()) {
// flush group
CTxDestination rewardDest = prev->rewardKeyType == 1 ? CTxDestination(PKHash(prev->rewardKeyID)) : CTxDestination(WitnessV0KeyHash(prev->rewardKeyID));
UniValue item(UniValue::VOBJ);
item.pushKV("btcTxHeight", static_cast<int>(prev->btcTxHeight));
item.pushKV("btcTxHash", prev->btcTxHash.ToString());
item.pushKV("anchorHeight", static_cast<int>(prev->anchorHeight));
item.pushKV("dfiBlockHash", prev->dfiBlockHash.ToString());
item.pushKV("prevAnchorHeight", static_cast<int>(prev->prevAnchorHeight));
item.pushKV("rewardAddress", EncodeDestination(rewardDest));
item.pushKV("confirmSignHash", prev->GetSignHash().ToString());
item.pushKV("signers", (uint64_t)signers.size());
result.push_back(item);
// clear
signers.clear();
prev = &confirm;
}
signers.push_back(confirm.GetSigner());
return true;
});
if (prev) {
// place last confirm's group
CTxDestination rewardDest = prev->rewardKeyType == 1 ? CTxDestination(PKHash(prev->rewardKeyID)) : CTxDestination(WitnessV0KeyHash(prev->rewardKeyID));
UniValue item(UniValue::VOBJ);
item.pushKV("btcTxHeight", static_cast<int>(prev->btcTxHeight));
item.pushKV("btcTxHash", prev->btcTxHash.ToString());
item.pushKV("anchorHeight", static_cast<int>(prev->anchorHeight));
item.pushKV("dfiBlockHash", prev->dfiBlockHash.ToString());
item.pushKV("prevAnchorHeight", static_cast<int>(prev->prevAnchorHeight));
item.pushKV("rewardAddress", EncodeDestination(rewardDest));
item.pushKV("confirmSignHash", prev->GetSignHash().ToString());
item.pushKV("signers", (uint64_t)signers.size());
result.push_back(item);
}
return result;
}
UniValue spv_listanchorrewards(const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWallet(request);
RPCHelpMan{"spv_listanchorrewards",
"\nList anchor rewards (if any)\n",
{
},
RPCResult{
"\"array\" Returns array of anchor rewards\n"
},
RPCExamples{
HelpExampleCli("spv_listanchorrewards", "")
+ HelpExampleRpc("spv_listanchorrewards", "")
},
}.Check(request);
auto locked_chain = pwallet->chain().lock();
LOCK(locked_chain->mutex());
UniValue result(UniValue::VARR);
pcustomcsview->ForEachAnchorReward([&result] (uint256 const & btcHash, uint256 rewardHash) {
UniValue item(UniValue::VOBJ);
item.pushKV("AnchorTxHash", btcHash.ToString());
item.pushKV("RewardTxHash", rewardHash.ToString());
result.push_back(item);
return true;
});
return result;
}
UniValue spv_listanchorsunrewarded(const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWallet(request);
RPCHelpMan{"spv_listanchorsunrewarded",
"\nList anchors that have yet to be paid\n",
{
},
RPCResult{
"\"array\" Returns array of unrewarded anchors\n"
},
RPCExamples{
HelpExampleCli("spv_listanchorsunrewarded", "")
+ HelpExampleRpc("spv_listanchorsunrewarded", "")
},
}.Check(request);
auto locked_chain = pwallet->chain().lock();
LOCK(locked_chain->mutex());
UniValue result(UniValue::VARR);
CAnchorIndex::UnrewardedResult unrewarded = panchors->GetUnrewarded();
for (auto const & btcTxHash : unrewarded) {
auto rec = panchors->GetAnchorByTx(btcTxHash);
UniValue item(UniValue::VOBJ);
AnchorToUniv(*rec, item);
result.push_back(item);
}
return result;
}
UniValue spv_setlastheight(const JSONRPCRequest& request)
{
RPCHelpMan{"spv_setlastheight",
"\nSet last processed block height (for test purposes only)...\n",
{
{"height", RPCArg::Type::NUM, RPCArg::Optional::NO, "Height in btc chain"},
},
RPCResult{
"\"none\" Returns nothing\n"
},
RPCExamples{
HelpExampleCli("spv_setlastheight", "\\\"height\\\"")
+ HelpExampleRpc("spv_setlastheight", "\\\"height\\\"")
},
}.Check(request);
auto fake_spv = static_cast<spv::CFakeSpvWrapper *>(spv::pspv.get());
if (!fake_spv)
throw JSONRPCError(RPC_INVALID_REQUEST, "command disabled");
fake_spv->lastBlockHeight = request.params[0].get_int();
panchors->CheckActiveAnchor(fake_spv->lastBlockHeight, true);
return UniValue();
}
UniValue spv_decodehtlcscript(const JSONRPCRequest& request)
{
RPCHelpMan{"spv_decodehtlcscript",
"\nDecode and return value in a HTLC redeemscript\n",
{
{"redeemscript", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The HTLC redeemscript"},
},
RPCResult{
"{\n"
" \"receiverPubkey\" (string) The public key of the possessor of the seed\n"
" \"ownerPubkey\" (string) The public key of the recipient of the refund\n"
" \"blocks\" (number) Locktime in number of blocks\n"
" \"hash\" (string) Hex-encoded seed hash if no seed provided\n"
"}\n"
},
RPCExamples{
HelpExampleCli("spv_decodehtlcscript", "\\\"redeemscript\\\"")
+ HelpExampleRpc("spv_decodehtlcscript", "\\\"redeemscript\\\"")
},
}.Check(request);
if (!IsHex(request.params[0].get_str()))
{
throw JSONRPCError(RPC_TYPE_ERROR, "Redeemscript expected in hex format");
}
auto redeemBytes = ParseHex(request.params[0].get_str());
CScript redeemScript(redeemBytes.begin(), redeemBytes.end());
auto details = spv::GetHTLCDetails(redeemScript);
UniValue result(UniValue::VOBJ);
result.pushKV("sellerkey", HexStr(details.sellerKey));
result.pushKV("buyerkey", HexStr(details.buyerKey));
result.pushKV("blocks", static_cast<uint64_t>(details.locktime));
result.pushKV("hash", HexStr(details.hash));
return result;
}
CPubKey PublickeyFromString(const std::string &pubkey)
{
if (!IsHex(pubkey) || (pubkey.length() != 66 && pubkey.length() != 130))
{
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid public key: " + pubkey);
}
return HexToPubKey(pubkey);
}
CScript CreateScriptForHTLC(const JSONRPCRequest& request, uint32_t& blocks, std::vector<unsigned char>& image)
{
CPubKey seller_key = PublickeyFromString(request.params[0].get_str());
CPubKey refund_key = PublickeyFromString(request.params[1].get_str());
{
UniValue timeout;
if (!timeout.read(std::string("[") + request.params[2].get_str() + std::string("]")) || !timeout.isArray() || timeout.size() != 1)
{
throw JSONRPCError(RPC_TYPE_ERROR, "Error parsing JSON: " + request.params[3].get_str());
}
blocks = timeout[0].get_int();
}
if (blocks >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
{
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid block denominated relative timeout");
}
else if (blocks < HTLC_MINIMUM_BLOCK_COUNT)
{
throw JSONRPCError(RPC_TYPE_ERROR, "Timeout below minimum of " + std::to_string(HTLC_MINIMUM_BLOCK_COUNT));
}
return GetScriptForHTLC(seller_key, refund_key, image, blocks);
}
UniValue spv_createhtlc(const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWallet(request);
RPCHelpMan{"spv_createhtlc",
"\nCreates a Bitcoin address whose funds can be unlocked with a seed or as a refund.\n"
"It returns a json object with the address and redeemScript.\n",
{
{"receiverPubkey", RPCArg::Type::STR, RPCArg::Optional::NO, "The public key of the possessor of the seed"},
{"ownerPubkey", RPCArg::Type::STR, RPCArg::Optional::NO, "The public key of the recipient of the refund"},
{"timeout", RPCArg::Type::STR, RPCArg::Optional::NO, "Timeout of the contract (denominated in blocks) relative to its placement in the blockchain. Minimum " + std::to_string(HTLC_MINIMUM_BLOCK_COUNT) + "."},
{"seed", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "SHA256 hash of the seed. If none provided one will be generated"},
},
RPCResult{
"{\n"
" \"address\":\"address\" (string) The value of the new Bitcoin address\n"
" \"redeemScript\":\"script\" (string) Hex-encoded redemption script\n"
" \"seed\":\"seed\" (string) Hex-encoded seed if no seed provided\n"
" \"seedhash\":\"seedhash\" (string) Hex-encoded seed hash if no seed provided\n"
"}\n"
},
RPCExamples{
HelpExampleCli("spv_createhtlc", "0333ffc4d18c7b2adbd1df49f5486030b0b70449c421189c2c0f8981d0da9669af 034201385acc094d24db4b53a05fc8991b10e3467e6e20a8551c49f89e7e4d0d3c 10 254e38932fdb9fc27f82aac2a5cc6d789664832383e3cf3298f8c120812712db")
+ HelpExampleRpc("spv_createhtlc", "0333ffc4d18c7b2adbd1df49f5486030b0b70449c421189c2c0f8981d0da9669af, 034201385acc094d24db4b53a05fc8991b10e3467e6e20a8551c49f89e7e4d0d3c, 10, 254e38932fdb9fc27f82aac2a5cc6d789664832383e3cf3298f8c120812712db")
},
}.Check(request);
if (!spv::pspv)
{
throw JSONRPCError(RPC_INVALID_REQUEST, "spv module disabled");
}
// Check that we are connected
if (!spv::pspv->IsConnected()) {
throw JSONRPCError(RPC_MISC_ERROR, "spv not connected");
}
// Make sure we are fully synced
if (spv::pspv->GetLastBlockHeight() < spv::pspv->GetEstimatedBlockHeight()) {
auto blocksRemaining = std::to_string(spv::pspv->GetEstimatedBlockHeight() -spv::pspv->GetLastBlockHeight());
throw JSONRPCError(RPC_MISC_ERROR, "spv still syncing, " + blocksRemaining + " blocks left.");
}
std::vector<unsigned char> hashBytes;
CKeyingMaterial seed;
// Seed hash provided
if (!request.params[3].isNull())
{
std::string hash = request.params[3].get_str();
if (IsHex(hash))
{
hashBytes = ParseHex(hash);
if (hashBytes.size() != 32)
{
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid hash image length, 32 (SHA256) accepted");
}
}
else
{
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid hash image");
}
}
else // No seed hash provided, generate seed
{
hashBytes.resize(32);
seed.resize(32);
GetStrongRandBytes(seed.data(), seed.size());
CSHA256 hash;
hash.Write(seed.data(), seed.size());
hash.Finalize(hashBytes.data());
}
// Get HTLC script
uint32_t blocks;
CScript inner = CreateScriptForHTLC(request, blocks, hashBytes);
// Get destination
CScriptID innerID(inner);
ScriptHash scriptHash(innerID);
// Add address and script to DeFi wallet storage for persistance
pwallet->SetAddressBook(scriptHash, "htlc", "htlc");
pwallet->AddCScript(inner);
// Add to SPV to watch transactions to this script
spv::pspv->AddBitcoinHash(scriptHash, true);
spv::pspv->RebuildBloomFilter(true);
// Create Bitcoin address
std::vector<unsigned char> data(21, spv::pspv->GetP2SHPrefix());
memcpy(&data[1], &innerID, 20);
UniValue result(UniValue::VOBJ);
result.pushKV("address", EncodeBase58Check(data));
result.pushKV("redeemScript", HexStr(inner));
if (!seed.empty())
{
result.pushKV("seed", HexStr(seed));
result.pushKV("seedhash", HexStr(hashBytes));
}
return result;
}
UniValue spv_listhtlcoutputs(const JSONRPCRequest& request)
{
RPCHelpMan{"spv_listhtlcoutputs",
"\nList all outputs related to HTLC addresses in the wallet\n",
{
{"address", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "HTLC address to filter results"},
},
RPCResult{
"[ (JSON array of transaction details)\n"
"{\n"
" \"txid\" (string) The transaction id\n"
" \"vout\" (numeric) Output relating to the HTLC address\n"
" \"address\" (string) HTLC address\n"
" \"confirms\" (numeric) Number of confirmations\n"
" { \"spent\" (JSON object containing spent info)\n"
" \"txid\" (string) Transaction id spending this output\n"
" \"confirms\" (numeric) Number of spent confirmations\n"
" }\n"
"}, ...]\n"
},