forked from vinced/namecoin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnamecoin.cpp
More file actions
1789 lines (1550 loc) · 57.1 KB
/
namecoin.cpp
File metadata and controls
1789 lines (1550 loc) · 57.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2010-2011 Vincent Durham
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
//
#include "headers.h"
#include "db.h"
#include "keystore.h"
#include "wallet.h"
#include "init.h"
#include "auxpow.h"
#include "namecoin.h"
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"
using namespace std;
using namespace json_spirit;
static const bool NAME_DEBUG = false;
typedef Value(*rpcfn_type)(const Array& params, bool fHelp);
extern map<string, rpcfn_type> mapCallTable;
extern int64 AmountFromValue(const Value& value);
extern Object JSONRPCError(int code, const string& message);
template<typename T> void ConvertTo(Value& value);
static const int NAMECOIN_TX_VERSION = 0x7100;
static const int64 MIN_AMOUNT = CENT;
static const int MAX_NAME_LENGTH = 255;
static const int MAX_VALUE_LENGTH = 1023;
static const int OP_NAME_INVALID = 0x00;
static const int OP_NAME_NEW = 0x01;
static const int OP_NAME_FIRSTUPDATE = 0x02;
static const int OP_NAME_UPDATE = 0x03;
static const int OP_NAME_NOP = 0x04;
static const int MIN_FIRSTUPDATE_DEPTH = 12;
map<vector<unsigned char>, uint256> mapMyNames;
map<vector<unsigned char>, set<uint256> > mapNamePending;
extern uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
// forward decls
extern bool DecodeNameScript(const CScript& script, int& op, vector<vector<unsigned char> > &vvch);
extern bool DecodeNameScript(const CScript& script, int& op, vector<vector<unsigned char> > &vvch, CScript::const_iterator& pc);
extern int IndexOfNameOutput(CWalletTx& wtx);
extern bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& scriptSigRet);
extern bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, int nHashType);
extern bool GetValueOfNameTx(const CTransaction& tx, vector<unsigned char>& value);
extern bool IsConflictedTx(CTxDB& txdb, const CTransaction& tx, vector<unsigned char>& name);
extern bool GetNameOfTx(const CTransaction& tx, vector<unsigned char>& name);
const int NAME_COIN_GENESIS_EXTRA = 521;
uint256 hashNameCoinGenesisBlock("000000000062b72c5e2ceb45fbc8587e807c155b0da735e6483dfba2f0a9c770");
class CNamecoinHooks : public CHooks
{
public:
virtual bool IsStandard(const CScript& scriptPubKey);
virtual void AddToWallet(CWalletTx& tx);
virtual bool CheckTransaction(const CTransaction& tx);
virtual bool ConnectInputs(CTxDB& txdb,
map<uint256, CTxIndex>& mapTestPool,
const CTransaction& tx,
vector<CTransaction>& vTxPrev,
vector<CTxIndex>& vTxindex,
CBlockIndex* pindexBlock,
CDiskTxPos& txPos,
bool fBlock,
bool fMiner);
virtual bool DisconnectInputs(CTxDB& txdb,
const CTransaction& tx,
CBlockIndex* pindexBlock);
virtual bool ConnectBlock(CBlock& block, CTxDB& txdb, CBlockIndex* pindex);
virtual bool DisconnectBlock(CBlock& block, CTxDB& txdb, CBlockIndex* pindex);
virtual bool ExtractAddress(const CScript& script, string& address);
virtual bool GenesisBlock(CBlock& block);
virtual bool Lockin(int nHeight, uint256 hash);
virtual int LockinHeight();
virtual string IrcPrefix();
virtual void AcceptToMemoryPool(CTxDB& txdb, const CTransaction& tx);
virtual void MessageStart(char* pchMessageStart)
{
// Make the message start different
pchMessageStart[3] = 0xfe;
}
virtual bool IsMine(const CTransaction& tx);
virtual bool IsMine(const CTransaction& tx, const CTxOut& txout);
virtual int GetOurChainID()
{
return 0x0001;
}
virtual int GetAuxPowStartBlock()
{
if (fTestNet)
return 0;
return 19200;
}
virtual int GetFullRetargetStartBlock()
{
if (fTestNet)
return 0;
return 19200;
}
string GetAlertPubkey1()
{
return "04ba207043c1575208f08ea6ac27ed2aedd4f84e70b874db129acb08e6109a3bbb7c479ae22565973ebf0ac0391514511a22cb9345bdb772be20cfbd38be578b0c";
}
string GetAlertPubkey2()
{
return "04fc4366270096c7e40adb8c3fcfbff12335f3079e5e7905bce6b1539614ae057ee1e61a25abdae4a7a2368505db3541cd81636af3f7c7afe8591ebc85b2a1acdd";
}
};
int64 getAmount(Value value)
{
ConvertTo<double>(value);
double dAmount = value.get_real();
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(-3, "Invalid amount");
return nAmount;
}
vector<unsigned char> vchFromValue(const Value& value) {
string strName = value.get_str();
unsigned char *strbeg = (unsigned char*)strName.c_str();
return vector<unsigned char>(strbeg, strbeg + strName.size());
}
vector<unsigned char> vchFromString(string str) {
unsigned char *strbeg = (unsigned char*)str.c_str();
return vector<unsigned char>(strbeg, strbeg + str.size());
}
string stringFromVch(vector<unsigned char> vch) {
string res;
vector<unsigned char>::iterator vi = vch.begin();
while (vi != vch.end()) {
res += (char)(*vi);
vi++;
}
return res;
}
// Increase expiration to 36000 gradually starting at block 24000.
// Use for validation purposes and pass the chain height.
int GetExpirationDepth(int nHeight) {
if (nHeight < 24000)
return 12000;
if (nHeight < 48000)
return nHeight - 12000;
return 36000;
}
// For display purposes, pass the name height.
int GetDisplayExpirationDepth(int nHeight) {
if (nHeight < 24000)
return 12000;
return 36000;
}
int64 GetNetworkFee(int nHeight)
{
// Speed up network fee decrease 4x starting at 24000
if (nHeight >= 24000)
nHeight += (nHeight - 24000) * 3;
if ((nHeight >> 13) >= 60)
return 0;
int64 nStart = 50 * COIN;
if (fTestNet)
nStart = 10 * CENT;
int64 nRes = nStart >> (nHeight >> 13);
nRes -= (nRes >> 14) * (nHeight % 8192);
return nRes;
}
int GetTxPosHeight(const CDiskTxPos& txPos)
{
// Read block header
CBlock block;
if (!block.ReadFromDisk(txPos.nFile, txPos.nBlockPos, false))
return 0;
// Find the block in the index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return pindex->nHeight;
}
int GetNameHeight(CTxDB& txdb, vector<unsigned char> vchName) {
CNameDB dbName("cr", txdb);
vector<CDiskTxPos> vtxPos;
if (dbName.ExistsName(vchName))
{
if (!dbName.ReadName(vchName, vtxPos))
return error("GetNameHeight() : failed to read from name DB");
if (vtxPos.empty())
return -1;
CDiskTxPos& txPos = vtxPos.back();
return GetTxPosHeight(txPos);
}
return -1;
}
CScript RemoveNameScriptPrefix(const CScript& scriptIn)
{
int op;
vector<vector<unsigned char> > vvch;
CScript::const_iterator pc = scriptIn.begin();
if (!DecodeNameScript(scriptIn, op, vvch, pc))
throw runtime_error("RemoveNameScriptPrefix() : could not decode name script");
return CScript(pc, scriptIn.end());
}
bool SignNameSignature(const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL, CScript scriptPrereq=CScript())
{
assert(nIn < txTo.vin.size());
CTxIn& txin = txTo.vin[nIn];
assert(txin.prevout.n < txFrom.vout.size());
const CTxOut& txout = txFrom.vout[txin.prevout.n];
// Leave out the signature from the hash, since a signature can't sign itself.
// The checksig op will also drop the signatures from its hash.
const CScript& scriptPubKey = RemoveNameScriptPrefix(txout.scriptPubKey);
uint256 hash = SignatureHash(scriptPrereq + txout.scriptPubKey, txTo, nIn, nHashType);
if (!Solver(*pwalletMain, scriptPubKey, hash, nHashType, txin.scriptSig))
return false;
txin.scriptSig = scriptPrereq + txin.scriptSig;
// Test solution
if (scriptPrereq.empty())
if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, 0))
return false;
return true;
}
bool IsMyName(const CTransaction& tx, const CTxOut& txout)
{
const CScript& scriptPubKey = RemoveNameScriptPrefix(txout.scriptPubKey);
CScript scriptSig;
if (!Solver(*pwalletMain, scriptPubKey, 0, 0, scriptSig))
return false;
return true;
}
bool CreateTransactionWithInputTx(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxIn, int nTxOut, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
{
int64 nValue = 0;
BOOST_FOREACH(const PAIRTYPE(CScript, int64)& s, vecSend)
{
if (nValue < 0)
return false;
nValue += s.second;
}
if (vecSend.empty() || nValue < 0)
return false;
wtxNew.pwallet = pwalletMain;
CRITICAL_BLOCK(cs_main)
{
// txdb must be opened before the mapWallet lock
CTxDB txdb("r");
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
nFeeRet = nTransactionFee;
loop
{
wtxNew.vin.clear();
wtxNew.vout.clear();
wtxNew.fFromMe = true;
int64 nTotalValue = nValue + nFeeRet;
printf("total value = %d\n", nTotalValue);
double dPriority = 0;
// vouts to the payees
BOOST_FOREACH(const PAIRTYPE(CScript, int64)& s, vecSend)
wtxNew.vout.push_back(CTxOut(s.second, s.first));
int64 nWtxinCredit = wtxIn.vout[nTxOut].nValue;
// Choose coins to use
set<pair<const CWalletTx*, unsigned int> > setCoins;
int64 nValueIn = 0;
if (!pwalletMain->SelectCoins(nTotalValue - nWtxinCredit, setCoins, nValueIn))
return false;
vector<pair<const CWalletTx*, unsigned int> >
vecCoins(setCoins.begin(), setCoins.end());
BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int)& coin, vecCoins)
{
int64 nCredit = coin.first->vout[coin.second].nValue;
dPriority += (double)nCredit * coin.first->GetDepthInMainChain();
}
// Input tx always at first position
vecCoins.insert(vecCoins.begin(), make_pair(&wtxIn, nTxOut));
nValueIn += nWtxinCredit;
dPriority += (double)nWtxinCredit * wtxIn.GetDepthInMainChain();
// Fill a vout back to self with any change
int64 nChange = nValueIn - nTotalValue;
if (nChange >= CENT)
{
// Note: We use a new key here to keep it from being obvious which side is the change.
// The drawback is that by not reusing a previous key, the change may be lost if a
// backup is restored, if the backup doesn't have the new private key for the change.
// If we reused the old key, it would be possible to add code to look for and
// rediscover unknown transactions that were written with keys of ours to recover
// post-backup change.
// Reserve a new key pair from key pool
vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
assert(pwalletMain->mapKeys.count(vchPubKey));
// Fill a vout to ourself, using same address type as the payment
CScript scriptChange;
if (vecSend[0].first.GetBitcoinAddressHash160() != 0)
scriptChange.SetBitcoinAddress(vchPubKey);
else
scriptChange << vchPubKey << OP_CHECKSIG;
// Insert change txn at random position:
vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
}
else
reservekey.ReturnKey();
// Fill vin
BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int)& coin, vecCoins)
wtxNew.vin.push_back(CTxIn(coin.first->GetHash(), coin.second));
// Sign
int nIn = 0;
BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int)& coin, vecCoins)
{
if (coin.first == &wtxIn && coin.second == nTxOut)
{
if (!SignNameSignature(*coin.first, wtxNew, nIn++))
throw runtime_error("could not sign name coin output");
}
else
{
if (!SignSignature(*pwalletMain, *coin.first, wtxNew, nIn++))
return false;
}
}
// Limit size
unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
return false;
dPriority /= nBytes;
// Check that enough fee is included
int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
bool fAllowFree = CTransaction::AllowFree(dPriority);
int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree);
if (nFeeRet < max(nPayFee, nMinFee))
{
nFeeRet = max(nPayFee, nMinFee);
continue;
}
// Fill vtxPrev by copying from previous transactions vtxPrev
wtxNew.AddSupportingTransactions(txdb);
wtxNew.fTimeReceivedIsTxTime = true;
break;
}
}
}
return true;
}
// nTxOut is the output from wtxIn that we should grab
// requires cs_main lock
string SendMoneyWithInputTx(CScript scriptPubKey, int64 nValue, int64 nNetFee, CWalletTx& wtxIn, CWalletTx& wtxNew, bool fAskFee)
{
int nTxOut = IndexOfNameOutput(wtxIn);
CReserveKey reservekey(pwalletMain);
int64 nFeeRequired;
vector< pair<CScript, int64> > vecSend;
vecSend.push_back(make_pair(scriptPubKey, nValue));
if (nNetFee)
{
CScript scriptFee;
scriptFee << OP_RETURN;
vecSend.push_back(make_pair(scriptFee, nNetFee));
}
if (!CreateTransactionWithInputTx(vecSend, wtxIn, nTxOut, wtxNew, reservekey, nFeeRequired))
{
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).c_str());
else
strError = _("Error: Transaction creation failed ");
printf("SendMoney() : %s", strError.c_str());
return strError;
}
if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
return "ABORTED";
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.");
MainFrameRepaint();
return "";
}
bool GetValueOfTxPos(const CDiskTxPos& txPos, vector<unsigned char>& vchValue, uint256& hash, int& nHeight)
{
nHeight = GetTxPosHeight(txPos);
CTransaction tx;
if (!tx.ReadFromDisk(txPos))
return error("GetValueOfTxPos() : could not read tx from disk");
if (!GetValueOfNameTx(tx, vchValue))
return error("GetValueOfTxPos() : could not decode value from tx");
hash = tx.GetHash();
return true;
}
bool GetValueOfName(CNameDB& dbName, vector<unsigned char> vchName, vector<unsigned char>& vchValue, int& nHeight)
{
vector<CDiskTxPos> vtxPos;
if (!dbName.ReadName(vchName, vtxPos) || vtxPos.empty())
return false;
CDiskTxPos& txPos = vtxPos.back();
uint256 hash;
return GetValueOfTxPos(txPos, vchValue, hash, nHeight);
}
bool GetTxOfName(CNameDB& dbName, vector<unsigned char> vchName, CTransaction& tx)
{
vector<CDiskTxPos> vtxPos;
if (!dbName.ReadName(vchName, vtxPos) || vtxPos.empty())
return false;
CDiskTxPos& txPos = vtxPos.back();
int nHeight = GetTxPosHeight(txPos);
if (nHeight + GetExpirationDepth(pindexBest->nHeight) < pindexBest->nHeight)
{
string name = stringFromVch(vchName);
printf("GetTxOfName(%s) : expired", name.c_str());
return false;
}
if (!tx.ReadFromDisk(txPos))
return error("GetTxOfName() : could not read tx from disk");
return true;
}
Value name_list(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"name_list [<name>]\n"
"list my own names"
);
vector<unsigned char> vchName;
vector<unsigned char> vchLastName;
int nMax = 500;
Array oRes;
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
for (;;)
{
CNameDB dbName("r");
vector<pair<vector<unsigned char>, CDiskTxPos> > nameScan;
if (!dbName.ScanNames(vchName, nMax, nameScan))
throw JSONRPCError(-4, "scan failed");
pair<vector<unsigned char>, CDiskTxPos> pairScan;
BOOST_FOREACH(pairScan, nameScan)
{
// skip previous last
if (pairScan.first == vchLastName)
continue;
vchLastName = pairScan.first;
string name = stringFromVch(pairScan.first);
CDiskTxPos txPos = pairScan.second;
vector<unsigned char> vchValue;
int nHeight;
uint256 hash;
if (!txPos.IsNull() &&
GetValueOfTxPos(txPos, vchValue, hash, nHeight) &&
pwalletMain->mapWallet.count(hash)
)
{
string value = stringFromVch(vchValue);
Object oName;
oName.push_back(Pair("name", name));
oName.push_back(Pair("value", value));
if (!hooks->IsMine(pwalletMain->mapWallet[hash]))
oName.push_back(Pair("transferred", 1));
oName.push_back(Pair("expires_in", nHeight + GetDisplayExpirationDepth(nHeight) - pindexBest->nHeight));
oRes.push_back(oName);
}
}
// break if nothing more
if (vchName == vchLastName)
break;
vchName = vchLastName;
}
return oRes;
}
Value name_debug(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 0)
throw runtime_error(
"name_debug\n"
"Dump pending transactions id in the debug file.\n");
printf("Pending:\n----------------------------\n");
pair<vector<unsigned char>, set<uint256> > pairPending;
CRITICAL_BLOCK(cs_main)
BOOST_FOREACH(pairPending, mapNamePending)
{
string name = stringFromVch(pairPending.first);
printf("%s :\n", name.c_str());
uint256 hash;
BOOST_FOREACH(hash, pairPending.second)
{
printf(" ");
if (!pwalletMain->mapWallet.count(hash))
printf("foreign ");
printf(" %s\n", hash.GetHex().c_str());
}
}
printf("----------------------------\n");
return true;
}
Value name_debug1(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1)
throw runtime_error(
"name_debug1 <name>\n"
"Dump name blocks number and transactions id in the debug file.\n");
vector<unsigned char> vchName = vchFromValue(params[0]);
printf("Dump name:\n");
CRITICAL_BLOCK(cs_main)
{
vector<CDiskTxPos> vtxPos;
CNameDB dbName("r");
if (!dbName.ReadName(vchName, vtxPos))
{
error("failed to read from name DB");
return false;
}
CDiskTxPos txPos;
BOOST_FOREACH(txPos, vtxPos)
{
CTransaction tx;
if (!tx.ReadFromDisk(txPos))
{
error("could not read txpos %s", txPos.ToString().c_str());
continue;
}
printf("@%d %s\n", GetTxPosHeight(txPos), tx.GetHash().GetHex().c_str());
}
}
printf("-------------------------\n");
return true;
}
Value name_history(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1)
throw runtime_error(
"name_history <name>\n"
"List all name values of a name.\n");
Array oRes;
vector<unsigned char> vchName = vchFromValue(params[0]);
string name = stringFromVch(vchName);
CRITICAL_BLOCK(cs_main)
{
vector<CDiskTxPos> vtxPos;
CNameDB dbName("r");
if (!dbName.ReadName(vchName, vtxPos))
throw JSONRPCError(-4, "failed to read from name DB");
CDiskTxPos txPos;
BOOST_FOREACH(txPos, vtxPos)
{
CTransaction tx;
if (!tx.ReadFromDisk(txPos))
{
error("could not read txpos %s", txPos.ToString().c_str());
continue;
}
Object oName;
vector<unsigned char> vchValue;
int nHeight;
uint256 hash;
if (!txPos.IsNull() && GetValueOfTxPos(txPos, vchValue, hash, nHeight))
{
oName.push_back(Pair("name", name));
string value = stringFromVch(vchValue);
oName.push_back(Pair("value", value));
oName.push_back(Pair("txid", tx.GetHash().GetHex()));
oName.push_back(Pair("expires_in", nHeight + GetDisplayExpirationDepth(nHeight) - pindexBest->nHeight));
oRes.push_back(oName);
}
}
}
return oRes;
}
Value name_scan(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"name_scan [<start-name>] [<max-returned>]\n"
"scan all names, starting at start-name and returning a maximum number of entries (default 500)\n"
);
vector<unsigned char> vchName;
int nMax = 500;
if (params.size() > 0)
{
vchName = vchFromValue(params[0]);
}
if (params.size() > 1)
{
Value vMax = params[1];
ConvertTo<double>(vMax);
nMax = (int)vMax.get_real();
}
CNameDB dbName("r");
Array oRes;
vector<pair<vector<unsigned char>, CDiskTxPos> > nameScan;
if (!dbName.ScanNames(vchName, nMax, nameScan))
throw JSONRPCError(-4, "scan failed");
pair<vector<unsigned char>, CDiskTxPos> pairScan;
BOOST_FOREACH(pairScan, nameScan)
{
Object oName;
string name = stringFromVch(pairScan.first);
CDiskTxPos txPos = pairScan.second;
oName.push_back(Pair("name", name));
vector<unsigned char> vchValue;
int nHeight;
uint256 hash;
if (!txPos.IsNull() && GetValueOfTxPos(txPos, vchValue, hash, nHeight))
{
string value = stringFromVch(vchValue);
oName.push_back(Pair("value", value));
oName.push_back(Pair("txid", hash.GetHex()));
oName.push_back(Pair("expires_in", nHeight + GetDisplayExpirationDepth(nHeight) - pindexBest->nHeight));
}
else
{
oName.push_back(Pair("expired", 1));
}
oRes.push_back(oName);
}
if (NAME_DEBUG) {
dbName.test();
}
return oRes;
}
Value name_firstupdate(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 4)
throw runtime_error(
"name_firstupdate <name> <rand> [<tx>] <value>\n"
"Perform a first update after a name_new reservation.\n"
"Note that the first update will go into a block 12 blocks after the name_new, at the soonest."
);
vector<unsigned char> vchName = vchFromValue(params[0]);
vector<unsigned char> vchRand = ParseHex(params[1].get_str());
vector<unsigned char> vchValue;
if (params.size() == 3)
{
vchValue = vchFromValue(params[2]);
}
else
{
vchValue = vchFromValue(params[3]);
}
CWalletTx wtx;
wtx.nVersion = NAMECOIN_TX_VERSION;
CRITICAL_BLOCK(cs_main)
{
if (mapNamePending.count(vchName) && mapNamePending[vchName].size())
{
error("name_firstupdate() : there are %d pending operations on that name, including %s",
mapNamePending[vchName].size(),
mapNamePending[vchName].begin()->GetHex().c_str());
throw runtime_error("there are pending operations on that name");
}
}
{
CNameDB dbName("r");
CTransaction tx;
if (GetTxOfName(dbName, vchName, tx))
{
error("name_firstupdate() : this name is already active with tx %s",
tx.GetHash().GetHex().c_str());
throw runtime_error("this name is already active");
}
}
CRITICAL_BLOCK(cs_main)
{
// Make sure there is a previous NAME_NEW tx on this name
// and that the random value matches
uint256 wtxInHash;
if (params.size() == 3)
{
if (!mapMyNames.count(vchName))
{
throw runtime_error("could not find a coin with this name, try specifying the name_new transaction id");
}
wtxInHash = mapMyNames[vchName];
}
else
{
wtxInHash.SetHex(params[2].get_str());
}
if (!pwalletMain->mapWallet.count(wtxInHash))
{
throw runtime_error("previous transaction is not in the wallet");
}
vector<unsigned char> strPubKey = pwalletMain->GetKeyFromKeyPool();
CScript scriptPubKeyOrig;
scriptPubKeyOrig.SetBitcoinAddress(strPubKey);
CScript scriptPubKey;
scriptPubKey << OP_NAME_FIRSTUPDATE << vchName << vchRand << vchValue << OP_2DROP << OP_2DROP;
scriptPubKey += scriptPubKeyOrig;
CWalletTx& wtxIn = pwalletMain->mapWallet[wtxInHash];
vector<unsigned char> vchHash;
bool found = false;
BOOST_FOREACH(CTxOut& out, wtxIn.vout)
{
vector<vector<unsigned char> > vvch;
int op;
if (DecodeNameScript(out.scriptPubKey, op, vvch)) {
if (op != OP_NAME_NEW)
throw runtime_error("previous transaction wasn't a name_new");
vchHash = vvch[0];
found = true;
}
}
if (!found)
{
throw runtime_error("previous tx on this name is not a name tx");
}
vector<unsigned char> vchToHash(vchRand);
vchToHash.insert(vchToHash.end(), vchName.begin(), vchName.end());
uint160 hash = Hash160(vchToHash);
if (uint160(vchHash) != hash)
{
throw runtime_error("previous tx used a different random value");
}
int64 nNetFee = GetNetworkFee(pindexBest->nHeight);
// Round up to CENT
nNetFee += CENT - 1;
nNetFee = (nNetFee / CENT) * CENT;
string strError = SendMoneyWithInputTx(scriptPubKey, MIN_AMOUNT, nNetFee, wtxIn, wtx, false);
if (strError != "")
throw JSONRPCError(-4, strError);
}
return wtx.GetHash().GetHex();
}
Value name_update(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw runtime_error(
"name_update <name> <value> [<toaddress>]\nUpdate and possibly transfer a name\n"
);
vector<unsigned char> vchName = vchFromValue(params[0]);
vector<unsigned char> vchValue = vchFromValue(params[1]);
CWalletTx wtx;
wtx.nVersion = NAMECOIN_TX_VERSION;
vector<unsigned char> strPubKey = pwalletMain->GetKeyFromKeyPool();
CScript scriptPubKeyOrig;
if (params.size() == 3)
{
string strAddress = params[2].get_str();
uint160 hash160;
bool isValid = AddressToHash160(strAddress, hash160);
if (!isValid)
throw JSONRPCError(-5, "Invalid namecoin address");
scriptPubKeyOrig.SetBitcoinAddress(strAddress);
}
else
{
scriptPubKeyOrig.SetBitcoinAddress(strPubKey);
}
CScript scriptPubKey;
scriptPubKey << OP_NAME_UPDATE << vchName << vchValue << OP_2DROP << OP_DROP;
scriptPubKey += scriptPubKeyOrig;
CRITICAL_BLOCK(cs_main)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
if (mapNamePending.count(vchName) && mapNamePending[vchName].size())
{
error("name_update() : there are %d pending operations on that name, including %s",
mapNamePending[vchName].size(),
mapNamePending[vchName].begin()->GetHex().c_str());
throw runtime_error("there are pending operations on that name");
}
CNameDB dbName("r");
CTransaction tx;
if (!GetTxOfName(dbName, vchName, tx))
{
throw runtime_error("could not find a coin with this name");
}
uint256 wtxInHash = tx.GetHash();
if (!pwalletMain->mapWallet.count(wtxInHash))
{
error("name_update() : this coin is not in your wallet %s",
wtxInHash.GetHex().c_str());
throw runtime_error("this coin is not in your wallet");
}
CWalletTx& wtxIn = pwalletMain->mapWallet[wtxInHash];
string strError = SendMoneyWithInputTx(scriptPubKey, MIN_AMOUNT, 0, wtxIn, wtx, false);
if (strError != "")
throw JSONRPCError(-4, strError);
}
return wtx.GetHash().GetHex();
}
Value name_new(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"name_new <name>\n"
);
vector<unsigned char> vchName = vchFromValue(params[0]);
CWalletTx wtx;
wtx.nVersion = NAMECOIN_TX_VERSION;
uint64 rand = GetRand((uint64)-1);
vector<unsigned char> vchRand = CBigNum(rand).getvch();
vector<unsigned char> vchToHash(vchRand);
vchToHash.insert(vchToHash.end(), vchName.begin(), vchName.end());
uint160 hash = Hash160(vchToHash);
vector<unsigned char> strPubKey = pwalletMain->GetKeyFromKeyPool();
CScript scriptPubKeyOrig;
scriptPubKeyOrig.SetBitcoinAddress(strPubKey);
CScript scriptPubKey;
scriptPubKey << OP_NAME_NEW << hash << OP_2DROP;
scriptPubKey += scriptPubKeyOrig;
CRITICAL_BLOCK(cs_main)
{
string strError = pwalletMain->SendMoney(scriptPubKey, MIN_AMOUNT, wtx, false);
if (strError != "")
throw JSONRPCError(-4, strError);
mapMyNames[vchName] = wtx.GetHash();
}
vector<Value> res;
res.push_back(wtx.GetHash().GetHex());
res.push_back(HexStr(vchRand));
return res;
}
void UnspendInputs(CWalletTx& wtx)
{
set<CWalletTx*> setCoins;
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
if (!pwalletMain->IsMine(txin))
{
printf("UnspendInputs(): !mine %s", txin.ToString().c_str());
continue;
}
CWalletTx& prev = pwalletMain->mapWallet[txin.prevout.hash];
int nOut = txin.prevout.n;
printf("UnspendInputs(): %s:%d spent %d\n", prev.GetHash().ToString().c_str(), nOut, prev.IsSpent(nOut));
if (nOut >= prev.vout.size())
throw runtime_error("CWalletTx::MarkSpent() : nOut out of range");
prev.vfSpent.resize(prev.vout.size());
if (prev.vfSpent[nOut])
{
prev.vfSpent[nOut] = false;
prev.fAvailableCreditCached = false;
prev.WriteToDisk();
}
pwalletMain->vWalletUpdated.push_back(prev.GetHash());
}
}
Value deletetransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"deletetransaction <txid>\nNormally used when a transaction cannot be confirmed due to a double spend.\nRestart the program after executing this call.\n"
);
if (params.size() != 1)
throw runtime_error("missing txid");
CRITICAL_BLOCK(cs_main)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
uint256 hash;
hash.SetHex(params[0].get_str());
if (!pwalletMain->mapWallet.count(hash))
throw runtime_error("transaction not in wallet");
if (!mapTransactions.count(hash))
throw runtime_error("transaction not in memory - is already in blockchain?");
CWalletTx wtx = pwalletMain->mapWallet[hash];
UnspendInputs(wtx);
// We are not removing from mapTransactions because this can cause memory corruption
// during mining. The user should restart to clear the tx from memory.
wtx.RemoveFromMemoryPool();
pwalletMain->EraseFromWallet(wtx.GetHash());
vector<unsigned char> vchName;
if (GetNameOfTx(wtx, vchName) && mapNamePending.count(vchName)) {
printf("deletetransaction() : remove from pending");
mapNamePending[vchName].erase(wtx.GetHash());
}
return "success, please restart program to clear memory";
}
}
Value name_clean(const Array& params, bool fHelp)
{
if (fHelp || params.size())
throw runtime_error("name_clean\nClean unsatisfiable transactions from the wallet - including name_update on an already taken name\n");
CRITICAL_BLOCK(cs_main)
CRITICAL_BLOCK(pwalletMain->cs_mapWallet)
{
map<uint256, CWalletTx> mapRemove;
printf("-----------------------------\n");
{