-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathtx.py
1500 lines (1387 loc) · 57.3 KB
/
tx.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
from io import BytesIO
from json import dumps
import random
import requests
import zmq
from ecc import PrivateKey, S256Point, Signature
from helper import (
decode_base58,
double_sha256,
encode_varint,
hash160,
int_to_little_endian,
little_endian_to_int,
p2pkh_script,
p2sh_script,
read_varint,
SIGHASH_ALL,
)
from script import Script
class LibBitcoinClient:
context = zmq.Context()
mainnet_socket = None
testnet_socket = None
cache = {}
@classmethod
def get_socket(cls, testnet=False):
if testnet:
if cls.testnet_socket is None:
cls.testnet_socket = cls.context.socket(zmq.REQ)
cls.testnet_socket.connect(
'tcp://testnet.libbitcoin.net:19091')
return cls.testnet_socket
else:
if cls.mainnet_socket is None:
cls.mainnet_socket = cls.context.socket(zmq.REQ)
cls.mainnet_socket.connect(
'tcp://mainnet.libbitcoin.net:9091')
return cls.mainnet_socket
class Tx(LibBitcoinClient):
default_version = 1
default_hash_type = 1
cache = {}
p2pkh_prefixes = (b'\x00', b'\x6f')
p2sh_prefixes = (b'\x05', b'\xc4')
testnet_prefixes = (b'\x6f', b'\xc4')
scale = 100000000
num_bytes = 25
fee = 2500
insight = 'https://btc-bitcore6.trezor.io/api'
seeds = None
def __init__(self, version, tx_ins, tx_outs, locktime, testnet=False):
self.version = version
self.tx_ins = tx_ins
self.tx_outs = tx_outs
self.locktime = locktime
self.testnet = testnet
self._hash_prevouts = None
self._hash_sequence = None
self._hash_outputs = None
def __repr__(self):
tx_ins = ''
for tx_in in self.tx_ins:
tx_ins += tx_in.__repr__() + '\n'
tx_outs = ''
for tx_out in self.tx_outs:
tx_outs += tx_out.__repr__() + '\n'
return '{}\nversion: {}\ntx_ins:\n{}\ntx_outs:\n{}\nlocktime: {}\n'.format(
self.hash().hex(),
self.version,
tx_ins,
tx_outs,
self.locktime,
)
def hash(self):
return double_sha256(self.serialize())[::-1]
def id(self):
return self.hash().hex()
@classmethod
def get_address_data(cls, addr):
b58 = decode_base58(addr, num_bytes=cls.num_bytes)
prefix = b58[:-20]
h160 = b58[-20:]
testnet = prefix in cls.testnet_prefixes
if prefix in cls.p2pkh_prefixes:
script_pubkey = Script.parse(p2pkh_script(h160))
elif prefix in cls.p2sh_prefixes:
script_pubkey = Script.parse(p2sh_script(h160))
else:
raise RuntimeError('unknown type of address {} {}'.format(addr, prefix))
return {
'testnet': testnet,
'h160': h160,
'script_pubkey': script_pubkey,
}
@classmethod
def fetch_address_utxos(cls, address, at_block_height=None):
# grab all unspent transaction outputs as of block block_height
# if block_height is None, we include all utxos
address_data = cls.get_address_data(address)
serialized_script_pubkey = address_data['script_pubkey'].serialize()
socket = cls.get_socket(address_data['testnet'])
nonce = int_to_little_endian(random.randint(0, 2**32), 4)
msg = b'blockchain.fetch_history3'
socket.send(msg, zmq.SNDMORE)
socket.send(nonce, zmq.SNDMORE)
socket.send(address_data['h160'] + b'\x00\x00\x00\x00')
response_msg = socket.recv()
response_nonce = socket.recv()
if response_msg != msg or response_nonce != nonce:
raise RuntimeError('received wrong msg: {}'.format(
response_msg.decode('ascii')))
response = socket.recv()
response_code = little_endian_to_int(response[:4])
if response_code != 0:
raise RuntimeError('got code from server: {}'.format(response_code))
response = response[4:]
receives = []
spent = set()
while len(response) > 0:
kind = response[0]
prev_tx = response[1:33]
prev_index = response[33:37]
block_height = little_endian_to_int(response[37:41])
if kind == 0:
value = little_endian_to_int(response[41:49])
if at_block_height is None or block_height <= at_block_height:
receives.append([prev_tx, prev_index, value])
else:
if at_block_height is None or block_height <= at_block_height:
spent.add(little_endian_to_int(response[41:49]))
response = response[49:]
utxos = []
tx_mask = 0xffffffffffff8000
index_mask = 0x7fff
for prev_tx, prev_index, value in receives:
tx_upper_49_bits = (little_endian_to_int(prev_tx) >> 12*8) & tx_mask
index_lower_15_bits = little_endian_to_int(prev_index) & index_mask
key = tx_upper_49_bits | index_lower_15_bits
if key not in spent:
utxos.append([serialized_script_pubkey, prev_tx[::-1], little_endian_to_int(prev_index), value])
return utxos
@classmethod
def get_all_utxos(cls, addrs):
utxos = []
for addr in addrs:
# look up utxos for each address
utxos.extend(cls.fetch_address_utxos(addr))
return utxos
@classmethod
def spend_tx(cls, wifs, utxos, destination_addr, fee=540, segwit=False):
destination_address_data = cls.get_address_data(destination_addr)
testnet = destination_address_data['testnet']
if testnet:
prefix = cls.testnet_prefixes[0]
else:
prefix = cls.p2pkh_prefixes[0]
tx_ins = []
sequence = 0xffffffff
priv_lookup = {}
total = 0
for wif in wifs:
priv_key = PrivateKey.parse(wif)
if segwit:
addr = priv_key.point.segwit_address()
else:
addr = priv_key.point.address(priv_key.compressed, prefix=prefix)
# look up utxos for each address
address_data = cls.get_address_data(addr)
script_pubkey = address_data['script_pubkey']
spk = script_pubkey.serialize()
priv_lookup[spk] = priv_key
if not utxos:
raise RuntimeError('fetch utxos first')
for serialized_script_pubkey, prev_tx, prev_index, value in utxos:
tx_ins.append(TxIn(prev_tx, prev_index, b'', sequence, value=value, script_pubkey=serialized_script_pubkey))
total += value
num_tx_ins = len(tx_ins)
if num_tx_ins == 0:
raise RuntimeError('nothing to spend')
script_pubkey = destination_address_data['script_pubkey']
tx_out = TxOut(total - fee, script_pubkey.serialize())
tx = cls(cls.default_version, tx_ins, [tx_out], 0, testnet=testnet)
for index, tx_in in enumerate(tx_ins):
priv_key = priv_lookup[tx_in.script_pubkey().serialize()]
if segwit:
sec = priv_key.point.sec(True)
redeem_script = Script([0, hash160(sec)]).serialize()
else:
redeem_script = None
tx.sign_input(
index,
priv_key,
cls.default_hash_type,
compressed=priv_key.compressed,
redeem_script=redeem_script,
)
if not tx.verify():
raise RuntimeError('failed validation')
return tx
@classmethod
def spend_all_tx(cls, private_keys, destination_addr, fee, segwit, utxos):
destination_address_data = cls.get_address_data(destination_addr)
testnet = destination_address_data['testnet']
if testnet:
if segwit:
prefix = cls.p2sh_prefixes[1]
else:
prefix = cls.p2pkh_prefixes[1]
else:
if segwit:
prefix = cls.p2sh_prefixes[0]
else:
prefix = cls.p2pkh_prefixes[0]
tx_ins = []
sequence = 0xffffffff
priv_lookup = {}
total = 0
for private_key in private_keys:
if segwit:
addr = private_key.point.segwit_address(prefix=prefix)
else:
addr = private_key.point.address(private_key.compressed, prefix=prefix)
address_data = cls.get_address_data(addr)
script_pubkey = address_data['script_pubkey']
priv_lookup[script_pubkey.serialize()] = private_key
for serialized_script_pubkey, prev_tx, prev_index, value in utxos:
private_key = priv_lookup[serialized_script_pubkey]
if segwit:
script_sig = private_key.segwit_redeem_script()
else:
script_sig = b''
tx_in = TxIn(
prev_tx,
prev_index,
script_sig,
sequence,
value=value,
script_pubkey=serialized_script_pubkey,
)
tx_ins.append(tx_in)
total += value
num_tx_ins = len(tx_ins)
if num_tx_ins == 0:
return
if total - fee < 0:
return
script_pubkey = destination_address_data['script_pubkey']
print('{}: {} to {}'.format(cls, (total - fee) / cls.scale, destination_addr))
tx_out = TxOut(total - fee, script_pubkey.serialize())
tx = cls(cls.default_version, tx_ins, [tx_out], 0, testnet=testnet)
for index, tx_in in enumerate(tx_ins):
private_key = priv_lookup[tx_in.script_pubkey().serialize()]
if segwit:
sec = private_key.point.sec(True)
redeem_script = Script([0, hash160(sec)]).serialize()
else:
redeem_script = None
if not tx.sign_input(
index,
private_key,
cls.default_hash_type,
compressed=private_key.compressed,
redeem_script=redeem_script,
):
raise RuntimeError('sign and verify do different things')
if not tx.verify():
raise RuntimeError('failed validation')
return tx
@classmethod
def parse(cls, s):
'''Takes a byte stream and parses the transaction at the start
return a Tx object
'''
# s.read(n) will return n bytes
# version has 4 bytes, little-endian, interpret as int
version = little_endian_to_int(s.read(4))
# num_inputs is a varint, use read_varint(s)
num_inputs = read_varint(s)
# if we have a segwit marker, we need to parse in another way
if num_inputs == 0:
return cls.parse_segwit(s, version)
# each input needs parsing
inputs = []
for _ in range(num_inputs):
inputs.append(TxIn.parse(s))
# num_outputs is a varint, use read_varint(s)
num_outputs = read_varint(s)
# each output needs parsing
outputs = []
for _ in range(num_outputs):
outputs.append(TxOut.parse(s))
# locktime is 4 bytes, little-endian
locktime = little_endian_to_int(s.read(4))
# return an instance of the class (cls(...))
return cls(version, inputs, outputs, locktime)
@classmethod
def parse_segwit(cls, s, version):
'''Takes a byte stream and parses the segwit transaction in middle
return a Tx object
'''
marker = s.read(1)
if marker != b'\x01':
raise RuntimeError('Not a segwit transaction {}'.format(marker))
# num_inputs is a varint, use read_varint(s)
num_inputs = read_varint(s)
# each input needs parsing
tx_ins = []
for _ in range(num_inputs):
tx_ins.append(TxIn.parse(s))
# num_outputs is a varint, use read_varint(s)
num_outputs = read_varint(s)
# each output needs parsing
tx_outs = []
for _ in range(num_outputs):
tx_outs.append(TxOut.parse(s))
# now parse the witness program
for tx_in in tx_ins:
num_elements = read_varint(s)
elements = [num_elements]
for _ in range(num_elements):
element_len = read_varint(s)
elements.append(s.read(element_len))
tx_in.witness_program = Script(elements).serialize()
# locktime is 4 bytes, little-endian
locktime = little_endian_to_int(s.read(4))
# return an instance of the class (cls(...))
return cls(version, tx_ins, tx_outs, locktime)
def is_segwit(self):
for tx_in in self.tx_ins:
if tx_in.is_segwit():
return True
return False
def serialize(self):
'''Returns the byte serialization of the transaction'''
if self.is_segwit():
return self.serialize_segwit()
# serialize version (4 bytes, little endian)
result = int_to_little_endian(self.version, 4)
# encode_varint on the number of inputs
result += encode_varint(len(self.tx_ins))
# iterate inputs
for tx_in in self.tx_ins:
# serialize each input
result += tx_in.serialize()
# encode_varint on the number of inputs
result += encode_varint(len(self.tx_outs))
# iterate outputs
for tx_out in self.tx_outs:
# serialize each output
result += tx_out.serialize()
# serialize locktime (4 bytes, little endian)
result += int_to_little_endian(self.locktime, 4)
return result
def serialize_segwit(self):
'''Returns the byte serialization of the transaction'''
# serialize version (4 bytes, little endian)
result = int_to_little_endian(self.version, 4)
# segwit marker '0001'
result += b'\x00\x01'
# encode_varint on the number of inputs
result += encode_varint(len(self.tx_ins))
# iterate inputs
for tx_in in self.tx_ins:
# serialize each input
result += tx_in.serialize()
# encode_varint on the number of inputs
result += encode_varint(len(self.tx_outs))
# iterate outputs
for tx_out in self.tx_outs:
# serialize each output
result += tx_out.serialize()
# add the witness data
for tx_in in self.tx_ins:
result += tx_in.witness_program
# serialize locktime (4 bytes, little endian)
result += int_to_little_endian(self.locktime, 4)
return result
def fee(self):
'''Returns the fee of this transaction in satoshi'''
# initialize input sum and output sum
input_sum, output_sum = 0, 0
# iterate through inputs
for tx_in in self.tx_ins:
# for each input get the value and add to input sum
input_sum += tx_in.value()
# iterate through outputs
for tx_out in self.tx_outs:
# for each output get the amount and add to output sum
output_sum += tx_out.amount
# return input sum - output sum
return input_sum - output_sum
def hash_prevouts(self):
if self._hash_prevouts is None:
all_prevouts = b''
all_sequence = b''
for tx_in in self.tx_ins:
all_prevouts += tx_in.prev_tx[::-1] + int_to_little_endian(tx_in.prev_index, 4)
all_sequence += int_to_little_endian(tx_in.sequence, 4)
self._hash_prevouts = double_sha256(all_prevouts)
self._hash_sequence = double_sha256(all_sequence)
return self._hash_prevouts
def hash_sequence(self):
if self._hash_sequence is None:
self.hash_prevouts() # this should calculate self._hash_prevouts
return self._hash_sequence
def hash_outputs(self):
if self._hash_outputs is None:
all_outputs = b''
for tx_out in self.tx_outs:
all_outputs += tx_out.serialize()
self._hash_outputs = double_sha256(all_outputs)
return self._hash_outputs
def sig_hash_preimage_bip143(self, input_index, hash_type, redeem_script=None):
'''Returns the integer representation of the hash that needs to get
signed for index input_index'''
tx_in = self.tx_ins[input_index]
# per BIP143 spec
s = int_to_little_endian(self.version, 4)
s += self.hash_prevouts() + self.hash_sequence()
s += tx_in.prev_tx[::-1] + int_to_little_endian(tx_in.prev_index, 4)
if tx_in.is_segwit() or redeem_script:
if redeem_script:
h160 = redeem_script[-20:]
else:
h160 = tx_in.redeem_script()[-20:]
ser = p2pkh_script(h160)
else:
ser = tx_in.script_pubkey().serialize()
s += bytes([len(ser)]) + ser # script pubkey
s += int_to_little_endian(tx_in.value(), 8)
s += int_to_little_endian(tx_in.sequence, 4)
s += self.hash_outputs()
s += int_to_little_endian(self.locktime, 4)
s += int_to_little_endian(hash_type, 4)
return s
def sig_hash_bip143(self, input_index, hash_type, redeem_script=None):
s = self.sig_hash_preimage_bip143(input_index, hash_type, redeem_script=redeem_script)
return int.from_bytes(double_sha256(s), 'big')
def sig_hash(self, input_index, hash_type):
'''Returns the integer representation of the hash that needs to get
signed for index input_index'''
# create a transaction serialization where
# all the input script_sigs are blanked out
alt_tx_ins = []
for tx_in in self.tx_ins:
alt_tx_ins.append(TxIn(
prev_tx=tx_in.prev_tx,
prev_index=tx_in.prev_index,
script_sig=b'',
sequence=tx_in.sequence,
value=tx_in.value(),
script_pubkey=tx_in.script_pubkey().serialize(),
))
# replace the input's scriptSig with the scriptPubKey
signing_input = alt_tx_ins[input_index]
script_pubkey = signing_input.script_pubkey(self.testnet)
sig_type = script_pubkey.type()
if sig_type == 'p2pkh':
signing_input.script_sig = script_pubkey
elif sig_type == 'p2sh':
current_input = self.tx_ins[input_index]
signing_input.script_sig = Script.parse(
current_input.redeem_script())
else:
raise RuntimeError('not a valid sig_type: {}'.format(sig_type))
alt_tx = self.__class__(
version=self.version,
tx_ins=alt_tx_ins,
tx_outs=self.tx_outs,
locktime=self.locktime,
)
# add the hash_type
result = alt_tx.serialize()
result += int_to_little_endian(hash_type, 4)
return int.from_bytes(double_sha256(result), 'big')
def verify_input(self, input_index):
'''Returns whether the input has a valid signature'''
# get the relevant input
tx_in = self.tx_ins[input_index]
# get the number of signatures required. This is available in tx_in.script_sig.num_sigs_required()
sigs_required = tx_in.script_sig.num_sigs_required()
# iterate over the sigs required and check each signature
for sig_num in range(sigs_required):
# get the point from the sec format
sec = tx_in.sec_pubkey(index=sig_num)
# get the sec_pubkey at current signature index
point = S256Point.parse(sec)
# get the der sig and hash_type from input
# get the der_signature at current signature index
der, hash_type = tx_in.der_signature(index=sig_num)
# get the signature from der format
signature = Signature.parse(der)
# get the hash to sign
if tx_in.is_segwit():
h160 = hash160(tx_in.script_sig.redeem_script())
if h160 != tx_in.script_pubkey(self.testnet).elements[1]:
return False
pubkey_h160 = tx_in.script_sig.redeem_script()[-20:]
if pubkey_h160 != point.h160():
return False
z = self.sig_hash_bip143(input_index, hash_type)
else:
z = self.sig_hash(input_index, hash_type)
# use point.verify on the hash to sign and signature
if not point.verify(z, signature):
return False
return True
def sign_input(self, input_index, private_key, hash_type, compressed=True, redeem_script=None):
'''Signs the input using the private key'''
# get the hash to sign
tx_in = self.tx_ins[input_index]
if redeem_script:
z = self.sig_hash_bip143(input_index, hash_type, redeem_script=redeem_script)
else:
z = self.sig_hash(input_index, hash_type)
# get der signature of z from private key
der = private_key.sign(z).der()
# append the hash_type to der (use bytes([hash_type]))
sig = der + bytes([hash_type])
# calculate the sec
sec = private_key.point.sec(compressed=compressed)
if redeem_script:
# witness program 0
tx_in.script_sig = Script([redeem_script])
tx_in.witness_program = Script([2, sig, sec]).serialize()
else:
# initialize a new script with [sig, sec] as the elements
# change input's script_sig to new script
tx_in.script_sig = Script([sig, sec])
# return whether sig is valid using self.verify_input
return self.verify_input(input_index)
def is_coinbase(self):
'''Returns whether this transaction is a coinbase transaction or not'''
# check that there is exactly 1 input
if len(self.tx_ins) != 1:
return False
# grab the first input
first_input = self.tx_ins[0]
# check that first input prev_tx is b'\x00' * 32 bytes
if first_input.prev_tx != b'\x00' * 32:
return False
# check that first input prev_index is 0xffffffff
if first_input.prev_index != 0xffffffff:
return False
return True
def coinbase_height(self):
'''Returns the height of the block this coinbase transaction is in
Returns None if this transaction is not a coinbase transaction
'''
# if this is NOT a coinbase transaction, return None
if not self.is_coinbase():
return None
# grab the first input
first_input = self.tx_ins[0]
# grab the first element of the script_sig (.script_sig.elements[0])
first_element = first_input.script_sig.elements[0]
# convert the first element from little endian to int
return little_endian_to_int(first_element)
def verify(self):
for i in range(len(self.tx_ins)):
if not self.verify_input(i):
return False
return True
def sign(self, private_key, compressed=True):
for i in range(len(self.tx_ins)):
if not self.sign_input(
i,
private_key,
self.default_hash_type,
compressed=compressed,
):
raise RuntimeError('signing failed')
def send_insight(self):
if self.insight is None:
return
url = '{}/tx/send'.format(self.insight)
data = dumps({'rawtx': self.serialize().hex()})
r = requests.post(url, data=data, headers={'Content-Type': 'application/json'})
return r.text
class BTXTx(Tx):
fork_block = 492820
default_version = 2
fee = 200000
magic = b'\xf9\xbe\xb4\xd9'
port = 8555
seeds = ("37.120.190.76", "37.120.186.85", "185.194.140.60", "188.71.223.206", "185.194.142.122")
insight = None
@classmethod
def fetch_address_utxos(cls, address):
api_key = 'e86ce04b6888'
url = 'https://chainz.cryptoid.info/btx/api.dws?q=unspent&active={}&key={}'.format(
address, api_key)
result = requests.get(url).json()
address_data = cls.get_address_data(address)
serialized_script_pubkey = address_data['script_pubkey'].serialize()
print(result)
utxos = []
for item in result['unspent_outputs']:
utxos.append([serialized_script_pubkey, bytes.fromhex(item['tx_hash']), item['tx_ouput_n'], int(item['value'])])
return utxos
class ForkTx(Tx):
fork_block = 0
@classmethod
def fetch_address_utxos(cls, address):
return super().fetch_address_utxos(address, at_block_height=cls.fork_block)
class BTCPTx(Tx):
default_hash_type = 0x41
fork_id = 42 << 8
p2pkh_prefixes = (b'\x13\x25',)
p2sh_prefixes = (b'\x13\xaf',)
num_bytes = 26
fee = 20000
insight = 'https://explorer.btcprivate.org/api'
@classmethod
def fetch_address_utxos(cls, address):
url = 'https://explorer.btcprivate.org/api/addr/{}/utxo'.format(
address)
result = requests.get(url).json()
address_data = cls.get_address_data(address)
serialized_script_pubkey = address_data['script_pubkey'].serialize()
utxos = []
for item in result:
utxos.append([serialized_script_pubkey, bytes.fromhex(item['txid']), item['vout'], int(item['satoshis'])])
return utxos
def sig_hash(self, input_index, hash_type):
'''Returns the integer representation of the hash that needs to get
signed for index input_index'''
# create a transaction serialization where
# all the input script_sigs are blanked out
alt_tx_ins = []
for tx_in in self.tx_ins:
alt_tx_ins.append(TxIn(
prev_tx=tx_in.prev_tx,
prev_index=tx_in.prev_index,
script_sig=b'',
sequence=tx_in.sequence,
value=tx_in.value(),
script_pubkey=tx_in.script_pubkey().serialize(),
))
# replace the input's scriptSig with the scriptPubKey
signing_input = alt_tx_ins[input_index]
signing_input.script_sig = signing_input.script_pubkey(self.testnet)
alt_tx = self.__class__(
version=self.version,
tx_ins=alt_tx_ins,
tx_outs=self.tx_outs,
locktime=self.locktime,
)
# add the hash_type
result = alt_tx.serialize()
result += int_to_little_endian(hash_type | self.fork_id, 4)
return int.from_bytes(double_sha256(result), 'big')
def sign_input(self, input_index, private_key, hash_type, compressed=True, redeem_script=None):
'''Signs the input using the private key'''
# get the hash to sign
tx_in = self.tx_ins[input_index]
if redeem_script:
h160 = Script.parse(redeem_script).elements[1]
tx_in._script_pubkey = Script.parse(p2pkh_script(h160))
z = self.sig_hash(input_index, hash_type)
# get der signature of z from private key
der = private_key.sign(z).der()
# append the hash_type to der (use bytes([hash_type]))
sig = der + bytes([hash_type])
# calculate the sec
sec = private_key.point.sec(compressed=compressed)
if redeem_script:
tx_in.script_sig = Script([sig, sec, redeem_script])
else:
tx_in.script_sig = Script([sig, sec])
return self.verify_input(input_index)
class B2XTx(ForkTx):
fork_block = 501451
fork_id = 0
default_hash_type = 0x31
fee = 20000
magic = b'\xf4\xb2\xb5\xd8'
port = 8333
seeds = ("node1.b2x-segwit.io", "node2.b2x-segwit.io", "node3.b2x-segwit.io")
insight = None
def sig_hash(self, input_index, hash_type):
'''Returns the integer representation of the hash that needs to get
signed for index input_index'''
# create a transaction serialization where
# all the input script_sigs are blanked out
alt_tx_ins = []
for tx_in in self.tx_ins:
alt_tx_ins.append(TxIn(
prev_tx=tx_in.prev_tx,
prev_index=tx_in.prev_index,
script_sig=b'',
sequence=tx_in.sequence,
value=tx_in.value(),
script_pubkey=tx_in.script_pubkey().serialize(),
))
# replace the input's scriptSig with the scriptPubKey
signing_input = alt_tx_ins[input_index]
script_pubkey = signing_input.script_pubkey(self.testnet)
sig_type = script_pubkey.type()
if sig_type == 'p2pkh':
signing_input.script_sig = script_pubkey
elif sig_type == 'p2sh':
current_input = self.tx_ins[input_index]
signing_input.script_sig = Script.parse(
current_input.redeem_script())
else:
raise RuntimeError('not a valid sig_type: {}'.format(sig_type))
alt_tx = self.__class__(
version=self.version,
tx_ins=alt_tx_ins,
tx_outs=self.tx_outs,
locktime=self.locktime,
)
# add the hash_type
result = alt_tx.serialize()
result += int_to_little_endian(hash_type << 1, 4)
return int.from_bytes(double_sha256(result), 'big')
def sig_hash_preimage_bip143(self, input_index, hash_type, redeem_script=None):
'''Returns the integer representation of the hash that needs to get
signed for index input_index'''
tx_in = self.tx_ins[input_index]
# per BIP143 spec
s = int_to_little_endian(self.version, 4)
s += self.hash_prevouts() + self.hash_sequence()
s += tx_in.prev_tx[::-1] + int_to_little_endian(tx_in.prev_index, 4)
if tx_in.is_segwit() or redeem_script:
if redeem_script:
h160 = redeem_script[-20:]
else:
h160 = tx_in.redeem_script()[-20:]
ser = p2pkh_script(h160)
else:
ser = tx_in.script_pubkey().serialize()
s += bytes([len(ser)]) + ser # script pubkey
s += int_to_little_endian(tx_in.value(), 8)
s += int_to_little_endian(tx_in.sequence, 4)
s += self.hash_outputs()
s += int_to_little_endian(self.locktime, 4)
s += int_to_little_endian(hash_type << 1, 4)
return s
class LBTCTx(ForkTx):
fork_block = 499999
fork_id = 0
magic = b'\xf9\xbe\xb3\xd7'
port = 9333
seeds = ("seed9.lbtc.io", "seed8.lbtc.io", "seed10.lbtc.io")
default_version = 0xff01
fee = 200000
insight = None
class BCHTx(ForkTx):
fork_block = 478558
fork_id = 0
default_hash_type = 0x41
insight = 'https://bch-bitcore2.trezor.io/api'
fee = 540
def sig_hash_preimage_bip143(self, input_index, hash_type, redeem_script=None):
'''Returns the integer representation of the hash that needs to get
signed for index input_index'''
tx_in = self.tx_ins[input_index]
# per BIP143 spec
s = int_to_little_endian(self.version, 4)
s += self.hash_prevouts() + self.hash_sequence()
s += tx_in.prev_tx[::-1] + int_to_little_endian(tx_in.prev_index, 4)
if tx_in.is_segwit() or redeem_script:
if redeem_script:
h160 = redeem_script[-20:]
else:
h160 = tx_in.redeem_script()[-20:]
ser = p2pkh_script(h160)
else:
ser = tx_in.script_pubkey().serialize()
s += bytes([len(ser)]) + ser # script pubkey
s += int_to_little_endian(tx_in.value(), 8)
s += int_to_little_endian(tx_in.sequence, 4)
s += self.hash_outputs()
s += int_to_little_endian(self.locktime, 4)
s += int_to_little_endian(hash_type | self.fork_id, 4)
return s
def verify_input(self, input_index):
'''Returns whether the input has a valid signature'''
# get the relevant input
tx_in = self.tx_ins[input_index]
# get the sec_pubkey at current signature index
point = S256Point.parse(tx_in.sec_pubkey())
# get the der sig and hash_type from input
# get the der_signature at current signature index
der, hash_type = tx_in.der_signature()
# get the signature from der format
signature = Signature.parse(der)
# get the hash to sign
z = self.sig_hash_bip143(input_index, hash_type)
# use point.verify on the hash to sign and signature
if not point.verify(z, signature):
return False
return True
def sign_input(self, input_index, private_key, hash_type, compressed=True, redeem_script=None):
'''Signs the input using the private key'''
# get the hash to sign
z = self.sig_hash_bip143(input_index, hash_type)
# get der signature of z from private key
der = private_key.sign(z).der()
# append the hash_type to der (use bytes([hash_type]))
sig = der + bytes([hash_type])
# calculate the sec
sec = private_key.point.sec(compressed=compressed)
# initialize a new script with [sig, sec] as the elements
script_sig = Script([sig, sec])
# change input's script_sig to new script
self.tx_ins[input_index].script_sig = script_sig
# return whether sig is valid using self.verify_input
return self.verify_input(input_index)
def sign(self, private_key, compressed=True):
hash_type = self.default_hash_type
for i in range(len(self.tx_ins)):
if not self.sign_input(
i, private_key, hash_type, compressed=compressed):
raise RuntimeError('signing failed')
class BTGTx(BCHTx):
fork_block = 491407
fork_id = 79 << 8
p2pkh_prefixes = (b'\x26', b'\x6f', b'\x00')
p2sh_prefixes = (b'\x17', b'\xc4', b'\x05')
insight = 'https://btg-bitcore2.trezor.io/api'
fee = 5000
def sign_input(self, input_index, private_key, hash_type, compressed=True, redeem_script=None):
'''Signs the input using the private key'''
# get the hash to sign
z = self.sig_hash_bip143(input_index, hash_type, redeem_script=redeem_script)
# get der signature of z from private key
der = private_key.sign(z).der()
# append the hash_type to der (use bytes([hash_type]))
sig = der + bytes([hash_type])
# calculate the sec
sec = private_key.point.sec(compressed=compressed)
tx_in = self.tx_ins[input_index]
if redeem_script:
tx_in.script_sig = Script([redeem_script])
tx_in.witness_program = Script([2, sig, sec]).serialize()
else:
# initialize a new script with [sig, sec] as the elements
script_sig = Script([sig, sec])
# change input's script_sig to new script
tx_in.script_sig = script_sig
# return whether sig is valid using self.verify_input
return self.verify_input(input_index)
class BCITx(BTGTx):
fork_block = 505083
fork_id = 79 << 8
default_hash_type = 0x41
p2pkh_prefixes = (b'\x66',)
p2sh_prefixes = (b'\x17',)
insight = 'https://explorer.bitcoininterest.io/api'
magic = b'\xed\xe4\xfe\x26'
port = 8331
seeds = ("74.208.166.57", "216.250.117.221")
fee = 20000
class BTPTx(BTGTx):
fork_block = 499345
fork_id = 80 << 8
default_hash_type = 0x41
p2pkh_prefixes = (b'\x38',)
p2sh_prefixes = (b'\x05',)
insight = 'http://exp.btceasypay.com/insight-api'
fee = 20000
scale = 10000000
class BTVTx(BTGTx):
fork_block = 505050
fork_id = 50 << 8
default_hash_type = 0x41
fee = 20000
magic = b'\xf9\x50\x50\x50'
port = 8333
seeds = ("seed1.bitvote.one", "seed2.bitvote.one", "seed3.bitvote.one")
insight = 'https://block.bitvote.one/insight-api'
def sig_hash(self, input_index, hash_type):
'''Returns the integer representation of the hash that needs to get
signed for index input_index'''
# create a transaction serialization where
# all the input script_sigs are blanked out
alt_tx_ins = []
for tx_in in self.tx_ins:
alt_tx_ins.append(TxIn(
prev_tx=tx_in.prev_tx,
prev_index=tx_in.prev_index,
script_sig=b'',
sequence=tx_in.sequence,
value=tx_in.value(),
script_pubkey=tx_in.script_pubkey().serialize(),
))
# replace the input's scriptSig with the scriptPubKey
signing_input = alt_tx_ins[input_index]
script_pubkey = signing_input.script_pubkey(self.testnet)
sig_type = script_pubkey.type()
if sig_type == 'p2pkh':
signing_input.script_sig = script_pubkey
elif sig_type == 'p2sh':
current_input = self.tx_ins[input_index]
signing_input.script_sig = Script.parse(
current_input.redeem_script())
else:
raise RuntimeError('not a valid sig_type: {}'.format(sig_type))
alt_tx = self.__class__(
version=self.version,
tx_ins=alt_tx_ins,
tx_outs=self.tx_outs,
locktime=self.locktime,
)
# add the hash_type
result = alt_tx.serialize()
result += int_to_little_endian(hash_type | self.fork_id, 4)
return int.from_bytes(double_sha256(result), 'big')
def sign_input(self, input_index, private_key, hash_type, compressed=True, redeem_script=None):
'''Signs the input using the private key'''
# get the hash to sign
tx_in = self.tx_ins[input_index]
if redeem_script:
z = self.sig_hash_bip143(input_index, hash_type, redeem_script=redeem_script)
else:
z = self.sig_hash(input_index, hash_type)
# get der signature of z from private key
der = private_key.sign(z).der()
# append the hash_type to der (use bytes([hash_type]))
sig = der + bytes([hash_type])
# calculate the sec
sec = private_key.point.sec(compressed=compressed)
if redeem_script:
# witness program 0
tx_in.script_sig = Script([redeem_script])