-
Notifications
You must be signed in to change notification settings - Fork 86
/
claimer.py
1638 lines (1421 loc) · 64.1 KB
/
claimer.py
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
import hashlib, os, struct, sys, socket, time, urllib2, json, argparse, cStringIO, traceback, hmac, ssl
N = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fL
R = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141L
A = 0L
B = 7L
gx = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798L
gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
b58ab = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
bech32ab = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
def bech32_polymod(values):
GEN = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
chk = 1
for v in values:
b = (chk >> 25)
chk = (chk & 0x1ffffff) << 5 ^ v
for i in range(5):
chk ^= GEN[i] if ((b >> i) & 1) else 0
return chk
def bech32_hrp_expand(s):
return [ord(x) >> 5 for x in s] + [0] + [ord(x) & 31 for x in s]
def bech32decode(addr):
hrp, data = addr.lower().rsplit("1", 1)
data = [bech32ab.index(c) for c in data]
assert bech32_polymod(bech32_hrp_expand(hrp) + data) == 1, "bech32 checksum failed"
assert data[0] == 0, "only support version 0 witness for now"
data = data[1:-6]
n = 0
for c in data:
n = n << 5 | c
nbytes, extrabits = divmod(len(data) * 5, 8)
return long2byte(n >> extrabits, nbytes)
def bech32encode(hrp, s):
extrabits = (5 - ((len(s) * 8) % 5)) % 5
nchars = (len(s) * 8 + extrabits) / 5
n = byte2long(s) << extrabits
data = []
for i in xrange(nchars):
data.insert(0, n & 31)
n >>= 5
data.insert(0, 0) # version 0
values = bech32_hrp_expand(hrp) + data
polymod = bech32_polymod(values + [0,0,0,0,0,0]) ^ 1
data += [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
return hrp + "1" + "".join(bech32ab[c] for c in data)
def b58csum(s):
return hashlib.sha256(hashlib.sha256(s).digest()).digest()[0:4]
def b58decode(s, checksum=True):
idx = 0
while s[idx] == "1":
idx += 1
n = 0
for c in s[idx:]:
n = n * 58 + b58ab.index(c)
res = long2byte(n)
res = idx * "\x00" + res
if checksum:
res, cs = res[:-4], res[-4:]
assert cs == b58csum(res), "base58 checksum failed"
return res
def b58encode(s, checksum=True):
if checksum:
s += b58csum(s)
idx = 0
while s[idx] == "\x00":
idx += 1
n = byte2long(s)
res = ""
while n > 0:
res = b58ab[n % 58] + res
n /= 58
return "1" * idx + res
def byte2long(s):
res = 0
for c in s:
res = (res << 8) | ord(c)
return res
def long2byte(n, sz=None):
res = ""
while n > 0:
res = chr(n & 0xff) + res
n >>= 8
if sz is not None:
res = res.rjust(sz, "\x00")
return res
def read_varint(st):
value = ord(st.read(1))
if value < 0xfd:
return value
if value == 0xfd:
return struct.unpack("<H", st.read(2))[0]
if value == 0xfe:
return struct.unpack("<L", st.read(4))[0]
if value == 0xff:
return struct.unpack("<Q", st.read(8))[0]
def make_varint(value):
if value < 0xfd:
return chr(value)
if value <= 0xffff:
return "\xfd" + struct.pack("<H", value)
if value <= 0xffffffff:
return "\xfe" + struct.pack("<L", value)
return "\xff" + struct.pack("<Q", value)
def lengthprefixed(s):
return make_varint(len(s)) + s
def modinv(x, n):
return pow(x, n-2, n)
class Point(object):
def __init__(self, x, y, inf=False):
self.x = x
self.y = y
self.inf = inf
def curve_add(p, q, N):
if p.inf:
return q
if q.inf:
return p
if p.x == q.x:
if p.y == q.y:
d1 = (3 * p.x * p.x) % N
d2 = (2 * p.y) % N
else:
return Point(-1, -1, True)
else:
d1 = (q.y - p.y) % N
d2 = (q.x - p.x) % N
d2i = modinv(d2, N)
d = (d1 * d2i) % N
resx = (d * d - p.x - q.x) % N
resy = (d * (p.x - resx) - p.y) % N
return Point(resx, resy)
def scalar_mul(scalar, p, N):
t = p
res = None
while scalar != 0:
if scalar & 1 == 1:
if res is None:
res = t
else:
res = curve_add(res, t, N)
t = curve_add(t, t, N)
scalar = scalar >> 1
return res
def der_signature(r, s):
r = long2byte(r)
if ord(r[0]) >= 0x80:
r = "\x00" + r
s = long2byte(s)
if ord(s[0]) >= 0x80:
s = "\x00" + s
res = "\x02" + lengthprefixed(r) + "\x02" + lengthprefixed(s)
return "\x30" + lengthprefixed(res)
def gen_k_rfc6979(privkey, m):
h1 = hashlib.sha256(m).digest()
x = long2byte(privkey, 32)
V = "\x01" * 32
K = "\x00" * 32
K = hmac.new(K, V + "\x00" + x + h1, hashlib.sha256).digest()
V = hmac.new(K, V, hashlib.sha256).digest()
K = hmac.new(K, V + "\x01" + x + h1, hashlib.sha256).digest()
V = hmac.new(K, V, hashlib.sha256).digest()
while True:
V = hmac.new(K, V, hashlib.sha256).digest()
k = byte2long(V)
if k >= 1 and k < R:
return k
K = hmac.new(K, V + "\x00", hashlib.sha256).digest()
V = hmac.new(K, V, hashlib.sha256).digest()
def signdata(privkey, data):
h = doublesha(data)
r, s = sign(privkey, h)
return der_signature(r, s)
def sign(privkey, h):
z = byte2long(h)
k = gen_k_rfc6979(privkey, h)
p = scalar_mul(k, Point(gx, gy), N)
r = p.x % R
assert r != 0
ki = modinv(k, R)
s = (ki * (z + r * privkey)) % R
assert s != 0
if s > (R / 2):
s = R - s
return r, s
def serializepubkey(p, compressed):
if compressed:
if p.y & 1 == 1:
return "\x03" + long2byte(p.x, 32)
else:
return "\x02" + long2byte(p.x, 32)
else:
return "\x04" + long2byte(p.x, 32) + long2byte(p.y, 32)
def doublesha(s):
s = hashlib.sha256(s).digest()
return hashlib.sha256(s).digest()
def hash160(s):
s = hashlib.sha256(s).digest()
h = hashlib.new("ripemd160")
h.update(s)
return h.digest()
def pubkey2h160(p, compressed):
s = serializepubkey(p, compressed)
return hash160(s)
def pubkey2segwith160(p):
s = pubkey2h160(p, 1)
return hash160("\x00\x14" + s)
def pubkey2addr(p, compressed):
s = pubkey2h160(p, compressed)
return b58encode("\x00" + s)
def pubkey2segwitaddr(p):
s = pubkey2segwith160(p)
return b58encode("\x05" + s)
def wif2privkey(s):
s = b58decode(s)
keytype = ord(s[0])
if len(s) == 34 and s[-1] == "\x01":
compressed = 1
elif len(s) == 33:
compressed = 0
else:
raise Exception("Unknown private key WIF format!")
return keytype, byte2long(s[1:33]), compressed
def identify_keytype(wifkey, addr):
if addr.startswith("bc1"):
addrh160 = bech32decode(addr)
assert len(addrh160) == 20
privkeytype, privkey, compressed = wif2privkey(args.wifkey)
pubkey = scalar_mul(privkey, Point(gx, gy), N)
if addrh160 == pubkey2h160(pubkey, 1):
return "segwitbech32", privkey, pubkey, addrh160, 1
raise Exception("Unable to identify key type!")
else:
addrh160 = b58decode(addr)[-20:]
assert len(addrh160) == 20
privkeytype, privkey, compressed = wif2privkey(args.wifkey)
pubkey = scalar_mul(privkey, Point(gx, gy), N)
if addrh160 == pubkey2h160(pubkey, 0):
return "standard", privkey, pubkey, addrh160, 0
if addrh160 == pubkey2h160(pubkey, 1):
return "standard", privkey, pubkey, addrh160, 1
if addrh160 == pubkey2segwith160(pubkey):
return "segwit", privkey, pubkey, pubkey2h160(pubkey, 1), 1
raise Exception("Unable to identify key type!")
def get_tx_details_from_blockchaininfo(txid, addr, hardforkheight):
print "Querying blockchain.info API about data for transaction %s" % txid
res = urllib2.urlopen("https://blockchain.info/rawtx/%s" % txid)
txinfo = json.loads(res.read())
if hardforkheight is not None and hardforkheight < txinfo["block_height"]:
print "\n\nTHIS TRANSACTION HAPPENED AFTER THE COIN FORKED FROM THE MAIN CHAIN!"
print "(fork at height %d, this tx at %d)" % (hardforkheight, txinfo["block_height"])
print "You will most likely be unable to claim these coins."
print "Please look for an earlier transaction before the fork point.\n\n"
get_consent("I will try anyway")
found = None
for outinfo in txinfo["out"]:
if "addr" in outinfo and outinfo["addr"] == addr:
txindex = outinfo["n"]
script = outinfo["script"].decode("hex")
satoshis = outinfo["value"]
print "Candidate transaction, index %d with %d Satoshis (%.8f BTC)" % (txindex, satoshis, satoshis / 100000000.0)
if found is None:
found = txindex, script, satoshis
else:
raise Exception("Multiple outputs with that address found! Aborting!")
if not found:
raise Exception("No output with address %s found in transaction %s" % (addr, txid))
return found
def get_btx_details_from_chainz_cryptoid(addr):
print "Querying chainz.cryptoid.info about last unspent transaction for address"
url = "https://chainz.cryptoid.info/btx/api.dws?q=unspent&active=%s&key=a660e3112b78" % addr
request = urllib2.Request(url)
request.add_header('User-Agent', 'Mozilla/5.0')
opener = urllib2.build_opener()
res = opener.open(request)
txinfo = json.loads(res.read())
unspent_outputs = txinfo["unspent_outputs"]
if len(unspent_outputs) == 0:
raise Exception("Block explorer didn't find any coins at that address")
outinfo = unspent_outputs[0]
txid = outinfo["tx_hash"]
txindex = outinfo["tx_ouput_n"]
script = outinfo["script"].decode("hex")
satoshis = int(outinfo["value"])
return txid, txindex, script, satoshis
def get_coin_details_from_electrum(coin, targettxid, sourceh160, keytype):
if keytype in ("segwit", "segwit_btcp"):
addr = b58encode(coin.SCRIPT_ADDRESS + hash160("\x00\x14" + sourceh160))
else:
addr = b58encode(coin.PUBKEY_ADDRESS + sourceh160)
sc = socket.create_connection((coin.electrum_server, coin.electrum_port))
if coin.electrum_ssl:
sc = ssl.wrap_socket(sc)
sc.send('{ "id": 0, "method": "blockchain.address.listunspent", "params": [ "%s" ] }\n' % addr)
res = readline(sc)
j = json.loads(res)
unspents = j["result"]
if len(unspents) == 0:
raise Exception("No %s at this address!" % coin.ticker)
if len(unspents) == 1:
target = unspents[0]
else:
target = None
for tx in unspents:
if tx["tx_hash"] == targettxid:
target = tx
break
if target is None:
print "Multiple potential outputs possible - please use one of these TXIDs to claim"
for tx in unspents:
coinamount = int(tx["value"]) * coin.coinratio / 100000000.0
btcamount = int(tx["value"]) / 100000000.0
print " TXID %s : %20.8f %s (equivalent to %.8f BTC)" % (tx["tx_hash"], coinamount, coin.ticker, btcamount)
exit()
return target["tx_hash"], int(target["tx_pos"]), None, int(target["value"])
def readline(sc):
res = ""
while True:
c = sc.recv(1)
if c == "":
raise Exception("Disconnect when querying electrum server")
elif c == "\n":
break
else:
res += c
return res
def get_consent(consentstring):
print "\nWrite '%s' to continue" % consentstring
answer = raw_input()
if answer != consentstring:
raise Exception("User did not write '%s', aborting" % consentstring)
class Client(object):
_MAX_MEMPOOL_CHECKS = 5
_MAX_CONNECTION_RETRIES = 100
def __init__(self, coin):
self.coin = coin
self._transaction_sent = False
self._transaction_accepted = None
self._mempool_check_count = 0
self._connection_retries = 0
def send(self, cmd, msg):
magic = struct.pack("<L", self.coin.magic)
wrapper = magic + cmd.ljust(12, "\x00") + struct.pack("<L", len(msg)) + hashlib.sha256(hashlib.sha256(msg).digest()).digest()[0:4] + msg
self.sc.sendall(wrapper)
print "---> %s (%d bytes)" % (repr(cmd), len(msg))
def recv_msg(self):
def recv_all(length):
ret = ""
while len(ret) < length:
temp = self.sc.recv(length - len(ret))
if len(temp) == 0:
raise socket.error("Connection reset!")
ret += temp
return ret
header = recv_all(24)
if len(header) != 24:
raise Exception("INVALID HEADER LENGTH\n%s" % repr(header))
cmd = header[4:16].rstrip("\x00")
payloadlen = struct.unpack("<I", header[16:20])[0]
payload = recv_all(payloadlen)
return cmd, payload
def send_tx(self, txhash, tx, checkfee):
serverindex = ord(os.urandom(1)) % len(self.coin.seeds)
txhash_hexfmt = txhash[::-1].encode("hex")
while True:
try:
address = (coin.seeds[serverindex], self.coin.port)
print "Connecting to", address, "...",
self.sc = socket.create_connection(address, 10)
print "SUCCESS, connected to", self.sc.getpeername()
self.sc.settimeout(120)
services = 0
localaddr = "\x00" * 8 + "00000000000000000000FFFF".decode("hex") + "\x00" * 6
nonce = os.urandom(8)
user_agent = "Scraper"
msg = struct.pack("<IQQ", self.coin.versionno, services, int(time.time())) + (
localaddr + localaddr + nonce + lengthprefixed(user_agent) + struct.pack("<IB", 0, 0)) + self.coin.BCLDgarbage
client.send("version", msg)
while True:
cmd, payload = client.recv_msg()
print "<--- '%s' (%d bytes)" % (cmd, len(payload))
if cmd == "version":
sio = cStringIO.StringIO(payload)
protoversion, services, timestamp = struct.unpack("<IQQ", sio.read(20))
addr_recv = sio.read(26)
addr_from = sio.read(26)
nonce = sio.read(8)
user_agent_len = read_varint(sio)
user_agent = sio.read(user_agent_len)
start_height = struct.unpack("<I", sio.read(4))[0]
print " Version information:"
print "\tprotocol version", protoversion
print "\tservices", services
print "\ttimestamp", time.asctime(time.gmtime(timestamp))
print "\tuser agent", repr(user_agent)
print "\tblock height", repr(start_height)
client.send("verack", "")
elif cmd == "sendheaders":
msg = make_varint(0)
client.send("headers", msg)
elif cmd == "ping":
client.send("pong", payload)
if not self._transaction_sent:
client.send("inv", "\x01" + struct.pack("<I", 1) + txhash)
elif not self._transaction_accepted:
client.send("tx", tx)
print "\tRe-sent transaction: %s" % txhash_hexfmt
client.send("mempool", "")
elif cmd == "getdata":
if payload == "\x01\x01\x00\x00\x00" + txhash:
print "\tPeer requesting transaction details for %s" % txhash_hexfmt
client.send("tx", tx)
print "\tSENT TRANSACTION: %s" % txhash_hexfmt
self._transaction_sent = True
# If a getdata comes in without our txhash, it generally means the tx was rejected.
elif self._transaction_sent:
print "\tReceived getdata without our txhash. The transaction may have been rejected."
print "\tThis script will retransmit the transaction and monitor the mempool for a few minutes before giving up."
elif cmd == "feefilter":
minfee = struct.unpack("<Q", payload)[0]
print "\tserver requires minimum fee of %d satoshis" % minfee
if checkfee >= minfee:
print "\tour fee is >= minimum fee, so should be OK"
else:
print "\tOUR FEE IS TOO SMALL, transaction might not be accepted"
elif cmd == "inv":
blocks_to_get = []
st = cStringIO.StringIO(payload)
ninv = read_varint(st)
transaction_found = False
invtypes = {1: 'transaction', 2: 'block'}
for i in xrange(ninv):
invtype = struct.unpack("<I", st.read(4))[0]
invhash = st.read(32)
invtypestr = invtypes[invtype] if invtype in invtypes else str(invtype)
if i < 10:
print "\t%s: %s" % (invtypestr, invhash[::-1].encode("hex"))
elif i == 10:
print "\t..."
print "\tNot printing additional %d transactions" % (ninv - i)
if invtype == 1:
if invhash == txhash:
transaction_found = True
elif invtype == 2:
blocks_to_get.append(invhash)
if transaction_found and not self._transaction_accepted:
print "\n\tOUR TRANSACTION IS IN THEIR MEMPOOL, TRANSACTION ACCEPTED! YAY!"
if args.noblock:
# User specified --noblock, we are done here
return
else:
print "\tConsider leaving this script running until it detects the transaction in a block."
self._transaction_accepted = True
elif transaction_found:
print "\tTransaction still in mempool. Continue waiting for block inclusion."
elif not blocks_to_get:
print "\n\tOur transaction was not found in the mempool."
self._mempool_check_count += 1
if self._mempool_check_count <= self._MAX_MEMPOOL_CHECKS:
print "\tWill retransmit and check again %d more times." % (self._MAX_MEMPOOL_CHECKS - self._mempool_check_count)
else:
raise Exception("\tGiving up on transaction. Please verify that the inputs have not already been spent.")
if blocks_to_get:
inv = ["\x02\x00\x00\x00" + invhash for invhash in blocks_to_get]
msg = make_varint(len(inv)) + "".join(inv)
client.send("getdata", msg)
print "\trequesting %d blocks" % len(blocks_to_get)
elif cmd == "block":
if tx in payload or plaintx in payload:
print "\tBLOCK WITH OUR TRANSACTION OBSERVED! YES!"
print "\tYour coins have been successfully sent. Exiting..."
return
else:
print "\tTransaction not included in observed block."
elif cmd == "addr":
st = cStringIO.StringIO(payload)
naddr = read_varint(st)
for _ in xrange(naddr):
data = st.read(30)
if data[12:24] == "\x00" * 10 + "\xff\xff":
address = "%d.%d.%d.%d:%d" % struct.unpack(">BBBBH", data[24:30])
else:
address = "[%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x]:%d" % struct.unpack(">HHHHHHHHH", data[12:30])
print "\tGot peer address: %s" % address
elif cmd not in ('sendcmpct', 'verack'):
print repr(cmd), repr(payload)
except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
if self._connection_retries >= self._MAX_CONNECTION_RETRIES:
raise
print "\tConnection failed with: %s" % repr(e)
print "\tWill retry %d more times." % (self._MAX_CONNECTION_RETRIES - self._connection_retries)
serverindex = (serverindex + 1) % len(self.coin.seeds)
self._connection_retries += 1
time.sleep(2)
class BitcoinFork(object):
def __init__(self):
self.coinratio = 1.0
self.versionno = 70015
self.maketx = self.maketx_segwitsig
self.extrabytes = ""
self.BCDgarbage = ""
self.BCLsalt = ""
self.BCLDgarbage = ""
self.txversion = 1
self.signtype = 0x01
self.signid = self.signtype
self.PUBKEY_ADDRESS = chr(0)
self.SCRIPT_ADDRESS = chr(5)
self.bch_fork = False
self.address_size = 21
self.electrum_server = None
def maketx_segwitsig(self, sourcetx, sourceidx, sourceh160, signscript, sourcesatoshis, sourceprivkey, pubkey, compressed, outputs, fee, keytype):
verifytotal = fee
version = struct.pack("<I", self.txversion)
prevout = sourcetx.decode("hex")[::-1] + struct.pack("<I", sourceidx)
sequence = struct.pack("<i", -1)
inscript = lengthprefixed(signscript)
satoshis = struct.pack("<Q", sourcesatoshis)
txouts = ""
for outscript, amount, destaddr, rawaddr in outputs:
txouts += struct.pack("<Q", amount) + lengthprefixed(outscript)
verifytotal += amount
locktime = struct.pack("<I", 0)
sigtype = struct.pack("<I", self.signid)
prevouthash = doublesha(prevout)
sequencehash = doublesha(sequence)
txoutshash = doublesha(txouts)
to_sign = self.BCLDgarbage + version + self.BCDgarbage + self.BCLsalt + prevouthash + sequencehash + prevout + inscript + satoshis + sequence + txoutshash + locktime + sigtype + self.extrabytes
signature = signdata(sourceprivkey, to_sign) + make_varint(self.signtype)
serpubkey = serializepubkey(pubkey, compressed)
if keytype == "p2pk":
sigblock = lengthprefixed(signature)
else:
sigblock = lengthprefixed(signature) + lengthprefixed(serpubkey)
if keytype in ("p2pk", "standard"):
script = lengthprefixed(sigblock)
elif keytype == "segwit":
script = "\x17\x16\x00\x14" + sourceh160
elif keytype == "segwitbech32":
script = "\x00"
else:
raise Exception("Not implemented!")
plaintx = version + self.BCDgarbage + make_varint(1) + prevout + script + sequence + make_varint(len(outputs)) + txouts + locktime
if verifytotal != sourcesatoshis:
raise Exception("Addition of output amounts does not match input amount (Bug?), aborting")
if keytype in ("p2pk", "standard"):
return plaintx, plaintx
else:
witnesstx = version + self.BCDgarbage + "\x00\x01" + plaintx[4+len(self.BCDgarbage):-4] + "\x02" + sigblock + locktime
return witnesstx, plaintx
def maketx_basicsig(self, sourcetx, sourceidx, sourceh160, signscript, sourcesatoshis, sourceprivkey, pubkey, compressed, outputs, fee, keytype):
if keytype in ("segwit", "segwitbech32"):
return self.maketx_segwitsig(sourcetx, sourceidx, sourceh160, signscript, sourcesatoshis, sourceprivkey, pubkey, compressed, outputs, fee, keytype)
verifytotal = fee
version = struct.pack("<I", self.txversion)
prevout = sourcetx.decode("hex")[::-1] + struct.pack("<I", sourceidx)
sequence = struct.pack("<i", -1)
inscript = lengthprefixed(signscript)
txouts = ""
for outscript, amount, destaddr, rawaddr in outputs:
txouts += struct.pack("<Q", amount) + lengthprefixed(outscript)
verifytotal += amount
locktime = struct.pack("<I", 0)
sigtype = struct.pack("<I", self.signid)
if self.ticker == "CLAM":
CLAMgarbage = lengthprefixed("")
self.BCDgarbage = struct.pack("<I", int(time.time()))
else:
CLAMgarbage = ""
to_sign = self.BCLDgarbage + version + self.BCDgarbage + make_varint(1) + prevout + inscript + sequence + make_varint(len(outputs)) + txouts + locktime + CLAMgarbage + sigtype + self.extrabytes + self.BCLsalt
signature = signdata(sourceprivkey, to_sign) + make_varint(self.signtype)
serpubkey = serializepubkey(pubkey, compressed)
if keytype == "p2pk":
sigblock = lengthprefixed(signature)
else:
sigblock = lengthprefixed(signature) + lengthprefixed(serpubkey)
if keytype == "segwit_btcp":
sigblock += lengthprefixed("\x00\x14" + sourceh160)
plaintx = version + self.BCDgarbage + make_varint(1) + prevout + lengthprefixed(sigblock) + sequence + make_varint(len(outputs)) + txouts + locktime + CLAMgarbage
if verifytotal != sourcesatoshis:
raise Exception("Addition of output amounts does not match input amount (Bug?), aborting")
return plaintx, plaintx
class Bitcoin(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "BTC"
self.fullname = "Bitcoin"
self.hardforkheight = None
self.magic = 0xd9b4bef9
self.port = 8333
self.seeds = ("seed.bitcoin.sipa.be", "dnsseed.bluematt.me", "dnsseed.bitcoin.dashjr.org", "seed.bitcoinstats.com", "seed.bitcoin.jonasschnelli.ch", "seed.btc.petertodd.org", "seed.bitcoin.sprovoost.nl", "dnsseed.emzy.de")
self.maketx = self.maketx_basicsig
class BitcoinFaith(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "BTF"
self.fullname = "Bitcoin Faith"
self.hardforkheight = 500000
self.magic = 0xe6d4e2fa
self.port = 8346
self.seeds = ("a.btf.hjy.cc", "b.btf.hjy.cc", "c.btf.hjy.cc", "d.btf.hjy.cc", "e.btf.hjy.cc", "f.btf.hjy.cc")
self.signtype = 0x41
self.signid = self.signtype | (70 << 8)
self.PUBKEY_ADDRESS = chr(36)
self.SCRIPT_ADDRESS = chr(40)
class BitcoinWorld(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "BTW"
self.fullname = "Bitcoin World"
self.hardforkheight = 499777
self.magic = 0x777462f8
self.port = 8357
self.seeds = ("47.52.250.221", "47.91.237.5")
self.signtype = 0x41
self.signid = self.signtype | (87 << 8)
self.PUBKEY_ADDRESS = chr(73)
self.SCRIPT_ADDRESS = chr(31)
self.coinratio = 10000.0
class BitcoinGold(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "BTG"
self.fullname = "Bitcoin Gold"
self.hardforkheight = 491407
self.magic = 0x446d47e1
self.port = 8338
self.seeds = ("pool-us.bloxstor.com", "btgminingusa.com", "btg1.stage.bitsane.com", "eu-dnsseed.bitcoingold-official.org", "dnsseed.bitcoingold.org", "dnsseed.btcgpu.org")
self.signtype = 0x41
self.signid = self.signtype | (79 << 8)
self.PUBKEY_ADDRESS = chr(38)
self.SCRIPT_ADDRESS = chr(23)
class BitcoinX(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "BCX"
self.fullname = "BitcoinX"
self.hardforkheight = 498888
self.magic = 0xf9bc0511
self.port = 9003
self.seeds = ("192.169.227.48", "120.92.119.221", "120.92.89.254", "120.131.5.173", "120.92.117.145", "192.169.153.174", "192.169.154.185", "166.227.117.163")
self.signtype = 0x11
self.signid = self.signtype
self.PUBKEY_ADDRESS = chr(75)
self.SCRIPT_ADDRESS = chr(63)
self.coinratio = 10000.0
class Bitcoin2X(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "B2X"
self.fullname = "Bitcoin 2X Segwit"
self.hardforkheight = 501451
self.magic = 0xd8b5b2f4
self.port = 8333
self.seeds = ("node1.b2x-segwit.io", "node2.b2x-segwit.io", "node3.b2x-segwit.io")
self.signtype = 0x31
self.signid = self.signtype << 1
self.maketx = self.maketx_basicsig # does not use new-style segwit signing for standard transactions
class UnitedBitcoin(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "UBTC"
self.fullname = "United Bitcoin"
self.hardforkheight = 498777
self.magic = 0xd9b4bef9
self.port = 8333
self.seeds = ("urlelcm1.ub.com", "urlelcm2.ub.com", "urlelcm3.ub.com", "urlelcm4.ub.com", "urlelcm5.ub.com", "urlelcm6.ub.com", "urlelcm7.ub.com", "urlelcm8.ub.com", "urlelcm9.ub.com", "urlelcm10.ub.com")
self.signtype = 0x09
self.signid = self.signtype
self.maketx = self.maketx_basicsig # does not use new-style segwit signing for standard transactions
self.versionno = 731800
self.extrabytes = "\x02ub"
# https://github.com/superbitcoin/SuperBitcoin
class SuperBitcoin(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "SBTC"
self.fullname = "Super Bitcoin"
self.hardforkheight = 498888
self.magic = 0xd9b4bef9
self.port = 8334
self.seeds = ("seed.superbtca.com", "seed.superbtca.info", "seed.superbtc.org")
self.signtype = 0x41
self.signid = self.signtype
self.maketx = self.maketx_basicsig # does not use new-style segwit signing for standard transactions
self.extrabytes = lengthprefixed("sbtc")
self.versionno = 70017
class BitcoinDiamond(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "BCD"
self.fullname = "Bitcoin Diamond"
self.hardforkheight = 495866
self.magic = 0xd9b4debd
self.port = 7117
self.seeds = ("seed1.dns.btcd.io", "139.198.190.221", "seed2.dns.btcd.io", "121.201.13.117", "seed3.dns.btcd.io", "139.198.12.140",
"seed4.dns.btcd.io", "52.52.113.134", "seed5.dns.btcd.io", "13.114.121.21", "seed6.dns.btcd.io", "52.78.28.110")
self.signtype = 0x01
self.signid = self.signtype
self.maketx = self.maketx_basicsig # does not use new-style segwit signing for standard transactions
self.txversion = 12
self.BCDgarbage = "\xff" * 32
self.coinratio = 10.0
class BitcoinPizza(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "BPA"
self.fullname = "Bitcoin Pizza"
self.hardforkheight = 501888
self.magic = 0xd9c4bea9
self.port = 8888
self.seeds = ("dnsseed.bitcoinpizza.cc", "seed1.bitcoinpizza.cc", "seed2.bitcoinpizza.cc", "seed3.bitcoinpizza.cc", "seed4.bitcoinpizza.cc")
self.signtype = 0x21
self.signid = self.signtype | (47 << 8)
self.PUBKEY_ADDRESS = chr(55)
self.SCRIPT_ADDRESS = chr(80)
class BitcoinNew(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "BTN"
self.fullname = "Bitcoin New"
self.hardforkheight = 501000
self.magic = 0x344d37a1
self.port = 8838
self.seeds = ("dnsseed.bitcoin-new.org",)
self.signtype = 0x41
self.signid = self.signtype | (88 << 8)
class BitcoinHot(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "BTH"
self.fullname = "Bitcoin Hot"
self.hardforkheight = 498848
self.magic = 0x04ad77d1
self.port = 8222
self.seeds = ("seed-us.bitcoinhot.co", "seed-jp.bitcoinhot.co", "seed-hk.bitcoinhot.co", "seed-uk.bitcoinhot.co", "seed-cn.bitcoinhot.co")
self.signtype = 0x41
self.signid = self.signtype | (53 << 8)
self.PUBKEY_ADDRESS = chr(40)
self.SCRIPT_ADDRESS = chr(5) # NOT CERTAIN
self.versionno = 70016
self.coinratio = 100.0
# https://github.com/bitcoinvote/bitcoin
class BitcoinVote(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "BTV"
self.fullname = "Bitcoin Vote"
self.hardforkheight = 505050
self.magic = 0x505050f9
self.port = 8333
self.seeds = ("seed1.bitvote.one", "seed2.bitvote.one", "seed3.bitvote.one")
self.signtype = 0x41
self.signid = self.signtype | (50 << 8)
self.maketx = self.maketx_basicsig # does not use new-style segwit signing for standard transactions
class BitcoinTop(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "BTT"
self.fullname = "Bitcoin Top"
self.hardforkheight = 501118
self.magic = 0xd0b4bef9
self.port = 18888
self.seeds = ("dnsseed.bitcointop.org", "seed.bitcointop.org", "worldseed.bitcointop.org", "dnsseed.bitcointop.group", "seed.bitcointop.group",
"worldseed.bitcointop.group", "dnsseed.bitcointop.club", "seed.bitcointop.club", "worldseed.bitcointop.club")
self.signtype = 0x01
self.signid = self.signtype
self.maketx = self.maketx_basicsig # does not use new-style segwit signing for standard transactions
self.txversion = 13
self.BCDgarbage = "\xff" * 32
class BitCore(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "BTX"
self.fullname = "BitCore"
self.hardforkheight = 492820
self.magic = 0xd9b4bef9
self.port = 8555
self.seeds = ("37.120.190.76", "37.120.186.85", "185.194.140.60", "188.71.223.206", "185.194.142.122")
self.signtype = 0x01
self.signid = self.signtype
self.maketx = self.maketx_basicsig # does not use new-style segwit signing for standard transactions
class BitcoinPay(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "BTP"
self.fullname = "Bitcoin Pay"
self.hardforkheight = 499345
self.magic = 0xd9c1d0fe
self.port = 8380
self.seeds = ("seed.btceasypay.com",)
self.signtype = 0x41
self.signid = self.signtype | (80 << 8)
self.PUBKEY_ADDRESS = chr(0x38)
self.SCRIPT_ADDRESS = chr(0x3a)
self.coinratio = 10.0
# https://github.com/btcking/btcking
class BitcoinKing(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "BCK"
self.fullname = "Bitcoin King"
self.hardforkheight = 499999
self.magic = 0x161632af
self.port = 16333
self.seeds = ("47.52.28.49",)
self.signtype = 0x41
self.signid = self.signtype | (143 << 8)
# https://github.com/bitcoincandyofficial/bitcoincandy
class BitcoinCandy(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "CDY"
self.fullname = "Bitcoin Candy"
self.hardforkheight = 512666
self.magic = 0xd9c4c3e3
self.port = 8367
self.seeds = ("seed.bitcoincandy.one", "seed.cdy.one")
self.signtype = 0x41
self.signid = self.signtype | (111 << 8)
self.PUBKEY_ADDRESS = chr(0x1c)
self.SCRIPT_ADDRESS = chr(0x58)
self.coinratio = 1000.0
self.bch_fork = True
# https://github.com/BTSQ/BitcoinCommunity
class BitcoinCommunity(BitcoinFork):
def __init__(self):
BitcoinFork.__init__(self)
self.ticker = "BTSQ"
self.fullname = "Bitcoin Community"
self.hardforkheight = 506066
self.magic = 0xd9c4ceb9
self.port = 8866
self.seeds = ("dnsseed.aliyinke.com", "seed1.aliyinke.com", "seed2.aliyinke.com", "seed3.aliyinke.com")
self.signtype = 0x11
self.signid = self.signtype | (31 << 8)
self.PUBKEY_ADDRESS = chr(63)
self.SCRIPT_ADDRESS = chr(58)
self.coinratio = 1000.0
# https://github.com/worldbitcoin/worldbitcoin