This repository has been archived by the owner on Feb 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
mainchainBMM.diff
5447 lines (5252 loc) · 192 KB
/
mainchainBMM.diff
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
diff --git a/src/base58.cpp b/src/base58.cpp
index 499afbe38..72b51eed5 100644
--- a/src/base58.cpp
+++ b/src/base58.cpp
@@ -121,6 +121,29 @@ bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
return DecodeBase58(str.c_str(), vchRet);
}
+bool CBitcoinAddress::GetKeyID(CKeyID& keyID) const
+ {
+ if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
+ return false;
+ uint160 id;
+ memcpy(&id, vchData.data(), 20);
+ keyID = CKeyID(id);
+ return true;
+ }
+
+ bool CBitcoinAddress::IsValid() const
+{
+ return IsValid(Params());
+}
+
+bool CBitcoinAddress::IsValid(const CChainParams& params) const
+{
+ bool fCorrectSize = vchData.size() == 20;
+ bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
+ vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
+ return fCorrectSize && fKnownVersion;
+}
+
std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
@@ -213,6 +236,60 @@ int CBase58Data::CompareTo(const CBase58Data& b58) const
return 0;
}
+bool CSidechainAddress::Set(const CKeyID& id)
+{
+ SetData(Params().Base58Prefix(CChainParams::SIDECHAIN_PUBKEY_ADDRESS), &id, 20);
+ return true;
+}
+
+bool CSidechainAddress::Set(const CScriptID& id)
+{
+ SetData(Params().Base58Prefix(CChainParams::SIDECHAIN_SCRIPT_ADDRESS), &id, 20);
+ return true;
+}
+
+bool CSidechainAddress::IsValid() const
+{
+ return IsValid(Params());
+}
+
+bool CSidechainAddress::IsValid(const CChainParams& params) const
+{
+ bool fCorrectSize = vchData.size() == 20;
+ bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::SIDECHAIN_PUBKEY_ADDRESS) ||
+ vchVersion == params.Base58Prefix(CChainParams::SIDECHAIN_SCRIPT_ADDRESS);
+ return fCorrectSize && fKnownVersion;
+}
+
+CTxDestination CSidechainAddress::Get() const
+{
+ if (!IsValid())
+ return CNoDestination();
+ uint160 id;
+ memcpy(&id, &vchData[0], 20);
+ if (vchVersion == Params().Base58Prefix(CChainParams::SIDECHAIN_PUBKEY_ADDRESS))
+ return CKeyID(id);
+ else if (vchVersion == Params().Base58Prefix(CChainParams::SIDECHAIN_SCRIPT_ADDRESS))
+ return CScriptID(id);
+ else
+ return CNoDestination();
+}
+
+bool CSidechainAddress::GetKeyID(CKeyID& keyID) const
+{
+ if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::SIDECHAIN_PUBKEY_ADDRESS))
+ return false;
+ uint160 id;
+ memcpy(&id, &vchData[0], 20);
+ keyID = CKeyID(id);
+ return true;
+}
+
+bool CSidechainAddress::IsScript() const
+{
+ return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SIDECHAIN_SCRIPT_ADDRESS);
+}
+
namespace
{
class DestinationEncoder : public boost::static_visitor<std::string>
diff --git a/src/base58.h b/src/base58.h
index 39eb4eacc..a8e285a63 100644
--- a/src/base58.h
+++ b/src/base58.h
@@ -94,6 +94,47 @@ public:
bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; }
};
+/** Base58 encoded Sidechain address */
+class CSidechainAddress : public CBase58Data {
+public:
+ bool Set(const CKeyID &id);
+ bool Set(const CScriptID &id);
+ bool IsValid() const;
+ bool IsValid(const CChainParams ¶ms) const;
+
+ CSidechainAddress() {}
+ CSidechainAddress(const std::string& strAddress) { SetString(strAddress); }
+ CSidechainAddress(const char* pszAddress) { SetString(pszAddress); }
+
+ CTxDestination Get() const;
+ bool GetKeyID(CKeyID &keyID) const;
+ bool IsScript() const;
+};
+
+/** base58-encoded Bitcoin addresses.
+ * Public-key-hash-addresses have version 0 (or 111 testnet).
+ * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
+ * Script-hash-addresses have version 5 (or 196 testnet).
+ * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
+ */
+class CBitcoinAddress : public CBase58Data {
+public:
+ bool Set(const CKeyID &id);
+ bool Set(const CScriptID &id);
+ bool Set(const CTxDestination &dest);
+ bool IsValid() const;
+ bool IsValid(const CChainParams ¶ms) const;
+
+ CBitcoinAddress() {}
+ CBitcoinAddress(const CTxDestination &dest) { Set(dest); }
+ CBitcoinAddress(const std::string& strAddress) { SetString(strAddress); }
+ CBitcoinAddress(const char* pszAddress) { SetString(pszAddress); }
+
+ CTxDestination Get() const;
+ bool GetKeyID(CKeyID &keyID) const;
+ bool IsScript() const;
+};
+
/**
* A base58-encoded secret key
*/
diff --git a/src/chain.cpp b/src/chain.cpp
index 79e8bdfa4..435ef6d6b 100644
--- a/src/chain.cpp
+++ b/src/chain.cpp
@@ -5,6 +5,8 @@
#include <chain.h>
+int nCoinbaseCached = 0;
+
/**
* CChain implementation
*/
diff --git a/src/chain.h b/src/chain.h
old mode 100644
new mode 100755
index 3728f768c..af770bbb7
--- a/src/chain.h
+++ b/src/chain.h
@@ -8,12 +8,23 @@
#include <arith_uint256.h>
#include <primitives/block.h>
+#include <primitives/transaction.h>
#include <pow.h>
+#include <sidechain.h>
#include <tinyformat.h>
#include <uint256.h>
#include <vector>
+//! Number of coinbase(s) chainActive has cached
+extern int nCoinbaseCached;
+
+/** Target size limit of coinbase cache */
+static const int COINBASE_CACHE_TARGET = SIDECHAIN_VERIFICATION_PERIOD;
+
+/** How many blocks to wait between pruning cache */
+static const int COINBASE_CACHE_PRUNE_INTERVAL = 50;
+
/**
* Maximum amount of time that a block timestamp is allowed to exceed the
* current network-adjusted time before the block will be accepted.
@@ -219,6 +230,12 @@ public:
//! (memory only) Maximum nTime in the chain up to and including this block.
unsigned int nTimeMax;
+ //! Should a coinbase be cached for this block?
+ bool fCoinbase;
+
+ //! Cached coinbase for this block
+ CTransactionRef coinbase;
+
void SetNull()
{
phashBlock = nullptr;
@@ -240,6 +257,9 @@ public:
nTime = 0;
nBits = 0;
nNonce = 0;
+
+ fCoinbase = false;
+ coinbase = NULL;
}
CBlockIndex()
@@ -405,6 +425,18 @@ public:
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
+
+ // Coinbase cache
+ READWRITE(fCoinbase);
+ if (fCoinbase)
+ READWRITE(coinbase);
+ else
+ if (coinbase && !ser_action.ForRead()) {
+ // TODO improve
+ // Reduce size on disk by replacing coinbase with blank tx
+ CTransactionRef tx = MakeTransactionRef(CTransaction());
+ READWRITE(tx);
+ }
}
uint256 GetBlockHash() const
diff --git a/src/chainparams.cpp b/src/chainparams.cpp
old mode 100644
new mode 100755
index 6eb223171..e2f7f66d1
--- a/src/chainparams.cpp
+++ b/src/chainparams.cpp
@@ -101,6 +101,11 @@ public:
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1479168000; // November 15th, 2016.
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1510704000; // November 15th, 2017.
+ // Deployment of Drivechains (BIPX, BIPY)
+ consensus.vDeployments[Consensus::DEPLOYMENT_DRIVECHAINS].bit = 4;
+ consensus.vDeployments[Consensus::DEPLOYMENT_DRIVECHAINS].nStartTime = 1515974401; // January 15th, 2018.
+ consensus.vDeployments[Consensus::DEPLOYMENT_DRIVECHAINS].nTimeout = 1547510401; // January 15th, 2019.
+
// The best chain should have at least this much work.
consensus.nMinimumChainWork = uint256S("0x000000000000000000000000000000000000000000f91c579d57cad4bc5278cc");
@@ -138,6 +143,8 @@ public:
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,0);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,5);
+ base58Prefixes[SIDECHAIN_PUBKEY_ADDRESS] = std::vector<unsigned char>(1,8);
+ base58Prefixes[SIDECHAIN_SCRIPT_ADDRESS] = std::vector<unsigned char>(1,63);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,128);
base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x88, 0xB2, 0x1E};
base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x88, 0xAD, 0xE4};
@@ -212,6 +219,11 @@ public:
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1462060800; // May 1st 2016
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1493596800; // May 1st 2017
+ // Deployment of Drivechains (BIPX, BIPY)
+ consensus.vDeployments[Consensus::DEPLOYMENT_DRIVECHAINS].bit = 4;
+ consensus.vDeployments[Consensus::DEPLOYMENT_DRIVECHAINS].nStartTime = 1515974401; // January 15th, 2018.
+ consensus.vDeployments[Consensus::DEPLOYMENT_DRIVECHAINS].nTimeout = 1547510401; // January 15th, 2019.
+
// The best chain should have at least this much work.
consensus.nMinimumChainWork = uint256S("0x00000000000000000000000000000000000000000000002830dab7f76dbb7d63");
@@ -240,6 +252,8 @@ public:
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,111);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196);
+ base58Prefixes[SIDECHAIN_PUBKEY_ADDRESS] = std::vector<unsigned char>(1,8);
+ base58Prefixes[SIDECHAIN_SCRIPT_ADDRESS] = std::vector<unsigned char>(1,63);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239);
base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x35, 0x87, 0xCF};
base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x35, 0x83, 0x94};
@@ -299,6 +313,10 @@ public:
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = Consensus::BIP9Deployment::ALWAYS_ACTIVE;
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT;
+ consensus.vDeployments[Consensus::DEPLOYMENT_DRIVECHAINS].bit = 4;
+ consensus.vDeployments[Consensus::DEPLOYMENT_DRIVECHAINS].nStartTime = Consensus::BIP9Deployment::ALWAYS_ACTIVE;
+ consensus.vDeployments[Consensus::DEPLOYMENT_DRIVECHAINS].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT;
+
// The best chain should have at least this much work.
consensus.nMinimumChainWork = uint256S("0x00");
@@ -338,6 +356,8 @@ public:
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,111);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196);
+ base58Prefixes[SIDECHAIN_PUBKEY_ADDRESS] = std::vector<unsigned char>(1,8);
+ base58Prefixes[SIDECHAIN_SCRIPT_ADDRESS] = std::vector<unsigned char>(1,63);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239);
base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x35, 0x87, 0xCF};
base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x35, 0x83, 0x94};
diff --git a/src/chainparams.h b/src/chainparams.h
index d478da989..5c7f863d8 100644
--- a/src/chainparams.h
+++ b/src/chainparams.h
@@ -44,6 +44,8 @@ public:
enum Base58Type {
PUBKEY_ADDRESS,
SCRIPT_ADDRESS,
+ SIDECHAIN_PUBKEY_ADDRESS,
+ SIDECHAIN_SCRIPT_ADDRESS,
SECRET_KEY,
EXT_PUBLIC_KEY,
EXT_SECRET_KEY,
diff --git a/src/coins.cpp b/src/coins.cpp
old mode 100644
new mode 100755
index 8dfb35c2e..d1703d0f6
--- a/src/coins.cpp
+++ b/src/coins.cpp
@@ -6,6 +6,8 @@
#include <consensus/consensus.h>
#include <random.h>
+#include <sidechain.h>
+#include <utilstrencodings.h>
bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const { return false; }
uint256 CCoinsView::GetBestBlock() const { return uint256(); }
@@ -91,7 +93,17 @@ void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight, bool
bool overwrite = check ? cache.HaveCoin(COutPoint(txid, i)) : fCoinbase;
// Always set the possible_overwrite flag to AddCoin for coinbase txn, in order to correctly
// deal with the pre-BIP30 occurrences of duplicate coinbase transactions.
- cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), overwrite);
+ if (tx.criticalData.IsNull()) {
+ cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase, false), overwrite);
+ } else {
+ uint8_t nSidechain;
+ uint16_t nPrevBlockRef;
+ if (tx.criticalData.IsBMMRequest(nSidechain, nPrevBlockRef)) {
+ cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase, true, nSidechain, nPrevBlockRef, tx.criticalData.hashCritical), overwrite);
+ } else {
+ cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase, true), overwrite);
+ }
+ }
}
}
@@ -232,13 +244,25 @@ CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const
return nResult;
}
-bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
+bool CCoinsViewCache::HaveInputs(const CTransaction& tx, bool* fSidechainInputs, uint8_t* nSidechain) const
{
if (!tx.IsCoinBase()) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
if (!HaveCoin(tx.vin[i].prevout)) {
return false;
}
+
+ // Optionally check for Sidechain UTXO inputs
+ if (fSidechainInputs && nSidechain) {
+ const Coin &coin = AccessCoin(tx.vin[i].prevout);
+
+ auto vsf = ValidSidechainField.find(HexStr(coin.out.scriptPubKey));
+ if (vsf != ValidSidechainField.end()) {
+ *fSidechainInputs = true;
+ *nSidechain = vsf->second;
+ break;
+ }
+ }
}
}
return true;
diff --git a/src/coins.h b/src/coins.h
old mode 100644
new mode 100755
index c6850947e..9b1e7b908
--- a/src/coins.h
+++ b/src/coins.h
@@ -32,34 +32,54 @@ public:
//! unspent transaction output
CTxOut out;
+ //! at which height this containing transaction was included in the active block chain
+ uint32_t nHeight : 31;
+
//! whether containing transaction was a coinbase
unsigned int fCoinBase : 1;
- //! at which height this containing transaction was included in the active block chain
- uint32_t nHeight : 31;
+ //! whether containing transaction has critical data
+ bool fCriticalData;
+
+ //! TODO Memory Only
+ uint8_t nSidechain;
+ uint16_t nPrevBlockRef;
+ uint256 hashCritical;
//! construct a Coin from a CTxOut and height/coinbase information.
- Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {}
- Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {}
+ Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn, bool fCriticalDataIn, uint8_t nSidechainIn = 0, uint16_t nPrevBlockRefIn = 0, uint256 hashCriticalIn = uint256()) : out(std::move(outIn)), nHeight(nHeightIn), fCoinBase(fCoinBaseIn), fCriticalData(fCriticalDataIn), nSidechain(nSidechainIn), nPrevBlockRef(nPrevBlockRefIn), hashCritical(hashCriticalIn) {}
+ Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn, bool fCriticalDataIn, uint8_t nSidechainIn = 0, uint16_t nPrevBlockRefIn = 0, uint256 hashCriticalIn = uint256()) : out(outIn), nHeight(nHeightIn), fCoinBase(fCoinBaseIn), fCriticalData(fCriticalDataIn), nSidechain(nSidechainIn), nPrevBlockRef(nPrevBlockRefIn), hashCritical(hashCriticalIn) {}
void Clear() {
out.SetNull();
fCoinBase = false;
+ fCriticalData = false;
+ nSidechain = 0;
+ nPrevBlockRef = 0;
+ hashCritical.SetNull();
nHeight = 0;
}
//! empty constructor
- Coin() : fCoinBase(false), nHeight(0) { }
+ Coin() : nHeight(0), fCoinBase(false), fCriticalData(false), nSidechain(0), nPrevBlockRef(0), hashCritical(uint256()) { }
bool IsCoinBase() const {
return fCoinBase;
}
+ bool IsCriticalData() const {
+ return fCriticalData;
+ }
+
template<typename Stream>
void Serialize(Stream &s) const {
assert(!IsSpent());
uint32_t code = nHeight * 2 + fCoinBase;
::Serialize(s, VARINT(code));
+ ::Serialize(s, fCriticalData);
+ ::Serialize(s, VARINT(nSidechain));
+ ::Serialize(s, VARINT(nPrevBlockRef));
+ ::Serialize(s, hashCritical);
::Serialize(s, CTxOutCompressor(REF(out)));
}
@@ -69,6 +89,10 @@ public:
::Unserialize(s, VARINT(code));
nHeight = code >> 1;
fCoinBase = code & 1;
+ ::Unserialize(s, fCriticalData);
+ ::Unserialize(s, VARINT(nSidechain));
+ ::Unserialize(s, VARINT(nPrevBlockRef));
+ ::Unserialize(s, hashCritical);
::Unserialize(s, REF(CTxOutCompressor(out)));
}
@@ -203,7 +227,7 @@ class CCoinsViewCache : public CCoinsViewBacked
protected:
/**
* Make mutable so that we can "fill the cache" even from Get-methods
- * declared as "const".
+ * declared as "const".
*/
mutable uint256 hashBlock;
mutable CCoinsMap cacheCoins;
@@ -280,7 +304,7 @@ public:
//! Calculate the size of the cache (in bytes)
size_t DynamicMemoryUsage() const;
- /**
+ /**
* Amount of bitcoins coming in to a transaction
* Note that lightweight clients may not know anything besides the hash of previous transactions,
* so may not be able to calculate this.
@@ -291,7 +315,8 @@ public:
CAmount GetValueIn(const CTransaction& tx) const;
//! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
- bool HaveInputs(const CTransaction& tx) const;
+ // Optionally return whether or not any sidechain UTXO inputs are spent by the tx.
+ bool HaveInputs(const CTransaction& tx, bool* fSidechainInputs = NULL, uint8_t* nSidechain = NULL) const;
private:
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
diff --git a/src/consensus/consensus.h b/src/consensus/consensus.h
old mode 100644
new mode 100755
index 650635a76..111a1c930
--- a/src/consensus/consensus.h
+++ b/src/consensus/consensus.h
@@ -23,6 +23,10 @@ static const int WITNESS_SCALE_FACTOR = 4;
static const size_t MIN_TRANSACTION_WEIGHT = WITNESS_SCALE_FACTOR * 60; // 60 is the lower bound for the size of a valid serialized CTransaction
static const size_t MIN_SERIALIZABLE_TRANSACTION_WEIGHT = WITNESS_SCALE_FACTOR * 10; // 10 is the lower bound for the size of a serialized CTransaction
+static const int BMM_MAX_LD = 4000;
+static const int BMM_MAX_PREVBLOCK = 100;
+static const int CRITICAL_DATA_MATURITY = 100;
+
/** Flags for nSequence and nLockTime locks */
/** Interpret sequence numbers as relative lock-time constraints. */
static constexpr unsigned int LOCKTIME_VERIFY_SEQUENCE = (1 << 0);
diff --git a/src/consensus/params.h b/src/consensus/params.h
old mode 100644
new mode 100755
index 4ef808c85..3b842faea
--- a/src/consensus/params.h
+++ b/src/consensus/params.h
@@ -18,6 +18,7 @@ enum DeploymentPos
DEPLOYMENT_TESTDUMMY,
DEPLOYMENT_CSV, // Deployment of BIP68, BIP112, and BIP113.
DEPLOYMENT_SEGWIT, // Deployment of BIP141, BIP143, and BIP147.
+ DEPLOYMENT_DRIVECHAINS, // Deployment of BIPX and BIPY.
// NOTE: Also add new deployments to VersionBitsDeploymentInfo in versionbits.cpp
MAX_VERSION_BITS_DEPLOYMENTS
};
diff --git a/src/consensus/tx_verify.cpp b/src/consensus/tx_verify.cpp
old mode 100644
new mode 100755
index be73d0a2f..0d601d799
--- a/src/consensus/tx_verify.cpp
+++ b/src/consensus/tx_verify.cpp
@@ -4,15 +4,16 @@
#include <consensus/tx_verify.h>
-#include <consensus/consensus.h>
-#include <primitives/transaction.h>
-#include <script/interpreter.h>
-#include <consensus/validation.h>
+#include "consensus.h"
+#include "primitives/transaction.h"
+#include "script/interpreter.h"
+#include "sidechaindb.h"
+#include "validation.h"
// TODO remove the following dependencies
-#include <chain.h>
-#include <coins.h>
-#include <utilmoneystr.h>
+#include "chain.h"
+#include "coins.h"
+#include "utilmoneystr.h"
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
{
@@ -210,11 +211,13 @@ bool Consensus::CheckTxInputs(const CTransaction& tx, CValidationState& state, c
// are the actual inputs available?
if (!inputs.HaveInputs(tx)) {
return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-missingorspent", false,
- strprintf("%s: inputs missing/spent", __func__));
+ strprintf("%s: inputs missing/spent", __func__));
}
CAmount nValueIn = 0;
- for (unsigned int i = 0; i < tx.vin.size(); ++i) {
+ CAmount nFees = 0;
+ for (unsigned int i = 0; i < tx.vin.size(); i++)
+ {
const COutPoint &prevout = tx.vin[i].prevout;
const Coin& coin = inputs.AccessCoin(prevout);
assert(!coin.IsSpent());
diff --git a/src/init.cpp b/src/init.cpp
old mode 100644
new mode 100755
index 84398d978..58f1c2fac
--- a/src/init.cpp
+++ b/src/init.cpp
@@ -7,46 +7,49 @@
#include <config/bitcoin-config.h>
#endif
-#include <init.h>
-
-#include <addrman.h>
-#include <amount.h>
-#include <chain.h>
-#include <chainparams.h>
-#include <checkpoints.h>
-#include <compat/sanity.h>
-#include <consensus/validation.h>
-#include <fs.h>
-#include <httpserver.h>
-#include <httprpc.h>
-#include <key.h>
-#include <validation.h>
-#include <miner.h>
-#include <netbase.h>
-#include <net.h>
-#include <net_processing.h>
-#include <policy/feerate.h>
-#include <policy/fees.h>
-#include <policy/policy.h>
-#include <rpc/server.h>
-#include <rpc/register.h>
-#include <rpc/safemode.h>
-#include <rpc/blockchain.h>
-#include <script/standard.h>
-#include <script/sigcache.h>
-#include <scheduler.h>
-#include <timedata.h>
-#include <txdb.h>
-#include <txmempool.h>
-#include <torcontrol.h>
-#include <ui_interface.h>
-#include <util.h>
-#include <utilmoneystr.h>
-#include <validationinterface.h>
+#include "init.h"
+
+#include "addrman.h"
+#include "amount.h"
+#include "chain.h"
+#include "chainparams.h"
+#include "checkpoints.h"
+#include "compat/sanity.h"
+#include "consensus/validation.h"
+#include "fs.h"
+#include "httpserver.h"
+#include "httprpc.h"
+#include "key.h"
+#include "validation.h"
+#include "miner.h"
+#include "netbase.h"
+#include "net.h"
+#include "net_processing.h"
+#include "policy/feerate.h"
+#include "policy/fees.h"
+#include "policy/policy.h"
+#include "rpc/server.h"
+#include "rpc/register.h"
+#include "rpc/blockchain.h"
+#include "script/standard.h"
+#include "script/sigcache.h"
+#include "scheduler.h"
+#include "sidechain.h"
+#include "sidechaindb.h"
+#include "timedata.h"
+#include "txdb.h"
+#include "txmempool.h"
+#include "torcontrol.h"
+#include "ui_interface.h"
+#include "util.h"
+#include "utilmoneystr.h"
+#include "validationinterface.h"
#ifdef ENABLE_WALLET
#include <wallet/init.h>
+#include <wallet/wallet.h>
#endif
-#include <warnings.h>
+#include "warnings.h"
+#include <algorithm>
#include <stdint.h>
#include <stdio.h>
#include <memory>
@@ -71,6 +74,7 @@ bool fFeeEstimatesInitialized = false;
static const bool DEFAULT_PROXYRANDOMIZE = true;
static const bool DEFAULT_REST_ENABLE = false;
static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
+static const bool DEFAULT_DISABLE_SAFEMODE = false;
std::unique_ptr<CConnman> g_connman;
std::unique_ptr<PeerLogicValidation> peerLogic;
@@ -1570,6 +1574,47 @@ bool AppInitMain()
}
}
+ bool drivechainsEnabled = IsDrivechainEnabled(chainActive.Tip(), chainparams.GetConsensus());
+
+ // Synchronize SCDB
+ if (drivechainsEnabled && chainActive.Tip() && (chainActive.Tip()->GetBlockHash() != scdb.GetHashBlockLastSeen()))
+ {
+ // Find out how many blocks we need to update SCDB
+ const int nHeight = chainActive.Height();
+ int nTail = nHeight;
+ for (const Sidechain& s : ValidSidechains) {
+ int nLastPeriod = s.GetLastVerificationPeriod(nHeight);
+ if (nLastPeriod < nTail)
+ nTail = nLastPeriod;
+ }
+
+ // Update SCDB
+ for (int i = nTail; i <= nHeight; i++) {
+ // Skip genesis block
+ if (i == 0)
+ continue;
+
+ CBlockIndex* pindex = chainActive[i];
+ // Check that block index exists
+ if (!pindex) {
+ LogPrintf("SCDB cannot read null block index. Exiting.\n");
+ return false;
+ }
+
+ // Check that coinbase is cached
+ if (!pindex->fCoinbase || !pindex->coinbase)
+ return InitError("Cannot initalize SCDB. Corrupt coinbase cache.\n");
+
+ // Update SCDB
+ std::string strError = "";
+ if (!scdb.Update(i, pindex->GetBlockHash(), pindex->coinbase->vout, strError)) {
+ if (strError != "")
+ LogPrintf("SCDB update error: %s\n", strError);
+ return InitError("Failed to initialize SCDB.\n");
+ }
+ }
+ }
+
// As LoadBlockIndex can take several minutes, it's possible the user
// requested to kill the GUI during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
@@ -1741,7 +1786,29 @@ bool AppInitMain()
#ifdef ENABLE_WALLET
StartWallets(scheduler);
+
+ if (drivechainsEnabled) {
+ for (CWalletRef pwallet : vpwallets) {
+ LOCK2(cs_main, pwallet->cs_wallet);
+ pwallet->MarkDirty();
+
+ // Watch sidechain deposit addresses
+ for (const Sidechain& sidechain : ValidSidechains) {
+ std::vector<unsigned char> data(ParseHex(std::string(sidechain.sidechainHex)));
+ CScript script(data.begin(), data.end());
+ if (!pwallet->HaveWatchOnly(script)) {
+ pwallet->AddWatchOnly(script, 0 /* nCreateTime */);
+ }
+
+ CTxDestination destination;
+ if (ExtractDestination(script, destination)) {
+ pwallet->SetAddressBook(destination, sidechain.GetSidechainName(), "receive");
+ }
+ }
+ }
+
+ }
#endif
- return true;
+ return !fRequestShutdown;
}
diff --git a/src/miner.cpp b/src/miner.cpp
old mode 100644
new mode 100755
index dda52790c..f81d7a02f
--- a/src/miner.cpp
+++ b/src/miner.cpp
@@ -3,28 +3,37 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
-#include <miner.h>
-
-#include <amount.h>
-#include <chain.h>
-#include <chainparams.h>
-#include <coins.h>
-#include <consensus/consensus.h>
-#include <consensus/tx_verify.h>
-#include <consensus/merkle.h>
-#include <consensus/validation.h>
-#include <hash.h>
-#include <validation.h>
-#include <net.h>
-#include <policy/feerate.h>
-#include <policy/policy.h>
-#include <pow.h>
-#include <primitives/transaction.h>
-#include <script/standard.h>
-#include <timedata.h>
-#include <util.h>
-#include <utilmoneystr.h>
-#include <validationinterface.h>
+#include "miner.h"
+
+#include "amount.h"
+#include "base58.h"
+#include "chain.h"
+#include "chainparams.h"
+#include "coins.h"
+#include "consensus/consensus.h"
+#include "consensus/tx_verify.h"
+#include "consensus/merkle.h"
+#include "consensus/validation.h"
+#include "hash.h"
+#include "validation.h"
+#include "net.h"
+#include "policy/feerate.h"
+#include "policy/policy.h"
+#include "pow.h"
+#include "primitives/transaction.h"
+#include "script/standard.h"
+#include "sidechain.h"
+#include "sidechaindb.h"
+#include "timedata.h"
+#include "txmempool.h"
+#include "util.h"
+#include "utilmoneystr.h"
+#include "utilstrencodings.h"
+#include "validationinterface.h"
+
+#ifdef ENABLE_WALLET
+#include "wallet/wallet.h"
+#endif
#include <algorithm>
#include <queue>
@@ -163,9 +172,31 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& sc
coinbaseTx.vin[0].prevout.SetNull();
coinbaseTx.vout.resize(1);
coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
+
+ bool drivechainsEnabled = IsDrivechainEnabled(pindexPrev, chainparams.GetConsensus());
+
+ if (drivechainsEnabled) {
+ // Add WT^(s) which have been validated
+ for (const Sidechain& s : ValidSidechains) {
+ CTransaction wtx = CreateWTPrimePayout(s.nSidechain);
+ if (wtx.vout.size() && wtx.vin.size())
+ pblock->vtx.push_back(MakeTransactionRef(std::move(wtx)));
+ }
+ }
+
coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
+
+ if (drivechainsEnabled) {
+ // We're generating the block, and will upvote the last WT^ by default.
+ if (scdb.HasState())
+ scdb.UpdateSCDBIndex(scdb.GetUpvotes());
+ GenerateSCDBHashMerkleRootCommitment(*pblock, chainparams.GetConsensus());
+ GenerateBMMHashMerkleRootCommitment(*pblock, chainparams.GetConsensus());
+ GenerateCriticalHashCommitment(*pblock, chainparams.GetConsensus());
+ }
+
pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus());
pblocktemplate->vTxFees[0] = -nFees;
@@ -273,6 +304,139 @@ int BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& already
return nDescendantsUpdated;
}
+CTransaction BlockAssembler::CreateWTPrimePayout(uint8_t nSidechain)
+{
+ // The WT^ that will be created
+ CMutableTransaction mtx;
+
+ if (!IsDrivechainEnabled(chainActive.Tip(), chainparams.GetConsensus()))
+ return mtx;
+
+#ifdef ENABLE_WALLET
+ if (!scdb.HasState())
+ return mtx;
+ if (!IsSidechainNumberValid(nSidechain))
+ return mtx;
+
+ const Sidechain& sidechain = ValidSidechains[nSidechain];
+
+ // TODO remove
+ if (nSidechain == SIDECHAIN_TEST) {
+ if (nHeight % SIDECHAIN_TEST_VERIFICATION_PERIOD != 0)
+ return mtx;
+ } else {
+ if (nHeight % SIDECHAIN_VERIFICATION_PERIOD != 0)
+ return mtx;
+ }
+
+
+ // Select the highest scoring B-WT^ for sidechain during verification period
+ uint256 hashBest = uint256();
+ uint16_t scoreBest = 0;
+ std::vector<SidechainWTPrimeState> vState = scdb.GetState(nSidechain);
+ for (const SidechainWTPrimeState& state : vState) {
+ if (state.nWorkScore > scoreBest || scoreBest == 0) {
+ hashBest = state.hashWTPrime;
+ scoreBest = state.nWorkScore;
+ }
+ }
+ if (hashBest == uint256())
+ return mtx;
+
+ // Is the selected B-WT^ verified?
+ // Different MIN_WORKSCORE requirement for test sidechain (for testing..)
+ if (nSidechain == SIDECHAIN_TEST) {
+ if (scoreBest < SIDECHAIN_TEST_MIN_WORKSCORE)
+ return mtx;
+ } else {
+ if (scoreBest < SIDECHAIN_MIN_WORKSCORE)
+ return mtx;
+ }
+
+ // Copy outputs from B-WT^
+ // Note that this shouldn't be changed to be more efficient by just copying
+ // the entire transaction. We should copy the outputs only.
+ std::vector<CTransaction> vWTPrime = scdb.GetWTPrimeCache();
+ for (const CTransaction& tx : vWTPrime) {
+ if (tx.GetHash() == hashBest) {
+ for (const CTxOut& out : tx.vout)
+ mtx.vout.push_back(out);
+ break;
+ }
+ }
+ if (!mtx.vout.size())
+ return mtx;
+
+ // Calculate the amount to be withdrawn by WT^
+ CAmount amtBWT = CAmount(0);
+ for (const CTxOut& out : mtx.vout) {
+ const CScript scriptPubKey = out.scriptPubKey;
+ if (HexStr(scriptPubKey) != sidechain.sidechainHex) {
+ amtBWT += out.nValue;
+ }
+ }
+
+ // Format sidechain change return script
+ CKeyID sidechainKey;
+ sidechainKey.SetHex(sidechain.sidechainKey);
+ CScript sidechainScript;
+ sidechainScript << OP_DUP << OP_HASH160 << ToByteVector(sidechainKey) << OP_EQUALVERIFY << OP_CHECKSIG;
+
+ // Add placeholder change return as last output
+ mtx.vout.push_back(CTxOut(0, sidechainScript));
+
+ // Get SCUTXO(s)
+ std::vector<COutput> vSidechainCoins;
+ for (CWalletRef pwallet : vpwallets) {
+ pwallet->AvailableSidechainCoins(vSidechainCoins, nSidechain);
+ }
+ if (!vSidechainCoins.size())
+ return mtx;
+
+ // Calculate amount returning to sidechain script
+ CAmount returnAmount = CAmount(0);
+ for (const COutput& output : vSidechainCoins) {
+ mtx.vin.push_back(CTxIn(output.tx->GetHash(), output.i));
+ returnAmount += output.tx->tx->vout[output.i].nValue;
+ mtx.vout.back().nValue += returnAmount;
+ }
+
+ // Subtract payout amount from sidechain change return
+ mtx.vout.back().nValue -= amtBWT;
+
+ if (mtx.vout.back().nValue < 0)
+ return mtx;
+ if (!mtx.vin.size())
+ return mtx;
+
+ CBitcoinSecret vchSecret;
+ bool fGood = vchSecret.SetString(sidechain.sidechainPriv);
+ if (!fGood)
+ return mtx;
+
+ CKey privKey = vchSecret.GetKey();
+ if (!privKey.IsValid())
+ return mtx;
+
+ // Set up keystore with sidechain's private key
+ CBasicKeyStore tempKeystore;
+ tempKeystore.AddKey(privKey);
+ const CKeyStore& keystoreConst = tempKeystore;
+
+ // Sign WT^ SCUTXO input
+ const CTransaction& txToSign = mtx;
+ TransactionSignatureCreator creator(&keystoreConst, &txToSign, 0, returnAmount - amtBWT);
+ SignatureData sigdata;
+ bool sigCreated = ProduceSignature(creator, sidechainScript, sigdata);
+ if (!sigCreated)
+ return mtx;
+
+ mtx.vin[0].scriptSig = sigdata.scriptSig;
+#endif
+
+ return mtx;
+}
+
// Skip entries in mapTx that are already in a block or are present
// in mapModifiedTx (which implies that the mapTx ancestor state is
// stale due to ancestor inclusion in the block)
diff --git a/src/miner.h b/src/miner.h
index 9c086332d..32341e9c5 100644
--- a/src/miner.h
+++ b/src/miner.h
@@ -190,6 +190,10 @@ private:
* state updated assuming given transactions are inBlock. Returns number
* of updated descendants. */
int UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded, indexed_modified_transaction_set &mapModifiedTx);
+
+ // SidechainDB
+ /** Returns a WT^ payout transaction for nSidechain if there is one */
+ CTransaction CreateWTPrimePayout(uint8_t nSidechain);
};
/** Modify the extranonce in a block */
diff --git a/src/policy/policy.cpp b/src/policy/policy.cpp
index bff58932b..97b784286 100644
--- a/src/policy/policy.cpp
+++ b/src/policy/policy.cpp
@@ -8,6 +8,7 @@
#include <policy/policy.h>
#include <consensus/validation.h>
+#include <chainparams.h>
#include <validation.h>
#include <coins.h>