-
Notifications
You must be signed in to change notification settings - Fork 173
/
rpcrawtransaction.cpp
executable file
·1164 lines (940 loc) · 45.2 KB
/
rpcrawtransaction.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) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include "base58.h"
#include "rpcserver.h"
#include "rpcprotocol.h"
#include "txdb.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "wallet.h"
#include "coincontrol.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
extern std::vector<std::pair<std::string, std::string>> GetTxStakeBoincHashInfo(const CMerkleTx& mtx);
extern std::vector<std::pair<std::string, std::string>> GetTxNormalBoincHashInfo(const CMerkleTx& mtx);
std::string TimestampToHRDate(double dtm);
std::string GetPollXMLElementByPollTitle(std::string pollname, std::string XMLElement1, std::string XMLElement2);
std::string GetShareType(double dShareType);
bool PollCreatedAfterSecurityUpgrade(std::string pollname);
double DoubleFromAmount(int64_t amount);
std::vector<std::pair<std::string, std::string>> GetTxStakeBoincHashInfo(const CMerkleTx& mtx)
{
assert(mtx.IsCoinStake() || mtx.IsCoinBase());
std::vector<std::pair<std::string, std::string>> res;
// Fetch BlockIndex for tx block
CBlockIndex* pindex = NULL;
CBlock block;
{
BlockMap::iterator mi = mapBlockIndex.find(mtx.hashBlock);
if (mi == mapBlockIndex.end())
{
res.push_back(std::make_pair(_("ERROR"), _("Block not in index")));
return res;
}
pindex = (*mi).second;
if (!block.ReadFromDisk(pindex))
{
res.push_back(std::make_pair(_("ERROR"), _("Block read failed")));
return res;
}
}
//Deserialize
MiningCPID bb = DeserializeBoincBlock(block.vtx[0].hashBoinc,block.nVersion);
res.push_back(std::make_pair(_("Height"), ToString(pindex->nHeight)));
res.push_back(std::make_pair(_("Block Version"), ToString(block.nVersion)));
res.push_back(std::make_pair(_("Difficulty"), RoundToString(GetBlockDifficulty(block.nBits),8)));
res.push_back(std::make_pair(_("CPID"), bb.cpid));
res.push_back(std::make_pair(_("Interest"), RoundToString(bb.InterestSubsidy,8)));
if (bb.ResearchAverageMagnitude > 0)
{
res.push_back(std::make_pair(_("Boinc Reward"), RoundToString(bb.ResearchSubsidy,8)));
res.push_back(std::make_pair(_("Magnitude"), RoundToString(bb.Magnitude,8)));
res.push_back(std::make_pair(_("Average Magnitude"), RoundToString(bb.ResearchAverageMagnitude, 8)));
res.push_back(std::make_pair(_("Research Age"), RoundToString(bb.ResearchAge, 8)));
}
res.push_back(std::make_pair(_("Is Superblock"), (bb.superblock.length() >= 20 ? "Yes" : "No")));
if(fDebug)
{
if (bb.superblock.length() >= 20)
res.push_back(std::make_pair(_("Neural Contract Binary Size"), ToString(bb.superblock.length())));
res.push_back(std::make_pair(_("Neural Hash"), bb.NeuralHash));
res.push_back(std::make_pair(_("Current Neural Hash"), bb.CurrentNeuralHash));
res.push_back(std::make_pair(_("Client Version"), bb.clientversion));
res.push_back(std::make_pair(_("Organization"), bb.Organization));
res.push_back(std::make_pair(_("Boinc Public Key"), bb.BoincPublicKey));
}
return res;
}
std::vector<std::pair<std::string, std::string>> GetTxNormalBoincHashInfo(const CMerkleTx& mtx)
{
assert(!mtx.IsCoinStake() && !mtx.IsCoinBase());
std::vector<std::pair<std::string, std::string>> res;
try
{
const std::string &msg = mtx.hashBoinc;
res.push_back(std::make_pair(_("Network Date"), TimestampToHRDate((double)mtx.nTime)));
if (fDebug)
res.push_back(std::make_pair(_("Message Length"), ToString(msg.length())));
std::string sMessageType = ExtractXML(msg, "<MT>", "</MT>");
std::string sTxMessage = ExtractXML(msg, "<MESSAGE>", "</MESSAGE>");
std::string sRainMessage = ExtractXML(msg, "<NARR>", "</NARR>");
if (sMessageType.length())
{
if (sMessageType == "beacon")
{
std::string sBeaconAction = ExtractXML(msg, "<MA>", "</MA>");
std::string sBeaconCPID = ExtractXML(msg, "<MK>", "</MK>");
if (sBeaconAction == "A")
{
res.push_back(std::make_pair(_("Message Type"), _("Add Beacon Contract")));
std::string sBeaconEncodedContract = ExtractXML(msg, "<MV>", "</MV>");
if (sBeaconEncodedContract.length() < 256)
{
// If for whatever reason the contract is not a proper one and the average length does exceed this size; Without this a seg fault will occur on the DecodeBase64
// Another example is if an admin accidently uses add instead of delete in addkey to remove a beacon the 1 in <MV>1</MV> would cause a seg fault as well
res.push_back(std::make_pair(_("ERROR"), _("Contract length for beacon is less then 256 in length. Size: ") + ToString(sBeaconEncodedContract.length())));
if (fDebug)
res.push_back(std::make_pair(_("Message Data"), sBeaconEncodedContract));
return res;
}
std::string sBeaconDecodedContract = DecodeBase64(sBeaconEncodedContract);
std::vector<std::string> vBeaconContract = split(sBeaconDecodedContract.c_str(), ";");
std::string sBeaconAddress = vBeaconContract[2];
std::string sBeaconPublicKey = vBeaconContract[3];
res.push_back(std::make_pair(_("CPID"), sBeaconCPID));
res.push_back(std::make_pair(_("Address"), sBeaconAddress));
res.push_back(std::make_pair(_("Public Key"), sBeaconPublicKey));
}
else if (sBeaconAction == "D")
{
res.push_back(std::make_pair(_("Message Type"), _("Delete Beacon Contract")));
res.push_back(std::make_pair(_("CPID"), sBeaconCPID));
}
}
else if (sMessageType == "poll")
{
std::string sPollType = ExtractXML(msg, "<MK>", "</MK>");
std::string sPollTitle = ExtractXML(msg, "<TITLE>", "</TITLE>");
std::replace(sPollTitle.begin(), sPollTitle.end(), '_', ' ');
std::string sPollDays = ExtractXML(msg, "<DAYS>", "</DAYS>");
std::string sPollQuestion = ExtractXML(msg, "<QUESTION>", "</QUESTION>");
std::string sPollAnswers = ExtractXML(msg, "<ANSWERS>", "</ANSWERS>");
std::string sPollShareType = ExtractXML(msg, "<SHARETYPE>", "</SHARETYPE>");
std::string sPollUrl = ExtractXML(msg, "<URL>", "</URL");
std::string sPollExpiration = ExtractXML(msg, "<EXPIRATION>", "</EXPIRATION>");
std::replace(sPollAnswers.begin(), sPollAnswers.end(), ';', ',');
sPollShareType = GetShareType(std::stod(sPollShareType));
if (Contains(sPollType, "[Foundation"))
res.push_back(std::make_pair(_("Message Type"), _("Add Foundation Poll")));
else
res.push_back(std::make_pair(_("Message Type"), _("Add Poll")));
res.push_back(std::make_pair(_("Title"), sPollTitle));
res.push_back(std::make_pair(_("Question"), sPollQuestion));
res.push_back(std::make_pair(_("Answers"), sPollAnswers));
res.push_back(std::make_pair(_("Share Type"), sPollShareType));
res.push_back(std::make_pair(_("URL"), sPollUrl));
res.push_back(std::make_pair(_("Duration"), sPollDays + _(" days")));
res.push_back(std::make_pair(_("Expires"), TimestampToHRDate(std::stod(sPollExpiration))));
}
else if (sMessageType == "vote")
{
std::string sVoteTitled = ExtractXML(msg, "<TITLE>", "</TITLE>");
std::string sVoteShareType = GetPollXMLElementByPollTitle(sVoteTitled, "<SHARETYPE>", "</SHARETYPE>");
std::string sVoteTitle = sVoteTitled;
std::replace(sVoteTitle.begin(), sVoteTitle.end(), '_', ' ');
std::string sVoteAnswer = ExtractXML(msg, "<ANSWER>", "</ANSWER>");
std::replace(sVoteAnswer.begin(), sVoteAnswer.end(), ';', ',');
res.push_back(std::make_pair(_("Message Type"), _("Vote")));
res.push_back(std::make_pair(_("Title"), sVoteTitle));
if (sVoteShareType.empty())
{
res.push_back(std::make_pair(_("Share Type"), _("Unable to extract Share Type. Vote likely > 6 months old")));
res.push_back(std::make_pair(_("Answer"), sVoteAnswer));
if (fDebug)
res.push_back(std::make_pair(_("Share Type Debug"), sVoteShareType));
return res;
}
else
res.push_back(std::make_pair(_("Share Type"), GetShareType(std::stod(sVoteShareType))));
res.push_back(std::make_pair(_("Answer"), sVoteAnswer));
// Basic Variables for all poll types
double dVoteWeight = 0;
double dVoteMagnitude = 0;
double dVoteBalance = 0;
std::string sVoteMagnitude;
std::string sVoteBalance;
// Get voting magnitude and balance; These fields are always in vote contract
if (!PollCreatedAfterSecurityUpgrade(sVoteTitled))
{
sVoteMagnitude = ExtractXML(msg, "<MAGNITUDE>", "</MAGNITUDE>");
sVoteBalance = ExtractXML(msg, "<BALANCE>", "</BALANCE>");
}
else
{
sVoteMagnitude = ExtractXML(msg, "<INNERMAGNITUDE>", "</INNERMAGNITUDE>");
sVoteBalance = ExtractXML(msg, "<TOTALVOTEDBALANCE>", "</TOTALVOTEDBALANCE>");
}
if (sVoteShareType == "1")
dVoteWeight = std::stod(sVoteMagnitude);
else if (sVoteShareType == "2")
dVoteWeight = std::stod(sVoteBalance);
else if (sVoteShareType == "3")
{
// For voting mag for mag + balance polls we need to calculate total network magnitude from superblock before vote to use the correct data in formula.
// This gives us an accurate vote shares at that time. We like to keep wallet information as accurate as possible.
// Note during boosted superblocks we get unusual calculations for total network magnitude.
CBlockIndex* pblockindex = mapBlockIndex[mtx.hashBlock];
CBlock block;
if(pblockindex)
{
int nEndHeight = pblockindex->nHeight - (BLOCKS_PER_DAY*14);
// Incase; Why throw.
if (nEndHeight < 1)
nEndHeight = 1;
// Iterate back to find previous superblock
while (pblockindex->nHeight > nEndHeight && pblockindex->nIsSuperBlock == 0)
pblockindex = pblockindex->pprev;
}
if (pblockindex && pblockindex->nIsSuperBlock)
{
block.ReadFromDisk(pblockindex);
std::string sHashBoinc = block.vtx[0].hashBoinc;
MiningCPID vbb = DeserializeBoincBlock(sHashBoinc, block.nVersion);
std::string sUnpackedSuperblock = UnpackBinarySuperblock(vbb.superblock);
std::string sMagnitudeContract = ExtractXML(sUnpackedSuperblock, "<MAGNITUDES>", "</MAGNITUDES>");
// Since Superblockavg function gives avg for mags yes but total cpids we cannot use this function
// We need the rows_above_zero for Total Network Magnitude calculation with Money Supply Factor.
std::vector<std::string> vMagnitudeContract = split(sMagnitudeContract, ";");
int nRowsWithMag = 0;
double dTotalMag = 0;
for (auto const& sMag : vMagnitudeContract)
{
const std::vector<std::string>& vFields = split(sMag, ",");
if (vFields.size() < 2)
continue;
const std::string& sCPID = vFields[0];
double dMAG = std::stoi(vFields[1].c_str());
if (sCPID.length() > 10)
{
nRowsWithMag++;
dTotalMag += dMAG;
}
}
double dOutAverage = dTotalMag / ((double)nRowsWithMag + .01);
double dTotalNetworkMagnitude = (double)nRowsWithMag * dOutAverage;
double dMoneySupply = DoubleFromAmount(pblockindex->nMoneySupply);
double dMoneySupplyFactor = (dMoneySupply/dTotalNetworkMagnitude + .01);
dVoteMagnitude = RoundFromString(sVoteMagnitude,2);
dVoteBalance = RoundFromString(sVoteBalance,2);
if (dVoteMagnitude > 0)
dVoteWeight = ((dMoneySupplyFactor/5.67) * dVoteMagnitude) + std::stod(sVoteBalance);
else
dVoteWeight = std::stod(sVoteBalance);
res.push_back(std::make_pair(_("Magnitude"), RoundToString(dVoteMagnitude, 2)));
res.push_back(std::make_pair(_("Balance"), RoundToString(dVoteBalance, 2)));
}
else
{
res.push_back(std::make_pair(_("ERROR"), _("Unable to obtain superblock data before vote was made to calculate voting weight")));
dVoteWeight = -1;
res.push_back(std::make_pair(_("Magnitude"), RoundToString(dVoteMagnitude, 2)));
res.push_back(std::make_pair(_("Balance"), RoundToString(dVoteBalance, 2)));
}
}
else if (sVoteShareType == "4" || sVoteShareType == "5")
dVoteWeight = 1;
res.push_back(std::make_pair(_("Weight"), RoundToString(dVoteWeight, 0)));
}
else if (sMessageType == "project")
{
std::string sProjectName = ExtractXML(msg, "<MK>", "</MK>");
std::string sProjectURL = ExtractXML(msg, "<MV>", "</MV>");
std::string sProjectAction = ExtractXML(msg, "<MA>", "</MA>");
if (sProjectAction == "A")
res.push_back(std::make_pair(_("Message Type"), _("Add Project")));
else if (sProjectAction == "D")
res.push_back(std::make_pair(_("Message Type"), _("Delete Project")));
res.push_back(std::make_pair(_("Name"), sProjectName));
if (sProjectAction == "A")
res.push_back(std::make_pair(_("URL"), sProjectURL));
}
else
{
res.push_back(std::make_pair(_("Message Type"), _("Unknown")));
if (fDebug)
res.push_back(std::make_pair(_("Data"), msg));
return res;
}
}
else if (sTxMessage.length())
{
res.push_back(std::make_pair(_("Message Type"), _("Text Message")));
res.push_back(std::make_pair(_("Message"), sTxMessage));
}
else if (sRainMessage.length())
{
res.push_back(std::make_pair(_("Message Type"), _("Text Rain Message")));
res.push_back(std::make_pair(_("Message"), sRainMessage));
}
else if (sMessageType.empty() && sTxMessage.empty() && sRainMessage.empty())
res.push_back(std::make_pair(_("Message Type"), _("No Attached Messages")));
return res;
}
catch (const std::invalid_argument& e)
{
std::string sE(e.what());
res.push_back(std::make_pair(_("ERROR"), _("Invalid argument exception while parsing Transaction Message -> ") + sE));
return res;
}
catch (const std::out_of_range& e)
{
std::string sE(e.what());
res.push_back(std::make_pair(_("ERROR"), _("Out of range exception while parsing Transaction Message -> ") + sE));
return res;
}
}
void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.pushKV("asm", scriptPubKey.ToString());
if (fIncludeHex)
out.pushKV("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
{
out.pushKV("type", GetTxnOutputType(type));
return;
}
out.pushKV("reqSigs", nRequired);
out.pushKV("type", GetTxnOutputType(type));
UniValue a(UniValue::VARR);
for (auto const& addr : addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.pushKV("addresses", a);
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
{
entry.pushKV("txid", tx.GetHash().GetHex());
entry.pushKV("version", tx.nVersion);
entry.pushKV("time", (int)tx.nTime);
entry.pushKV("locktime", (int)tx.nLockTime);
entry.pushKV("hashboinc", tx.hashBoinc);
UniValue vin(UniValue::VARR);
for (auto const& txin : tx.vin)
{
UniValue in(UniValue::VOBJ);
if (tx.IsCoinBase())
in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
else
{
in.pushKV("txid", txin.prevout.hash.GetHex());
in.pushKV("vout", (int)txin.prevout.n);
UniValue o(UniValue::VOBJ);
o.pushKV("asm", txin.scriptSig.ToString());
o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
in.pushKV("scriptSig", o);
}
in.pushKV("sequence", (int)txin.nSequence);
vin.push_back(in);
}
entry.pushKV("vin", vin);
UniValue vout(UniValue::VARR);
for (unsigned int i = 0; i < tx.vout.size(); i++)
{
const CTxOut& txout = tx.vout[i];
UniValue out(UniValue::VOBJ);
out.pushKV("value", ValueFromAmount(txout.nValue));
out.pushKV("n", (int)i);
UniValue o(UniValue::VOBJ);
ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
out.pushKV("scriptPubKey", o);
vout.push_back(out);
}
entry.pushKV("vout", vout);
if (hashBlock != 0)
{
entry.pushKV("blockhash", hashBlock.GetHex());
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
{
entry.pushKV("confirmations", 1 + nBestHeight - pindex->nHeight);
entry.pushKV("time", (int)pindex->nTime);
entry.pushKV("blocktime", (int)pindex->nTime);
}
else
entry.pushKV("confirmations", 0);
}
}
}
UniValue getrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction <txid> [verbose=bool]\n"
"\n"
"If verbose is false, returns a string that is\n"
"serialized, hex-encoded data for <txid>.\n"
"If verbose is true, returns an Object\n"
"with information about <txid>\n");
uint256 hash;
hash.SetHex(params[0].get_str());
// Accept either a bool (true) or a num (>=1) to indicate verbose output. Adapted from Bitcoin 20180820.
bool fVerbose = false;
if (!params[1].isNull())
{
fVerbose = params[1].isNum() ? (params[1].get_int() != 0) : params[1].get_bool();
}
LOCK(cs_main);
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(hash, tx, hashBlock))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
string strHex = HexStr(ssTx.begin(), ssTx.end());
if (!fVerbose)
return strHex;
UniValue result(UniValue::VOBJ);
result.pushKV("hex", strHex);
TxToJSON(tx, hashBlock, result);
return result;
}
UniValue listunspent(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n"
"\n"
"Returns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filtered to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}\n");
RPCTypeCheck(params, list_of(UniValue::VNUM)(UniValue::VNUM)(UniValue::VARR));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CBitcoinAddress> setAddress;
if (params.size() > 2)
{
UniValue inputs = params[2].get_array();
for (unsigned int ix = 0; ix < inputs.size(); ix++)
{
CBitcoinAddress address(inputs[ix].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Gridcoin address: ")+inputs[ix].get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+inputs[ix].get_str());
setAddress.insert(address);
}
}
UniValue results(UniValue::VARR);
vector<COutput> vecOutputs;
pwalletMain->AvailableCoins(vecOutputs, false, NULL, false);
LOCK(pwalletMain->cs_wallet);
for (auto const& out : vecOutputs)
{
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if(setAddress.size())
{
CTxDestination address;
if(!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
int64_t nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
UniValue entry(UniValue::VOBJ);
entry.pushKV("txid", out.tx->GetHash().GetHex());
entry.pushKV("vout", out.i);
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
{
entry.pushKV("address", CBitcoinAddress(address).ToString());
auto item = pwalletMain->mapAddressBook.find(address);
if (item != pwalletMain->mapAddressBook.end())
{
entry.pushKV("label", item->second);
if (GetBoolArg("-enableaccounts", false))
entry.pushKV("account", item->second);
}
}
entry.pushKV("scriptPubKey", HexStr(pk.begin(), pk.end()));
entry.pushKV("amount", ValueFromAmount(nValue));
entry.pushKV("confirmations", out.nDepth);
results.push_back(entry);
}
return results;
}
UniValue consolidateunspent(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"consolidateunspent <address> [UTXO size [maximum number of inputs]]\n"
"\n"
"Performs a single transaction to consolidate UTXOs on\n"
"a given address. The optional parameter of UTXO size will result\n"
"in consolidating UTXOs to generate an output of that size or\n"
"the output for the total value of the specified maximum,\n"
"maximum number of smallest inputs, whichever is less.\n");
UniValue result(UniValue::VOBJ);
std::string sAddress = params[0].get_str();
CBitcoinAddress OptimizeAddress(sAddress);
int64_t nConsolidateLimit = 0;
// Set default maximum consolidation to 50 inputs if it is not specified. This is based
// on performance tests on the Pi to ensure the transaction returns within a reasonable time.
// The performance tests on the Pi show about 3 UTXO's/second. Intel machines should do
// about 3x that. The GUI will not be responsive during the transaction.
unsigned int nInputNumberLimit = 50;
if (params.size() > 1) nConsolidateLimit = AmountFromValue(params[1]);
if (params.size() > 2) nInputNumberLimit = params[2].get_int();
// Clamp InputNumberLimit to 200. Above 200 risks an invalid transaction due to the size.
nInputNumberLimit = std::min(nInputNumberLimit, (unsigned int) 200);
if (!OptimizeAddress.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Gridcoin address: ") + sAddress);
// Set the consolidation transaction address to the same as the inputs to consolidate.
CScript scriptDestPubKey;
scriptDestPubKey.SetDestination(OptimizeAddress.Get());
std::vector<COutput> vecInputs;
// A convenient way to do a sort without the bother of writing a comparison operator.
// The map does it for us! It must be a multimap, because it is highly likely one or
// more UTXO's will have the same nValue.
std::multimap<int64_t, COutput> mInputs;
// Have to lock both main and wallet to prevent deadlocks.
LOCK2(cs_main, pwalletMain->cs_wallet);
// Get the current UTXO's.
pwalletMain->AvailableCoins(vecInputs, false, NULL, false);
// Filter outputs by matching address and insert into sorted multimap.
for (auto const& out : vecInputs)
{
CTxDestination outaddress;
int64_t nOutValue = out.tx->vout[out.i].nValue;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, outaddress)) continue;
if (CBitcoinAddress(outaddress) == OptimizeAddress)
mInputs.insert(std::make_pair(nOutValue, out));
}
CWalletTx wtxNew;
// For min fee calculation.
CTransaction txDummy;
set<pair<const CWalletTx*,unsigned int>> setCoins;
unsigned int iInputCount = 0;
int64_t nValue = 0;
// Construct the inputs to the consolidation transaction. Either all of the inputs from above, or 200,
// or when the total reaches/exceeds nConsolidateLimit, whichever is more limiting. The map allows us
// to elegantly select the UTXO's from the smallest upwards.
for (auto const& out : mInputs)
{
// Increment first so the count is 1 based.
++iInputCount;
if (fDebug) LogPrintf("INFO: consolidateunspent: input value = %f, confirmations = %" PRId64, ((double) out.first) / (double) COIN, out.second.nDepth);
setCoins.insert(make_pair(out.second.tx, out.second.i));
nValue += out.second.tx->vout[out.second.i].nValue;
if (iInputCount == nInputNumberLimit || (nValue >= nConsolidateLimit && nConsolidateLimit != 0)) break;
}
// If number of inputs that meet criteria is less than two, then do nothing.
if (iInputCount < 2)
{
result.pushKV("result", true);
result.pushKV("UTXOs consolidated", (uint64_t) 0);
return result;
}
CReserveKey reservekey(pwalletMain);
// Fee calculation to avoid change.
// Bytes
// --------- The inputs to the tx - The one output.
int64_t nBytes = iInputCount * 148 + 34 + 10;
// Min Fee
int64_t nMinFee = txDummy.GetMinFee(1, GMF_SEND, nBytes);
int64_t nFee = nTransactionFee * (1 + nBytes / 1000);
int64_t nFeeRequired = max(nMinFee, nFee);
if (pwalletMain->IsLocked())
{
string strError = _("Error: Wallet locked, unable to create transaction.");
LogPrintf("consolidateunspent: %s", strError);
return strError;
}
if (fWalletUnlockStakingOnly)
{
string strError = _("Error: Wallet unlocked for staking only, unable to create transaction.");
LogPrintf("consolidateunspent: %s", strError);
return strError;
}
vector<pair<CScript, int64_t> > vecSend;
// Reduce the out value for the transaction by nFeeRequired from the total of the inputs to provide a fee
// to the staker. The fee has been calculated so that no change should be produced from the CreateTransaction
// call. Just in case, the input address is specified as the return address via coincontrol.
vecSend.push_back(std::make_pair(scriptDestPubKey, nValue - nFeeRequired));
CCoinControl coinControl;
// Send the change back to the same address.
coinControl.destChange = OptimizeAddress.Get();
if (!pwalletMain->CreateTransaction(vecSend, setCoins, wtxNew, reservekey, nFeeRequired, &coinControl))
{
string strError;
if (nValue + nFeeRequired > pwalletMain->GetBalance())
strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired));
else
strError = _("Error: Transaction creation failed ");
LogPrintf("consolidateunspent: %s", strError);
return strError;
}
if (!pwalletMain->CommitTransaction(wtxNew, reservekey))
return _("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
result.pushKV("result", true);
result.pushKV("UTXOs consolidated", (uint64_t) iInputCount);
result.pushKV("Output UTXO value", (double)(nValue - nFeeRequired) / COIN);
return result;
}
UniValue createrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...}\n"
"\nCreate a transaction spending the given inputs and creating new outputs.\n"
"Outputs can be addresses or data.\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.\n"
"\nArguments:\n"
"1. \"transactions\" (string, required) A json array of json objects\n"
" [\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n (numeric, required) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"2. \"outputs\" (string, required) a json object with outputs\n"
" {\n"
" \"address\": x.xxx (numeric, required) The key is the bitcoin address, the value is the CURRENCY_UNIT amount\n"
" \"data\": \"hex\", (string, required) The key is \"data\", the value is hex encoded data\n"
" ...\n"
" }\n"
"\nResult:\n"
"\"transaction\" (string) hex string of the transaction\n"
"\nExamples\n"
"createrawtransaction \"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01} "
"createrawtransaction \"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"} "
"createrawtransaction \"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01} "
"createrawtransaction \"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"} \n"
);
RPCTypeCheck(params, list_of(UniValue::VARR)(UniValue::VOBJ));
UniValue inputs = params[0].get_array();
UniValue sendTo = params[1].get_obj();
CTransaction rawTx;
for (unsigned int idx = 0; idx<inputs.size(); idx++)
{
const UniValue& input = inputs[idx];
const UniValue& o = input.get_obj();
const UniValue& txid_v = find_value(o, "txid");
if (!txid_v.isStr())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
string txid = txid_v.get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
const UniValue& vout_v = find_value(o, "vout");
if (!vout_v.isNum())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
CTxIn in(COutPoint(uint256(txid), nOutput));
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
vector<string> addrList = sendTo.getKeys();
for (auto const& name_: addrList)
{
CBitcoinAddress address(name_);
if (name_ == "data")
{
std::vector<unsigned char> data = ParseHexV(sendTo[name_],"Data");
CTxOut out(0, CScript() << OP_RETURN << data);
rawTx.vout.push_back(out);
}
else
{
CBitcoinAddress address(name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Gridcoin address: ")+name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64_t nAmount = AmountFromValue(sendTo[name_]);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << rawTx;
return HexStr(ss.begin(), ss.end());
}
UniValue decoderawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction <hex string>\n"
"\n"
"Return a JSON object representing the serialized, hex-encoded transaction\n");
RPCTypeCheck(params, list_of(UniValue::VSTR));
vector<unsigned char> txData(ParseHex(params[0].get_str()));
LOCK(cs_main);
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
UniValue result(UniValue::VOBJ);
TxToJSON(tx, 0, result);
return result;
}
UniValue decodescript(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decodescript <hex string>\n"
"\n"
"Decode a hex-encoded script.\n");
RPCTypeCheck(params, list_of(UniValue::VSTR));
UniValue r(UniValue::VOBJ);
CScript script;
if (params[0].get_str().size() > 0){
vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
}
ScriptPubKeyToJSON(script, r, false);
r.pushKV("p2sh", CBitcoinAddress(script.GetID()).ToString());
return r;
}
UniValue signrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n"
"\n"
"Sign inputs for raw transaction (serialized, hex-encoded).\n"
"Second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the blockchain.\n"
"Third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
"Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n"
"ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n"
"Returns json object with keys:\n"
" hex : raw transaction with signature(s) (hex-encoded string)\n"
" complete : 1 if transaction has a complete set of signature (0 if not)\n"
+ HelpRequiringPassphrase());
RPCTypeCheck(params, list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR), true);
LOCK2(cs_main, pwalletMain->cs_wallet);
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CTransaction> txVariants;
while (!ssData.empty())
{
try {
CTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CTransaction mergedTx(txVariants[0]);
bool fComplete = true;
// Fetch previous transactions (inputs):
map<COutPoint, CScript> mapPrevOut;
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
CTransaction tempTx;
MapPrevTx mapPrevTx;
CTxDB txdb("r");
map<uint256, CTxIndex> unused;
bool fInvalid;
// FetchInputs aborts on failure, so we go one at a time.
tempTx.vin.push_back(mergedTx.vin[i]);
tempTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid);
// Copy results into mapPrevOut:
for (auto const& txin : tempTx.vin)
{
const uint256& prevHash = txin.prevout.hash;
if (mapPrevTx.count(prevHash) && mapPrevTx[prevHash].second.vout.size()>txin.prevout.n)
mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey;
}
}
// Add previous txouts given in the RPC call:
if (params.size() > 1 && !params[1].isNull())
{
UniValue prevTxs = params[1].get_array();
for (unsigned int idx = 0; idx < prevTxs.size(); idx++)
{
const UniValue&p = prevTxs[idx];
if (!p.isObject())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
UniValue prevOut = p.get_obj();