/
71bdd18af3b2a025630d515c246e8bd34beef84a.patch
1755 lines (1689 loc) · 60.9 KB
/
71bdd18af3b2a025630d515c246e8bd34beef84a.patch
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
From 8fb90c7a6755cec4c1a1bfd1ee2fcfcfd3be7e69 Mon Sep 17 00:00:00 2001
From: Chris Double <chris.double@double.co.nz>
Date: Thu, 24 Nov 2011 18:58:15 +1300
Subject: [PATCH 1/3] Merged mining support (imported from namecoin)
---
contrib/merged-mine-proxy | 469 +++++++++++++++++++++++++++++++++++++++++++++
src/auxpow.cpp | 129 +++++++++++++
src/auxpow.h | 84 ++++++++
src/db.cpp | 4 +-
src/main.cpp | 139 +++++++++++++-
src/main.h | 74 +++++---
src/makefile.unix | 4 +-
src/rpc.cpp | 460 ++++++++++++++++++++++++++++++++++++++++++++-
8 files changed, 1324 insertions(+), 39 deletions(-)
create mode 100755 contrib/merged-mine-proxy
create mode 100644 src/auxpow.cpp
create mode 100644 src/auxpow.h
diff --git a/contrib/merged-mine-proxy b/contrib/merged-mine-proxy
new file mode 100755
index 0000000..4c38215
--- /dev/null
+++ b/contrib/merged-mine-proxy
@@ -0,0 +1,469 @@
+#!/usr/bin/python
+#
+# Copyright (c) 2011 Vince Durham
+# Distributed under the MIT/X11 software license, see the accompanying
+# file COPYING.
+#
+
+import logging
+import argparse
+import os
+import sys
+import traceback
+import json
+import base64
+import socket
+
+from datetime import datetime
+
+from twisted.internet import defer, reactor, threads
+from twisted.web import server, resource
+from twisted.internet.error import ConnectionRefusedError
+import twisted.internet.error
+from urlparse import urlsplit
+import httplib
+import thread
+
+__version__ = '0.2.2'
+
+'''
+merge-mine-proxy
+
+Run behind a pool or a miner to mine a parent chain and a set of auxiliary chains.
+
+Output is in the form:
+
+2011-07-07T00:00:00,solve,1,1,HASH
+
+Where the fields are:
+
+ * UTC date and time in ISO format
+ * The word "solve"
+ * 1 if the proof of work was accepted by the parent chain
+ * 1 if the proof of work was accepted by each aux chain
+ * HASH parent block hash
+
+'''
+
+AUX_UPDATE_INTERVAL = 5
+MERKLE_TREES_TO_KEEP = 24
+
+logger = logging.getLogger('merged-mine-proxy')
+logger.setLevel(logging.DEBUG)
+
+def reverse_chunks(s, l):
+ return ''.join(reversed([s[x:x+l] for x in xrange(0, len(s), l)]))
+
+def getresponse(http, path, postdata, headers):
+ http.request(path, 'POST', postdata, headers)
+ return http.getresponse().read()
+
+class Error(Exception):
+ def __init__(self, code, message, data=''):
+ if not isinstance(code, int):
+ raise TypeError('code must be an int')
+ if not isinstance(message, unicode):
+ raise TypeError('message must be a unicode')
+ self._code, self._message, self._data = code, message, data
+ def __str__(self):
+ return '%i %s %r' % (self._code, self._message, self._data)
+ def _to_obj(self):
+ return {
+ 'code': self._code,
+ 'message': self._message,
+ 'data': self._data,
+ }
+
+class Proxy(object):
+ def __init__(self, url):
+ (schema, netloc, path, query, fragment) = urlsplit(url)
+ auth = None
+ if netloc.find('@') >= 0:
+ (auth, netloc) = netloc.split("@")
+ if path == "":
+ path = "/"
+ self._url = "%s://%s%s" % (schema, netloc, path)
+ self._path = path
+ self._auth = auth
+ self._netloc = netloc
+ self._http = None
+
+ def callRemote(self, method, *params):
+ try:
+ if self._http is None:
+ (host, port) = self._netloc.split(":")
+ self._http = httplib.HTTPConnection(host, port)
+ try:
+ self._http.connect()
+ except socket.error:
+ raise httplib.HTTPException()
+
+ id_ = 0
+
+ headers = {
+ 'Content-Type': 'text/json',
+ }
+ if self._auth is not None:
+ headers['Authorization'] = 'Basic ' + base64.b64encode(self._auth)
+ resp = None
+
+ postdata=json.dumps({
+ 'jsonrpc': '2.0',
+ 'method': method,
+ 'params': params,
+ 'id': id_,
+ })
+
+ content = getresponse(self._http, self._path, postdata, headers)
+
+ resp = json.loads(content)
+
+ if resp['id'] != id_:
+ raise ValueError('invalid id')
+ if 'error' in resp and resp['error'] is not None:
+ raise Error(resp['error']['code'], resp['error']['message'])
+ return resp['result']
+ except httplib.HTTPException:
+ self._http = None
+ logger.error("Could not connect to %s", self._url)
+ raise Error(-32099, u'Could not connect to backend', self._url)
+
+ def __getattr__(self, attr):
+ if attr.startswith('rpc_'):
+ return lambda *params: self.callRemote(attr[len('rpc_'):], *params)
+ raise AttributeError('%r object has no attribute %r' % (self.__class__.__name__, attr))
+
+class Server(resource.Resource):
+ extra_headers = None
+
+ def render(self, request):
+ def finish(x):
+ if request._disconnected:
+ return
+ if x is not None:
+ request.write(x)
+ request.finish()
+
+ def finish_error(fail):
+ if request._disconnected:
+ return
+ request.setResponseCode(500) # won't do anything if already written to
+ request.write('---ERROR---')
+ request.finish()
+ fail.printTraceback()
+
+ defer.maybeDeferred(resource.Resource.render, self, request).addCallbacks(finish, finish_error)
+ return server.NOT_DONE_YET
+
+ @defer.inlineCallbacks
+ def render_POST(self, request):
+ # missing batching, 1.0 notifications
+ data = request.content.read()
+
+ if self.extra_headers is not None:
+ for name, value in self.extra_headers.iteritems():
+ request.setHeader(name, value)
+
+ try:
+ try:
+ req = json.loads(data)
+ except Exception:
+ raise RemoteError(-32700, u'Parse error')
+ except Error, e:
+ # id unknown
+ request.write(json.dumps({
+ 'jsonrpc': '2.0',
+ 'id': None,
+ 'result': None,
+ 'error': e._to_obj(),
+ }))
+
+ id_ = req.get('id', None)
+
+ try:
+ try:
+ method = req['method']
+ if not isinstance(method, unicode):
+ raise ValueError()
+ params = req.get('params', [])
+ if not isinstance(params, list):
+ raise ValueError()
+ except Exception:
+ raise Error(-32600, u'Invalid Request')
+
+ method_name = 'rpc_' + method
+ if not hasattr(self, method_name):
+ raise Error(-32601, u'Method not found')
+ method_meth = getattr(self, method_name)
+
+ df = defer.maybeDeferred(method_meth, *params)
+
+ if id_ is None:
+ return
+
+ try:
+ result = yield df
+ #except Error, e:
+ #w raise e
+ except Exception, e:
+ logger.error(str(e))
+ raise Error(-32099, u'Unknown error: ' + str(e))
+
+ res = json.dumps({
+ 'jsonrpc': '2.0',
+ 'id': id_,
+ 'result': result,
+ 'error': None,
+ })
+ request.setHeader('content-length', str(len(res)))
+ request.write(res)
+ except Error, e:
+ res = json.dumps({
+ 'jsonrpc': '2.0',
+ 'id': id_,
+ 'result': None,
+ 'error': e._to_obj(),
+ })
+ request.setHeader('content-length', str(len(res)))
+ request.write(res)
+
+class Listener(Server):
+ def __init__(self, parent, auxs, merkle_size, rewrite_target):
+ Server.__init__(self)
+ self.parent = parent
+ self.auxs = auxs
+ self.chain_ids = [None for i in auxs]
+ self.aux_targets = [None for i in auxs]
+ self.merkle_size = merkle_size
+ self.merkle_tree_queue = []
+ self.merkle_trees = {}
+ self.rewrite_target = None
+ if rewrite_target == 1:
+ self.rewrite_target = reverse_chunks("00000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffe", 2)
+ elif rewrite_target == 100:
+ self.rewrite_target = reverse_chunks("00000000028f5c28000000000000000000000000000000000000000000000000", 2)
+ if merkle_size > 255:
+ raise ValueError('merkle size up to 255')
+ self.putChild('', self)
+
+ def merkle_branch(self, chain_index, merkle_tree):
+ step = self.merkle_size
+ i1 = chain_index
+ j = 0
+ branch = []
+ while step > 1:
+ i = min(i1^1, step-1)
+ branch.append(merkle_tree[i + j])
+ i1 = i1 >> 1
+ j += step
+ step = (step + 1) / 2
+ return branch
+
+ def calc_merkle_index(self, chain):
+ chain_id = self.chain_ids[chain]
+ rand = 0 # nonce
+ rand = (rand * 1103515245 + 12345) & 0xffffffff;
+ rand += chain_id;
+ rand = (rand * 1103515245 + 12345) & 0xffffffff;
+ return rand % self.merkle_size
+
+ @defer.inlineCallbacks
+ def update_auxs(self):
+ # create merkle leaves with arbitrary initial value
+ merkle_leaves = [ ('0' * 63) + ("%02x" % x) for x in range(self.merkle_size) ]
+
+ # ask each aux chain for a block
+ for chain in range(len(self.auxs)):
+ aux_block = (yield self.auxs[chain].rpc_getauxblock())
+ aux_block_hash = aux_block['hash']
+ self.chain_ids[chain] = aux_block['chainid']
+ chain_merkle_index = self.calc_merkle_index(chain)
+ merkle_leaves[chain_merkle_index] = aux_block_hash
+ self.aux_targets[chain] = reverse_chunks(aux_block['target'], 2) # fix endian
+
+ # create merkle tree
+ merkle_tree = (yield self.parent.rpc_buildmerkletree(*merkle_leaves))
+ merkle_root = merkle_tree[-1]
+
+ if not self.merkle_trees.has_key(merkle_root):
+ # remember new tree
+ self.merkle_trees[merkle_root] = merkle_tree
+ self.merkle_tree_queue.append(merkle_root)
+ if len(self.merkle_tree_queue) > MERKLE_TREES_TO_KEEP:
+ # forget one tree
+ old_root = self.merkle_tree_queue.pop(0)
+ del self.merkle_trees[old_root]
+
+ def update_aux_process(self):
+ reactor.callLater(AUX_UPDATE_INTERVAL, self.update_aux_process)
+ self.update_auxs()
+
+ def rpc_getaux(self, data=None):
+ ''' Use this rpc call to get the aux chain merkle root and aux target. Pool software
+ can then call getworkaux(aux) instead of going through this proxy. It is enough to call this
+ once a second.
+ '''
+ try:
+ # Get aux based on the latest tree
+ merkle_root = self.merkle_tree_queue[-1]
+ # nonce = 0, one byte merkle size
+ aux = merkle_root + ("%02x000000" % self.merkle_size) + "00000000"
+ result = {'aux': aux}
+
+ if self.rewrite_target:
+ result['aux_target'] = self.rewrite_target
+ else:
+ # Find highest target
+ targets = []
+ targets.extend(self.aux_targets)
+ targets.sort()
+ result['aux_target'] = reverse_chunks(targets[-1], 2) # fix endian
+ return result
+ except Exception:
+ logger.error(traceback.format_exc())
+ raise
+
+ @defer.inlineCallbacks
+ def rpc_getwork(self, data=None):
+ ''' This rpc call generates bitcoin miner compatible work from data received
+ from the aux and parent chains.
+ '''
+ try:
+ if data:
+ # Submit work upstream
+ any_solved = False
+ aux_solved = []
+
+ # get merkle root
+ solution = (yield self.parent.rpc_getworkaux("", data))
+
+ if solution is False:
+ logger.error("stale work")
+ defer.returnValue(False)
+ return
+
+ parent_hash = solution['hash']
+ merkle_root = solution['aux'][:-16] # strip off size and nonce
+ if not self.merkle_trees.has_key(merkle_root):
+ logger.error("stale merkle root %s", merkle_root)
+ defer.returnValue(False)
+ return
+
+ merkle_tree = self.merkle_trees[merkle_root]
+
+ # submit to each aux chain
+ for chain in range(len(self.auxs)):
+ chain_merkle_index = self.calc_merkle_index(chain)
+ aux_solved.append(False)
+ # try submitting if under target
+ if self.aux_targets[chain] > parent_hash and not chain_merkle_index is None:
+ branch = self.merkle_branch(chain_merkle_index, merkle_tree)
+ proof = (
+ yield self.parent.rpc_getworkaux("", data, chain_merkle_index, *branch))
+ if proof is False:
+ logger.error("aux pow request rejected by parent, chain %d", chain)
+ else:
+ aux_hash = merkle_tree[chain_merkle_index]
+ aux_solved[-1] = (
+ yield self.auxs[chain].rpc_getauxblock(aux_hash, proof['auxpow']))
+ any_solved = any_solved or aux_solved[-1]
+
+ # submit to parent
+ parent_solved = (yield self.parent.rpc_getworkaux("submit", data))
+ any_solved = any_solved or parent_solved
+
+ logger.info("%s,solve,%s,%s,%s", datetime.utcnow().isoformat(),
+ "1" if parent_solved else "0",
+ ",".join(["1" if solve else "0" for solve in aux_solved]),
+ parent_hash)
+ defer.returnValue(any_solved)
+ else:
+ # Get work based on the latest tree
+ merkle_root = self.merkle_tree_queue[-1]
+ # nonce = 0, one byte merkle size
+ aux = merkle_root + ("%02x000000" % self.merkle_size) + "00000000"
+ work = (yield self.parent.rpc_getworkaux(aux))
+ if self.rewrite_target:
+ work['target'] = self.rewrite_target
+ else:
+ # Find highest target
+ targets = [reverse_chunks(work['target'], 2)] # fix endian
+ targets.extend(self.aux_targets)
+ targets.sort()
+ work['target'] = reverse_chunks(targets[-1], 2) # fix endian
+ defer.returnValue(work)
+ except Exception:
+ # Exceptions here are normally already handled by the rpc functions
+ #logger.debug(traceback.format_exc())
+ raise
+
+def main(args):
+ parent = Proxy(args.parent_url)
+ aux_urls = args.aux_urls or ['http://un:pw@127.0.0.1:8342/']
+ auxs = [Proxy(url) for url in aux_urls]
+ if args.merkle_size is None:
+ for i in range(8):
+ if (1<<i) > len(aux_urls):
+ args.merkle_size = i
+ logger.info('merkle size = %d', i)
+ break
+
+ if len(aux_urls) > args.merkle_size:
+ raise ValueError('the merkle size must be at least as large as the number of aux chains')
+
+ if args.pidfile:
+ pidfile = open(args.pidfile, 'w')
+ pidfile.write(str(os.getpid()))
+ pidfile.close()
+
+ listener = Listener(parent, auxs, args.merkle_size, args.rewrite_target)
+ listener.update_aux_process()
+ reactor.listenTCP(args.worker_port, server.Site(listener))
+
+def run():
+ parser = argparse.ArgumentParser(description='merge-mine-proxy (version %s)' % (__version__,))
+ parser.add_argument('--version', action='version', version=__version__)
+ worker_group = parser.add_argument_group('worker interface')
+ worker_group.add_argument('-w', '--worker-port', metavar='PORT',
+ help='listen on PORT for RPC connections from miners asking for work and providing responses (default: 9992)',
+ type=int, action='store', default=9992, dest='worker_port')
+
+ parent_group = parser.add_argument_group('parent chain (bitcoin) interface')
+ parent_group.add_argument('-p', '--parent-url', metavar='PARENT_URL',
+ help='connect to the parent RPC at this address (default: http://un:pw@127.0.0.1:8332/)',
+ type=str, action='store',
+ default='http://un:pw@127.0.0.1:8332/',
+ dest='parent_url')
+
+ aux_group = parser.add_argument_group('aux chain (e.g. namecoin) interface(s)')
+ aux_group.add_argument('-x', '--aux-url', metavar='AUX_URL',
+ help='connect to the aux RPC at this address (default: http://un:pw@127.0.0.1:8342/)',
+ type=str, action='store', nargs='+',
+ dest='aux_urls')
+ aux_group.add_argument('-s', '--merkle-size', metavar='SIZE',
+ help='use these many entries in the merkle tree. Must be a power of 2. Default is lowest power of 2 greater than number of aux chains.',
+ type=int, action='store', default=None,
+ dest='merkle_size')
+
+ parser.add_argument('-r', '--rewrite-target', help='rewrite target difficulty to 1',
+ action='store_const', const=1, default=False,
+ dest='rewrite_target')
+ parser.add_argument('-R', '--rewrite-target-100', help='rewrite target difficulty to 100',
+ action='store_const', const=100, default=False,
+ dest='rewrite_target')
+
+ parser.add_argument('-i', '--pidfile', metavar='PID', type=str, action='store', default=None, dest='pidfile')
+ parser.add_argument('-l', '--logfile', metavar='LOG', type=str, action='store', default=None, dest='logfile')
+
+ args = parser.parse_args()
+
+ if args.logfile:
+ logger.addHandler(logging.FileHandler(args.logfile))
+ else:
+ logger.addHandler(logging.StreamHandler())
+
+ reactor.callWhenRunning(main, args)
+ reactor.run()
+
+if __name__ == "__main__":
+ run()
diff --git a/src/auxpow.cpp b/src/auxpow.cpp
new file mode 100644
index 0000000..620504f
--- /dev/null
+++ b/src/auxpow.cpp
@@ -0,0 +1,129 @@
+// Copyright (c) 2011 Vince 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 "script.h"
+#include "auxpow.h"
+#include "init.h"
+
+using namespace std;
+using namespace boost;
+
+unsigned char pchMergedMiningHeader[] = { 0xfa, 0xbe, 'm', 'm' } ;
+
+void RemoveMergedMiningHeader(vector<unsigned char>& vchAux)
+{
+ if (vchAux.begin() != std::search(vchAux.begin(), vchAux.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader)))
+ throw runtime_error("merged mining aux too short");
+ vchAux.erase(vchAux.begin(), vchAux.begin() + sizeof(pchMergedMiningHeader));
+}
+
+bool CAuxPow::Check(uint256 hashAuxBlock, int nChainID)
+{
+ if (nIndex != 0)
+ return error("AuxPow is not a generate");
+
+ if (!fTestNet && parentBlock.GetChainID() == nChainID)
+ return error("Aux POW parent has our chain ID");
+
+ if (vChainMerkleBranch.size() > 30)
+ return error("Aux POW chain merkle branch too long");
+
+ // Check that the chain merkle root is in the coinbase
+ uint256 nRootHash = CBlock::CheckMerkleBranch(hashAuxBlock, vChainMerkleBranch, nChainIndex);
+ vector<unsigned char> vchRootHash(nRootHash.begin(), nRootHash.end());
+ std::reverse(vchRootHash.begin(), vchRootHash.end()); // correct endian
+
+ // Check that we are in the parent block merkle tree
+ if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != parentBlock.hashMerkleRoot)
+ return error("Aux POW merkle root incorrect");
+
+ const CScript script = vin[0].scriptSig;
+
+ // Check that the same work is not submitted twice to our chain.
+ //
+
+ CScript::const_iterator pcHead =
+ std::search(script.begin(), script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader));
+
+ CScript::const_iterator pc =
+ std::search(script.begin(), script.end(), vchRootHash.begin(), vchRootHash.end());
+
+ if (pc == script.end())
+ return error("Aux POW missing chain merkle root in parent coinbase");
+
+ if (pcHead != script.end())
+ {
+ // Enforce only one chain merkle root by checking that a single instance of the merged
+ // mining header exists just before.
+ if (script.end() != std::search(pcHead + 1, script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader)))
+ return error("Multiple merged mining headers in coinbase");
+ if (pcHead + sizeof(pchMergedMiningHeader) != pc)
+ return error("Merged mining header is not just before chain merkle root");
+ }
+ else
+ {
+ // For backward compatibility.
+ // Enforce only one chain merkle root by checking that it starts early in the coinbase.
+ // 8-12 bytes are enough to encode extraNonce and nBits.
+ if (pc - script.begin() > 20)
+ return error("Aux POW chain merkle root must start in the first 20 bytes of the parent coinbase");
+ }
+
+
+ // Ensure we are at a deterministic point in the merkle leaves by hashing
+ // a nonce and our chain ID and comparing to the index.
+ pc += vchRootHash.size();
+ if (script.end() - pc < 8)
+ return error("Aux POW missing chain merkle tree size and nonce in parent coinbase");
+
+ int nSize;
+ memcpy(&nSize, &pc[0], 4);
+ if (nSize != (1 << vChainMerkleBranch.size()))
+ return error("Aux POW merkle branch size does not match parent coinbase");
+
+ int nNonce;
+ memcpy(&nNonce, &pc[4], 4);
+
+ // Choose a pseudo-random slot in the chain merkle tree
+ // but have it be fixed for a size/nonce/chain combination.
+ //
+ // This prevents the same work from being used twice for the
+ // same chain while reducing the chance that two chains clash
+ // for the same slot.
+ unsigned int rand = nNonce;
+ rand = rand * 1103515245 + 12345;
+ rand += nChainID;
+ rand = rand * 1103515245 + 12345;
+
+ if (nChainIndex != (rand % nSize))
+ return error("Aux POW wrong index");
+
+ return true;
+}
+
+CScript MakeCoinbaseWithAux(unsigned int nBits, unsigned int nExtraNonce, vector<unsigned char>& vchAux)
+{
+ vector<unsigned char> vchAuxWithHeader(UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader));
+ vchAuxWithHeader.insert(vchAuxWithHeader.end(), vchAux.begin(), vchAux.end());
+
+ // Push OP_2 just in case we want versioning later
+ return CScript() << nBits << nExtraNonce << OP_2 << vchAuxWithHeader;
+}
+
+
+void IncrementExtraNonceWithAux(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime, vector<unsigned char>& vchAux)
+{
+ // Update nExtraNonce
+ int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
+ if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
+ {
+ nExtraNonce = 1;
+ nPrevTime = nNow;
+ }
+
+ pblock->vtx[0].vin[0].scriptSig = MakeCoinbaseWithAux(pblock->nBits, nExtraNonce, vchAux);
+ pblock->hashMerkleRoot = pblock->BuildMerkleTree();
+}
+
+
diff --git a/src/auxpow.h b/src/auxpow.h
new file mode 100644
index 0000000..18fc33f
--- /dev/null
+++ b/src/auxpow.h
@@ -0,0 +1,84 @@
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Distributed under the MIT/X11 software license, see the accompanying
+// file license.txt or http://www.opensource.org/licenses/mit-license.php.
+#ifndef BITCOIN_AUXPOW_H
+#define BITCOIN_AUXPOW_H
+
+#include "main.h"
+
+class CAuxPow : public CMerkleTx
+{
+public:
+ CAuxPow(const CTransaction& txIn) : CMerkleTx(txIn)
+ {
+ }
+
+ CAuxPow() :CMerkleTx()
+ {
+ }
+
+ // Merkle branch with root vchAux
+ // root must be present inside the coinbase
+ std::vector<uint256> vChainMerkleBranch;
+ // Index of chain in chains merkle tree
+ int nChainIndex;
+ CBlock parentBlock;
+
+ IMPLEMENT_SERIALIZE
+ (
+ nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
+ nVersion = this->nVersion;
+ READWRITE(vChainMerkleBranch);
+ READWRITE(nChainIndex);
+
+ // Always serialize the saved parent block as header so that the size of CAuxPow
+ // is consistent.
+ nSerSize += SerReadWrite(s, parentBlock, nType | SER_BLOCKHEADERONLY, nVersion, ser_action);
+ )
+
+ bool Check(uint256 hashAuxBlock, int nChainID);
+
+ uint256 GetParentBlockHash()
+ {
+ return parentBlock.GetHash();
+ }
+};
+
+template <typename Stream>
+int ReadWriteAuxPow(Stream& s, const boost::shared_ptr<CAuxPow>& auxpow, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
+{
+ if (nVersion & BLOCK_VERSION_AUXPOW)
+ {
+ return ::GetSerializeSize(*auxpow, nType, nVersion);
+ }
+ return 0;
+}
+
+template <typename Stream>
+int ReadWriteAuxPow(Stream& s, const boost::shared_ptr<CAuxPow>& auxpow, int nType, int nVersion, CSerActionSerialize ser_action)
+{
+ if (nVersion & BLOCK_VERSION_AUXPOW)
+ {
+ return SerReadWrite(s, *auxpow, nType, nVersion, ser_action);
+ }
+ return 0;
+}
+
+template <typename Stream>
+int ReadWriteAuxPow(Stream& s, boost::shared_ptr<CAuxPow>& auxpow, int nType, int nVersion, CSerActionUnserialize ser_action)
+{
+ if (nVersion & BLOCK_VERSION_AUXPOW)
+ {
+ auxpow.reset(new CAuxPow());
+ return SerReadWrite(s, *auxpow, nType, nVersion, ser_action);
+ }
+ else
+ {
+ auxpow.reset();
+ return 0;
+ }
+}
+
+extern void RemoveMergedMiningHeader(std::vector<unsigned char>& vchAux);
+extern CScript MakeCoinbaseWithAux(unsigned int nBits, unsigned int nExtraNonce, std::vector<unsigned char>& vchAux);
+#endif
diff --git a/src/db.cpp b/src/db.cpp
index f044355..e9a28a9 100644
--- a/src/db.cpp
+++ b/src/db.cpp
@@ -5,6 +5,7 @@
#include "headers.h"
#include "db.h"
#include "net.h"
+#include "auxpow.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
@@ -421,6 +422,7 @@ bool CTxDB::LoadBlockIndex()
pindexNew->nTime = diskindex.nTime;
pindexNew->nBits = diskindex.nBits;
pindexNew->nNonce = diskindex.nNonce;
+ pindexNew->auxpow = diskindex.auxpow;
// Watch for genesis block
if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
@@ -477,7 +479,7 @@ bool CTxDB::LoadBlockIndex()
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("LoadBlockIndex() : block.ReadFromDisk failed");
- if (!block.CheckBlock())
+ if (!block.CheckBlock(pindex->nHeight))
{
printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
pindexFork = pindex->pprev;
diff --git a/src/main.cpp b/src/main.cpp
index 96270bb..42bf399 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -5,6 +5,7 @@
#include "db.h"
#include "net.h"
#include "init.h"
+#include "auxpow.h"
#include "cryptopp/sha.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
@@ -626,6 +627,15 @@ bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
return true;
}
+void CBlock::SetAuxPow(CAuxPow* pow)
+{
+ if (pow != NULL)
+ nVersion |= BLOCK_VERSION_AUXPOW;
+ else
+ nVersion &= ~BLOCK_VERSION_AUXPOW;
+ auxpow.reset(pow);
+}
+
uint256 static GetOrphanRoot(const CBlock* pblock)
{
// Work back to the first block in the orphan chain
@@ -1008,12 +1018,12 @@ bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
{
// Check it again in case a previous version let a bad block in
- if (!CheckBlock())
+ if (!CheckBlock(pindex->nHeight))
return false;
//// issue here: it doesn't know the version
- unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
-
+ unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(*this, SER_DISK|SER_BLOCKHEADERONLY) + GetSizeOfCompactSize(vtx.size());
+
map<uint256, CTxIndex> mapUnused;
int64 nFees = 0;
BOOST_FOREACH(CTransaction& tx, vtx)
@@ -1246,10 +1256,64 @@ bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
return true;
}
+// Start accepting AUX POW at this block
+//
+// Even if we do not accept AUX POW ourselves, we can always be the parent chain.
+
+int GetAuxPowStartBlock()
+{
+ if (fTestNet)
+ return 0; // Always on testnet
+ else
+ return INT_MAX; // Never on prodnet
+}
+
+int GetOurChainID()
+{
+ return 0x0003;
+}
+
+bool CBlock::CheckProofOfWork(int nHeight) const
+{
+ if (nHeight >= GetAuxPowStartBlock())
+ {
+ // Prevent same work from being submitted twice:
+ // - this block must have our chain ID
+ // - parent block must not have the same chain ID (see CAuxPow::Check)
+ // - index of this chain in chain merkle tree must be pre-determined (see CAuxPow::Check)
+ if (!fTestNet && nHeight != INT_MAX && GetChainID() != GetOurChainID())
+ return error("CheckProofOfWork() : block does not have our chain ID");
+ if (auxpow.get() != NULL)
+ {
+ if (!auxpow->Check(GetHash(), GetChainID()))
+ return error("CheckProofOfWork() : AUX POW is not valid");
+ // Check proof of work matches claimed amount
+ if (!::CheckProofOfWork(auxpow->GetParentBlockHash(), nBits))
+ return error("CheckProofOfWork() : AUX proof of work failed");
+ }
+ else
+ {
+ // Check proof of work matches claimed amount
+ if (!::CheckProofOfWork(GetHash(), nBits))
+ return error("CheckProofOfWork() : proof of work failed");
+ }
+ }
+ else
+ {
+ if (auxpow.get() != NULL)
+ {
+ return error("CheckProofOfWork() : AUX POW is not allowed at this block");
+ }
+ // Check proof of work matches claimed amount
+ if (!::CheckProofOfWork(GetHash(), nBits))
+ return error("CheckProofOfWork() : proof of work failed");
+ }
+ return true;
+}
-bool CBlock::CheckBlock() const
+bool CBlock::CheckBlock(int nHeight) const
{
// These are checks that are independent of context
// that can be verified before saving an orphan block.
@@ -1259,7 +1323,7 @@ bool CBlock::CheckBlock() const
return error("CheckBlock() : size limits failed");
// Check proof of work matches claimed amount
- if (!CheckProofOfWork(GetHash(), nBits))
+ if (!CheckProofOfWork(nHeight))
return error("CheckBlock() : proof of work failed");
// Check timestamp
@@ -1356,7 +1420,7 @@ bool static ProcessBlock(CNode* pfrom, CBlock* pblock)
return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
// Preliminary checks
- if (!pblock->CheckBlock())
+ if (!pblock->CheckBlock(INT_MAX))
return error("ProcessBlock() : CheckBlock FAILED");
// If don't already have its previous block, shunt it off to holding area until we get it
@@ -2711,7 +2775,19 @@ class COrphan
}
};
-
+void CBlock::SetNull()
+{
+ nVersion = BLOCK_VERSION_DEFAULT | (GetOurChainID() * BLOCK_VERSION_CHAIN_START);
+ hashPrevBlock = 0;
+ hashMerkleRoot = 0;
+ nTime = 0;
+ nBits = 0;
+ nNonce = 0;
+ vtx.clear();
+ vMerkleTree.clear();
+ auxpow.reset();
+}
+
CBlock* CreateNewBlock(CReserveKey& reservekey)
{
CBlockIndex* pindexPrev = pindexBest;
@@ -2925,11 +3001,35 @@ bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
uint256 hash = pblock->GetHash();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
- if (hash > hashTarget)
- return false;
+ CAuxPow *auxpow = pblock->auxpow.get();
+
+ if (auxpow != NULL)
+ {
+ if (!auxpow->Check(hash, pblock->GetChainID()))
+ return error("AUX POW is not valid");
+
+ if (auxpow->GetParentBlockHash() > hashTarget)
+ return error("AUX POW parent hash %s is not under target %s", auxpow->GetParentBlockHash().GetHex().c_str(), hashTarget.GetHex().c_str());
+
+ //// debug print
+ printf("I0coinMiner:\n");
+ printf("AUX proof-of-work found \n our hash: %s \n parent hash: %s \n target: %s\n",
+ hash.GetHex().c_str(),
+ auxpow->GetParentBlockHash().GetHex().c_str(),
+ hashTarget.GetHex().c_str());
+ }
+ else
+ {
+ if (hash > hashTarget)
+ return false;
+ //// debug print
+ printf("I0coinMiner:\n");
+ printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
+ }
+
//// debug print
- printf("BitcoinMiner:\n");
+ printf("IxcoinMiner:\n");
printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
pblock->print();
printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
@@ -3152,3 +3252,22 @@ void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
}
}
}
+
+bool CBlockIndex::CheckIndex() const
+{
+ if (nVersion & BLOCK_VERSION_AUXPOW)
+ return CheckProofOfWork(auxpow->GetParentBlockHash(), nBits);
+ else
+ return CheckProofOfWork(GetBlockHash(), nBits);
+}
+
+std::string CBlockIndex::ToString() const
+{
+ return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s, hashParentBlock=%s)",
+ pprev, pnext, nFile, nBlockPos, nHeight,
+ hashMerkleRoot.ToString().substr(0,10).c_str(),
+ GetBlockHash().ToString().substr(0,20).c_str(),
+ (auxpow.get() != NULL) ? auxpow->GetParentBlockHash().ToString().substr(0,20).c_str() : "-"
+ );
+}
+
diff --git a/src/main.h b/src/main.h
index 3de83a3..f36747d 100644
--- a/src/main.h
+++ b/src/main.h
@@ -11,6 +11,7 @@
#include "db.h"
#include <list>
+#include <boost/shared_ptr.hpp>
class CBlock;
class CBlockIndex;
@@ -26,6 +27,7 @@
class CRequestTracker;
class CNode;
class CBlockIndex;
+class CAuxPow;
static const unsigned int MAX_BLOCK_SIZE = 1000000;
static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
@@ -97,6 +99,7 @@
void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
CBlock* CreateNewBlock(CReserveKey& reservekey);
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime);
+void IncrementExtraNonceWithAux(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime, std::vector<unsigned char>& vchAux);
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
bool CheckProofOfWork(uint256 hash, unsigned int nBits);
@@ -570,7 +573,6 @@ class CTransaction
return nMinFee;
}
-
bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
{
CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
@@ -756,9 +758,28 @@ class CTxIndex
int GetDepthInMainChain() const;
};
+template <typename Stream>