forked from Le-Space/doichain-core
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrpcnames.cpp
901 lines (739 loc) · 29.9 KB
/
rpcnames.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
// Copyright (c) 2014-2020 Daniel Kraft
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <base58.h>
#include <coins.h>
#include <consensus/validation.h>
#include <init.h>
#include <interfaces/chain.h>
#include <key_io.h>
#include <names/common.h>
#include <names/encoding.h>
#include <names/main.h>
#include <names/mempool.h>
#include <node/context.h>
#include <net.h>
#include <primitives/transaction.h>
#include <random.h>
#include <rpc/blockchain.h>
#include <rpc/names.h>
#include <rpc/server.h>
#include <rpc/util.h>
#include <script/names.h>
#include <txmempool.h>
#include <util/fees.h>
#include <util/moneystr.h>
#include <util/system.h>
#include <util/translation.h>
#include <validation.h>
#include <wallet/coincontrol.h>
#include <wallet/rpcwallet.h>
#include <wallet/wallet.h>
#include <univalue.h>
#include <algorithm>
#include <memory>
/* ************************************************************************** */
namespace
{
/**
* A simple helper class that handles determination of the address to which
* name outputs should be sent. It handles the CReserveKey reservation
* as well as parsing the explicit options given by the user (if any).
*/
class DestinationAddressHelper
{
private:
/** Reference to the wallet that should be used. */
CWallet& wallet;
/**
* The reserve key that was used if no override is given. When finalising
* (after the sending succeeded), this key needs to be marked as Keep().
*/
std::unique_ptr<ReserveDestination> rdest;
/** Set if a valid override destination was added. */
std::unique_ptr<CTxDestination> overrideDest;
public:
explicit DestinationAddressHelper (CWallet& w)
: wallet(w)
{}
/**
* Processes the given options object to see if it contains an override
* destination. If it does, remembers it.
*/
void setOptions (const UniValue& opt);
/**
* Returns the script that should be used as destination.
*/
CScript getScript ();
/**
* Marks the key as used if one has been reserved. This should be called
* when sending succeeded.
*/
void finalise ();
};
void DestinationAddressHelper::setOptions (const UniValue& opt)
{
RPCTypeCheckObj (opt,
{
{"destAddress", UniValueType (UniValue::VSTR)},
},
true, false);
if (!opt.exists ("destAddress"))
return;
CTxDestination dest = DecodeDestination (opt["destAddress"].get_str ());
if (!IsValidDestination (dest))
throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY, "invalid address");
overrideDest.reset (new CTxDestination (std::move (dest)));
}
CScript DestinationAddressHelper::getScript ()
{
if (overrideDest != nullptr)
return GetScriptForDestination (*overrideDest);
rdest.reset (new ReserveDestination (&wallet, wallet.m_default_address_type));
CTxDestination dest;
if (!rdest->GetReservedDestination (dest, false))
throw JSONRPCError (RPC_WALLET_KEYPOOL_RAN_OUT,
"Error: Keypool ran out,"
" please call keypoolrefill first");
return GetScriptForDestination (dest);
}
void DestinationAddressHelper::finalise ()
{
if (rdest != nullptr)
rdest->KeepDestination ();
}
/**
* Sends a name output to the given name script. This is the "final" step that
* is common between name_new, name_firstupdate, name_update and name_doi. This method
* also implements the "sendCoins" option, if included.
*/
UniValue
SendNameOutput (const JSONRPCRequest& request,
CWallet& wallet, const CScript& nameOutScript,
const CTxIn* nameInput, const UniValue& opt)
{
RPCTypeCheckObj (opt,
{
{"sendCoins", UniValueType (UniValue::VOBJ)},
},
true, false);
auto& node = EnsureNodeContext (request.context);
if (wallet.GetBroadcastTransactions () && !node.connman)
throw JSONRPCError (RPC_CLIENT_P2P_DISABLED,
"Error: Peer-to-peer functionality missing"
" or disabled");
std::vector<CRecipient> vecSend;
vecSend.push_back ({nameOutScript, NAME_LOCKED_AMOUNT, false});
if (opt.exists ("sendCoins"))
for (const std::string& addr : opt["sendCoins"].getKeys ())
{
const CTxDestination dest = DecodeDestination (addr);
if (!IsValidDestination (dest))
throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY,
"Invalid address: " + addr);
const CAmount nAmount = AmountFromValue (opt["sendCoins"][addr]);
if (nAmount <= 0)
throw JSONRPCError (RPC_TYPE_ERROR, "Invalid amount for send");
vecSend.push_back ({GetScriptForDestination (dest), nAmount, false});
}
CCoinControl coinControl;
return SendMoney (&wallet, coinControl, nameInput, vecSend, {});
}
} // anonymous namespace
/* ************************************************************************** */
RPCHelpMan
name_list ()
{
NameOptionsHelp optHelp;
optHelp
.withNameEncoding ()
.withValueEncoding ();
return RPCHelpMan ("name_list",
"\nShows the status of all names in the wallet.\n",
{
{"name", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "Only include this name"},
optHelp.buildRpcArg (),
},
RPCResult {RPCResult::Type::ARR, "", "",
{
NameInfoHelp ()
.withExpiration ()
.finish ()
}
},
RPCExamples {
HelpExampleCli ("name_list", "")
+ HelpExampleCli ("name_list", "\"myname\"")
+ HelpExampleRpc ("name_list", "")
},
[&] (const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest (request);
if (!wallet)
return NullUniValue;
CWallet* const pwallet = wallet.get ();
RPCTypeCheck (request.params, {UniValue::VSTR, UniValue::VOBJ}, true);
UniValue options(UniValue::VOBJ);
if (request.params.size () >= 2)
options = request.params[1].get_obj ();
valtype nameFilter;
if (request.params.size () >= 1 && !request.params[0].isNull ())
nameFilter = DecodeNameFromRPCOrThrow (request.params[0], options);
std::map<valtype, int> mapHeights;
std::map<valtype, UniValue> mapObjects;
/* Make sure the results are valid at least up to the most recent block
the user could have gotten from another RPC command prior to now. */
pwallet->BlockUntilSyncedToCurrentChain ();
{
LOCK2 (pwallet->cs_wallet, cs_main);
const int tipHeight = ::ChainActive ().Height ();
for (const auto& item : pwallet->mapWallet)
{
const CWalletTx& tx = item.second;
if (!tx.tx->IsDoichain ())
continue;
CNameScript nameOp;
int nOut = -1;
for (unsigned i = 0; i < tx.tx->vout.size (); ++i)
{
const CNameScript cur(tx.tx->vout[i].scriptPubKey);
if (cur.isNameOp ())
{
if (nOut != -1)
LogPrintf ("ERROR: wallet contains tx with multiple"
" name outputs");
else
{
nameOp = cur;
nOut = i;
}
}
}
if (nOut == -1 || (!nameOp.isAnyUpdate () && !nameOp.isDoiRegistration()))
continue;
const valtype& name = nameOp.getOpName ();
if (!nameFilter.empty () && nameFilter != name)
continue;
const int depth = tx.GetDepthInMainChain ();
if (depth <= 0)
continue;
const int height = tipHeight - depth + 1;
const auto mit = mapHeights.find (name);
if (mit != mapHeights.end () && mit->second > height)
continue;
UniValue obj
= getNameInfo (options, name, nameOp.getOpValue (),
COutPoint (tx.GetHash (), nOut),
nameOp.getAddress ());
addOwnershipInfo (nameOp.getAddress (), pwallet, obj);
addExpirationInfo (height, obj);
mapHeights[name] = height;
mapObjects[name] = obj;
}
}
UniValue res(UniValue::VARR);
for (const auto& item : mapObjects)
res.push_back (item.second);
return res;
}
);
}
/* ************************************************************************** */
RPCHelpMan
name_new ()
{
NameOptionsHelp optHelp;
optHelp
.withNameEncoding ()
.withWriteOptions ()
.withArg ("allowExisting", RPCArg::Type::BOOL, "false",
"If set, then the name_new is sent even if the name exists already");
return RPCHelpMan ("name_new",
"\nStarts registration of the given name. Must be followed up with name_firstupdate to finish the registration."
+ HELP_REQUIRING_PASSPHRASE,
{
{"name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name to register"},
optHelp.buildRpcArg (),
},
RPCResult {RPCResult::Type::ARR_FIXED, "", "",
{
{RPCResult::Type::STR_HEX, "txid", "the txid, required for name_firstupdate"},
{RPCResult::Type::STR_HEX, "rand", "random value, for name_firstupdate"},
},
},
RPCExamples {
HelpExampleCli ("name_new", "\"myname\"")
+ HelpExampleRpc ("name_new", "\"myname\"")
},
[&] (const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest (request);
if (!wallet)
return NullUniValue;
CWallet* const pwallet = wallet.get ();
RPCTypeCheck (request.params, {UniValue::VSTR, UniValue::VOBJ});
UniValue options(UniValue::VOBJ);
if (request.params.size () >= 2)
options = request.params[1].get_obj ();
RPCTypeCheckObj (options,
{
{"allowExisting", UniValueType (UniValue::VBOOL)},
},
true, false);
const valtype name = DecodeNameFromRPCOrThrow (request.params[0], options);
if (name.size () > MAX_NAME_LENGTH)
throw JSONRPCError (RPC_INVALID_PARAMETER, "the name is too long");
if (!options["allowExisting"].isTrue ())
{
LOCK (cs_main);
CNameData oldData;
const auto& coinsTip = ::ChainstateActive ().CoinsTip ();
if (coinsTip.GetName (name, oldData) && !oldData.isExpired ())
throw JSONRPCError (RPC_TRANSACTION_ERROR, "this name exists already");
}
valtype rand(20);
GetRandBytes (&rand[0], rand.size ());
/* Make sure the results are valid at least up to the most recent block
the user could have gotten from another RPC command prior to now. */
pwallet->BlockUntilSyncedToCurrentChain ();
LOCK (pwallet->cs_wallet);
EnsureWalletIsUnlocked (pwallet);
DestinationAddressHelper destHelper(*pwallet);
destHelper.setOptions (options);
const CScript newScript
= CNameScript::buildNameNew (destHelper.getScript (), name, rand);
const UniValue txidVal
= SendNameOutput (request, *pwallet, newScript, nullptr, options);
destHelper.finalise ();
const std::string randStr = HexStr (rand);
const std::string txid = txidVal.get_str ();
LogPrintf ("name_new: name=%s, rand=%s, tx=%s\n",
EncodeNameForMessage (name), randStr.c_str (), txid.c_str ());
UniValue res(UniValue::VARR);
res.push_back (txid);
res.push_back (randStr);
return res;
}
);
}
/* ************************************************************************** */
namespace
{
/**
* Helper routine to fetch the name output of a previous transaction. This
* is required for name_firstupdate.
* @param txid Previous transaction ID.
* @param txOut Set to the corresponding output.
* @param txIn Set to the CTxIn to include in the new tx.
* @return True if the output could be found.
*/
bool
getNamePrevout (const uint256& txid, CTxOut& txOut, CTxIn& txIn)
{
AssertLockHeld (cs_main);
// Maximum number of outputs that are checked for the NAME_NEW prevout.
constexpr unsigned MAX_NAME_PREVOUT_TRIALS = 1000;
// Unfortunately, with the change of the txdb to be based on outputs rather
// than full transactions, we can no longer just look up the txid and iterate
// over all outputs. Since this is only necessary for a corner case, we just
// keep trying with indices until we find the output (up to a maximum number
// of trials).
for (unsigned i = 0; i < MAX_NAME_PREVOUT_TRIALS; ++i)
{
const COutPoint outp(txid, i);
Coin coin;
if (!::ChainstateActive ().CoinsTip ().GetCoin (outp, coin))
continue;
if (!coin.out.IsNull ()
&& CNameScript::isNameScript (coin.out.scriptPubKey))
{
txOut = coin.out;
txIn = CTxIn (outp);
return true;
}
}
return false;
}
} // anonymous namespace
UniValue
name_firstupdate (const JSONRPCRequest& request)
{
/* There is an undocumented sixth argument that can be used to disable
the check for already existing names here (it will still be checked
by the mempool and tx validation logic, of course). This is used
by the regtests to catch a bug that was previously present but
has presumably no other use. */
NameOptionsHelp optHelp;
optHelp
.withNameEncoding ()
.withValueEncoding ()
.withWriteOptions ();
/* We can not use RPCHelpMan::Check here, as we have that "hidden" sixth
argument for "allow active" names (in tests). */
if (request.fHelp || request.params.size () < 4 || request.params.size () > 6)
throw std::runtime_error (
RPCHelpMan ("name_firstupdate",
"\nFinishes the registration of a name. Depends on name_new being already issued."
+ HELP_REQUIRING_PASSPHRASE,
{
{"name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name to register"},
{"rand", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The rand value of name_new"},
{"tx", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The name_new txid"},
{"value", RPCArg::Type::STR, RPCArg::Optional::NO, "Value for the name"},
optHelp.buildRpcArg (),
},
RPCResult {RPCResult::Type::STR_HEX, "", "the transaction ID"},
RPCExamples {
HelpExampleCli ("name_firstupdate", "\"myname\", \"555844f2db9c7f4b25da6cb8277596de45021ef2\" \"a77ceb22aa03304b7de64ec43328974aeaca211c37dd29dcce4ae461bb80ca84\", \"my-value\"")
+ HelpExampleRpc ("name_firstupdate", "\"myname\", \"555844f2db9c7f4b25da6cb8277596de45021ef2\" \"a77ceb22aa03304b7de64ec43328974aeaca211c37dd29dcce4ae461bb80ca84\", \"my-value\"")
}
).ToString ());
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest (request);
if (!wallet)
return NullUniValue;
CWallet* const pwallet = wallet.get ();
RPCTypeCheck (request.params,
{UniValue::VSTR, UniValue::VSTR, UniValue::VSTR, UniValue::VSTR,
UniValue::VOBJ});
UniValue options(UniValue::VOBJ);
if (request.params.size () >= 5)
options = request.params[4].get_obj ();
const valtype name = DecodeNameFromRPCOrThrow (request.params[0], options);
if (name.size () > MAX_NAME_LENGTH)
throw JSONRPCError (RPC_INVALID_PARAMETER, "the name is too long");
const valtype rand = ParseHexV (request.params[1], "rand");
if (rand.size () > 20)
throw JSONRPCError (RPC_INVALID_PARAMETER, "invalid rand value");
const uint256 prevTxid = ParseHashV (request.params[2], "txid");
const valtype value = DecodeValueFromRPCOrThrow (request.params[3], options);
if (value.size () > MAX_VALUE_LENGTH_UI)
throw JSONRPCError (RPC_INVALID_PARAMETER, "the value is too long");
{
auto& mempool = EnsureMemPool (request.context);
LOCK (mempool.cs);
if (mempool.registersName (name))
throw JSONRPCError (RPC_TRANSACTION_ERROR,
"this name is already being registered");
}
if (request.params.size () < 6 || !request.params[5].get_bool ())
{
LOCK (cs_main);
CNameData oldData;
const auto& coinsTip = ::ChainstateActive ().CoinsTip ();
if (coinsTip.GetName (name, oldData) && !oldData.isExpired ())
throw JSONRPCError (RPC_TRANSACTION_ERROR,
"this name is already active");
}
CTxOut prevOut;
CTxIn txIn;
{
LOCK (cs_main);
if (!getNamePrevout (prevTxid, prevOut, txIn))
throw JSONRPCError (RPC_TRANSACTION_ERROR, "previous txid not found");
}
const CNameScript prevNameOp(prevOut.scriptPubKey);
assert (prevNameOp.isNameOp ());
if (prevNameOp.getNameOp () != OP_NAME_NEW)
throw JSONRPCError (RPC_TRANSACTION_ERROR, "previous tx is not name_new");
valtype toHash(rand);
toHash.insert (toHash.end (), name.begin (), name.end ());
if (uint160 (prevNameOp.getOpHash ()) != Hash160 (toHash))
throw JSONRPCError (RPC_TRANSACTION_ERROR, "rand value is wrong");
/* Make sure the results are valid at least up to the most recent block
the user could have gotten from another RPC command prior to now. */
pwallet->BlockUntilSyncedToCurrentChain ();
LOCK (pwallet->cs_wallet);
EnsureWalletIsUnlocked (pwallet);
DestinationAddressHelper destHelper(*pwallet);
destHelper.setOptions (options);
const CScript nameScript
= CNameScript::buildNameFirstupdate (destHelper.getScript (), name, value, rand);
const UniValue txidVal
= SendNameOutput (request, *pwallet, nameScript, &txIn, options);
destHelper.finalise ();
return txidVal;
}
/* ************************************************************************** */
RPCHelpMan
name_update ()
{
NameOptionsHelp optHelp;
optHelp
.withNameEncoding ()
.withValueEncoding ()
.withWriteOptions ();
return RPCHelpMan ("name_update",
"\nUpdates a name and possibly transfers it."
+ HELP_REQUIRING_PASSPHRASE,
{
{"name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name to update"},
{"value", RPCArg::Type::STR, RPCArg::Optional::NO, "Value for the name"},
optHelp.buildRpcArg (),
},
RPCResult {RPCResult::Type::STR_HEX, "", "the transaction ID"},
RPCExamples {
HelpExampleCli ("name_update", "\"myname\", \"new-value\"")
+ HelpExampleRpc ("name_update", "\"myname\", \"new-value\"")
},
[&] (const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest (request);
if (!wallet)
return NullUniValue;
CWallet* const pwallet = wallet.get ();
RPCTypeCheck (request.params,
{UniValue::VSTR, UniValue::VSTR, UniValue::VOBJ});
UniValue options(UniValue::VOBJ);
if (request.params.size () >= 3)
options = request.params[2].get_obj ();
const valtype name = DecodeNameFromRPCOrThrow (request.params[0], options);
if (name.size () > MAX_NAME_LENGTH)
throw JSONRPCError (RPC_INVALID_PARAMETER, "the name is too long");
const valtype value = DecodeValueFromRPCOrThrow (request.params[1], options);
if (value.size () > MAX_VALUE_LENGTH_UI)
throw JSONRPCError (RPC_INVALID_PARAMETER, "the value is too long");
/* For finding the name output to spend, we first check if there are
pending operations on the name in the mempool. If there are, then we
build upon the last one to get a valid chain. If there are none, then we
look up the last outpoint from the name database instead. */
const unsigned chainLimit = gArgs.GetArg ("-limitnamechains",
DEFAULT_NAME_CHAIN_LIMIT);
COutPoint outp;
{
auto& mempool = EnsureMemPool (request.context);
LOCK (mempool.cs);
const unsigned pendingOps = mempool.pendingNameChainLength (name);
if (pendingOps >= chainLimit)
throw JSONRPCError (RPC_TRANSACTION_ERROR,
"there are already too many pending operations"
" on this name");
if (pendingOps > 0)
outp = mempool.lastNameOutput (name);
}
if (outp.IsNull ())
{
LOCK (cs_main);
CNameData oldData;
const auto& coinsTip = ::ChainstateActive ().CoinsTip ();
if (!coinsTip.GetName (name, oldData) || oldData.isExpired ())
throw JSONRPCError (RPC_TRANSACTION_ERROR,
"this name can not be updated");
outp = oldData.getUpdateOutpoint ();
}
assert (!outp.IsNull ());
const CTxIn txIn(outp);
/* Make sure the results are valid at least up to the most recent block
the user could have gotten from another RPC command prior to now. */
pwallet->BlockUntilSyncedToCurrentChain ();
LOCK (pwallet->cs_wallet);
EnsureWalletIsUnlocked (pwallet);
DestinationAddressHelper destHelper(*pwallet);
destHelper.setOptions (options);
const CScript nameScript
= CNameScript::buildNameUpdate (destHelper.getScript (), name, value);
const UniValue txidVal
= SendNameOutput (request, *pwallet, nameScript, &txIn, options);
destHelper.finalise ();
return txidVal;
}
);
}
/* ************************************************************************** */
RPCHelpMan
name_doi ()
{
NameOptionsHelp optHelp;
optHelp
.withNameEncoding ()
.withValueEncoding ()
.withWriteOptions ();
return RPCHelpMan ("name_doi",
"\nCreates or updates a name_doi record and possibly transfers it."
+ HELP_REQUIRING_PASSPHRASE,
{
{"name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name_doi record to create or update"},
{"value", RPCArg::Type::STR, RPCArg::Optional::NO, "Value for the name"},
optHelp.buildRpcArg (),
},
RPCResult {RPCResult::Type::STR_HEX, "", "the transaction ID"},
RPCExamples {
HelpExampleCli ("name_doi", "\"myname\", \"new-value\"")
+ HelpExampleRpc ("name_doi", "\"myname\", \"new-value\"")
},
[&] (const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest (request);
if (!wallet)
return NullUniValue;
CWallet* const pwallet = wallet.get ();
RPCTypeCheck (request.params,
{UniValue::VSTR, UniValue::VSTR, UniValue::VOBJ});
UniValue options(UniValue::VOBJ);
if (request.params.size () >= 3)
options = request.params[2].get_obj ();
const valtype name = DecodeNameFromRPCOrThrow (request.params[0], options);
if (name.size () > MAX_NAME_LENGTH)
throw JSONRPCError (RPC_INVALID_PARAMETER, "the name is too long");
const valtype value = DecodeValueFromRPCOrThrow (request.params[1], options);
if (value.size () > MAX_VALUE_LENGTH_UI)
throw JSONRPCError (RPC_INVALID_PARAMETER, "the value is too long");
/* For finding the name output to spend, we first check if there are
pending operations on the name in the mempool. If there are, then we
build upon the last one to get a valid chain. If there are none, then we
look up the last outpoint from the name database instead. */
const unsigned chainLimit = gArgs.GetArg ("-limitnamechains",
DEFAULT_NAME_CHAIN_LIMIT);
COutPoint outp;
CScript oldAddress;
CNameData oldData;
{
auto& mempool = EnsureMemPool (request.context);
LOCK (mempool.cs);
const unsigned pendingOps = mempool.pendingNameChainLength (name);
if (pendingOps >= chainLimit)
throw JSONRPCError (RPC_TRANSACTION_ERROR,
"there are already too many pending operations"
" on this name");
LogPrintf ("looking for pending operations \n");
if (pendingOps > 0)
outp = mempool.lastNameOutput (name);
}
if (outp.IsNull ())
{
LogPrintf ("couldn't find old output in pending operations, looking in old data\n");
LOCK (cs_main);
const auto& coinsTip = ::ChainstateActive ().CoinsTip ();
coinsTip.GetName (name, oldData);
outp = oldData.getUpdateOutpoint ();
oldAddress = oldData.getAddress ();
}
/* Make sure the results are valid at least up to the most recent block
the user could have gotten from another RPC command prior to now. */
pwallet->BlockUntilSyncedToCurrentChain ();
LOCK (pwallet->cs_wallet);
EnsureWalletIsUnlocked (pwallet);
DestinationAddressHelper destHelper(*pwallet);
destHelper.setOptions (options);
if(!outp.IsNull ())
{
LogPrintf ("updating a name_doi: %s having old_data: %s\n",
EncodeNameForMessage(name),
EncodeNameForMessage(oldData.getValue ()));
CTxIn txIn (outp);
/* LogPrintf ("sending storage fee (0.01 DOI) to fixed address: mx9dSRrjfGTsDxgNjULGXibvayBhY4qLj1\n");
const CTxDestination dest = DecodeDestination ("mx9dSRrjfGTsDxgNjULGXibvayBhY4qLj1");
if (!IsValidDestination (dest))
throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY,
"Invalid address: ");
CScript script = GetScriptForDestination (dest) */
/*
CScript script;
if(options.isNull())
script = destHelper.getScript ();
else{ //send storage fee to destination too.
//script = GetScriptForDestination (dest)
}*/
CScript script = destHelper.getScript ();
const CScript nameScript = CNameScript::buildNameDOI (script, name, value);
const UniValue txidVal = SendNameOutput (request, *pwallet, nameScript, &txIn, options);
destHelper.finalise ();
return txidVal;
}
else
{
/* LogPrintf ("creating new name_doi sending storage (0.01 DOI) fee to fixed address: mx9dSRrjfGTsDxgNjULGXibvayBhY4qLj1\n");
const CTxDestination dest = DecodeDestination ("mx9dSRrjfGTsDxgNjULGXibvayBhY4qLj1");
if (!IsValidDestination (dest))
throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY,
"Invalid address: ");
CScript script = GetScriptForDestination (dest) */
CScript script = destHelper.getScript ();
const CScript nameScript = CNameScript::buildNameDOI (script, name, value);
const UniValue txidVal = SendNameOutput (request, *pwallet, nameScript, nullptr, options);
destHelper.finalise ();
return txidVal;
}
}
);
}
/* ************************************************************************** */
RPCHelpMan
sendtoname ()
{
return RPCHelpMan{"sendtoname",
"\nSend an amount to the owner of a name.\n"
"\nIt is an error if the name is expired."
+ HELP_REQUIRING_PASSPHRASE,
{
{"name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name to send to."},
{"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "The amount in " + CURRENCY_UNIT + " to send. eg 0.1"},
{"comment", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "A comment used to store what the transaction is for.\n"
" This is not part of the transaction, just kept in your wallet."},
{"comment_to", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "A comment to store the name of the person or organization\n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet."},
{"subtractfeefromamount", RPCArg::Type::BOOL, /* default */ "false", "The fee will be deducted from the amount being sent.\n"
" The recipient will receive less coins than you enter in the amount field."},
{"replaceable", RPCArg::Type::BOOL, /* default */ "fallback to wallet's default", "Allow this transaction to be replaced by a transaction with higher fees via BIP 125"},
},
RPCResult {RPCResult::Type::STR_HEX, "", "the transaction ID"},
RPCExamples{
HelpExampleCli ("sendtoname", "\"id/foobar\" 0.1")
+ HelpExampleCli ("sendtoname", "\"id/foobar\" 0.1 \"donation\" \"seans outpost\"")
+ HelpExampleCli ("sendtoname", "\"id/foobar\" 0.1 \"\" \"\" true")
+ HelpExampleRpc ("sendtoname", "\"id/foobar\", 0.1, \"donation\", \"seans outpost\"")
},
[&] (const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest (request);
if (!wallet)
return NullUniValue;
CWallet* const pwallet = wallet.get ();
if (::ChainstateActive ().IsInitialBlockDownload ())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD,
"Doichain is downloading blocks...");
/* Make sure the results are valid at least up to the most recent block
the user could have gotten from another RPC command prior to now. */
pwallet->BlockUntilSyncedToCurrentChain();
LOCK(pwallet->cs_wallet);
/* sendtoname does not support an options argument (e.g. to override the
configured name/value encodings). That would just add to the already
long list of rarely used arguments. Also, this function is inofficially
deprecated anyway, see
https://github.com/doichain/doichain-core/issues/12. */
const UniValue NO_OPTIONS(UniValue::VOBJ);
const valtype name = DecodeNameFromRPCOrThrow (request.params[0], NO_OPTIONS);
CNameData data;
if (!::ChainstateActive ().CoinsTip ().GetName (name, data))
{
std::ostringstream msg;
msg << "name not found: " << EncodeNameForMessage (name);
throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY, msg.str ());
}
if (data.isExpired ())
throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY, "the name is expired");
/* The code below is strongly based on sendtoaddress. Make sure to
keep it in sync. */
// Wallet comments
mapValue_t mapValue;
if (request.params.size() > 2 && !request.params[2].isNull()
&& !request.params[2].get_str().empty())
mapValue["comment"] = request.params[2].get_str();
if (request.params.size() > 3 && !request.params[3].isNull()
&& !request.params[3].get_str().empty())
mapValue["to"] = request.params[3].get_str();
bool fSubtractFeeFromAmount = false;
if (!request.params[4].isNull())
fSubtractFeeFromAmount = request.params[4].get_bool();
CCoinControl coin_control;
if (!request.params[5].isNull()) {
coin_control.m_signal_bip125_rbf = request.params[5].get_bool();
}
EnsureWalletIsUnlocked(pwallet);
std::vector<CRecipient> recipients;
const CAmount amount = AmountFromValue (request.params[1]);
recipients.push_back ({data.getAddress (), amount, fSubtractFeeFromAmount});
return SendMoney(pwallet, coin_control, nullptr, recipients, mapValue);
}
};
}