-
Notifications
You must be signed in to change notification settings - Fork 617
/
Transaction.py
1661 lines (1428 loc) · 61.1 KB
/
Transaction.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
################################################################################
# #
# Copyright (C) 2011-2014, Armory Technologies, Inc. #
# Distributed under the GNU Affero General Public License (AGPL v3) #
# See LICENSE or http://www.gnu.org/licenses/agpl.html #
# #
################################################################################
import logging
import os
import CppBlockUtils as Cpp
from armoryengine.ArmoryUtils import *
from armoryengine.BinaryPacker import *
from armoryengine.BinaryUnpacker import *
################################################################################
# Identify all the codes/strings that are needed for dealing with scripts
################################################################################
# Start list of OP codes
OP_0 = 0
OP_FALSE = 0
OP_PUSHDATA1 = 76
OP_PUSHDATA2 = 77
OP_PUSHDATA4 = 78
OP_1NEGATE = 79
OP_1 = 81
OP_TRUE = 81
OP_2 = 82
OP_3 = 83
OP_4 = 84
OP_5 = 85
OP_6 = 86
OP_7 = 87
OP_8 = 88
OP_9 = 89
OP_10 = 90
OP_11 = 91
OP_12 = 92
OP_13 = 93
OP_14 = 94
OP_15 = 95
OP_16 = 96
OP_NOP = 97
OP_IF = 99
OP_NOTIF = 100
OP_ELSE = 103
OP_ENDIF = 104
OP_VERIFY = 105
OP_RETURN = 106
OP_TOALTSTACK = 107
OP_FROMALTSTACK = 108
OP_IFDUP = 115
OP_DEPTH = 116
OP_DROP = 117
OP_DUP = 118
OP_NIP = 119
OP_OVER = 120
OP_PICK = 121
OP_ROLL = 122
OP_ROT = 123
OP_SWAP = 124
OP_TUCK = 125
OP_2DROP = 109
OP_2DUP = 110
OP_3DUP = 111
OP_2OVER = 112
OP_2ROT = 113
OP_2SWAP = 114
OP_CAT = 126
OP_SUBSTR = 127
OP_LEFT = 128
OP_RIGHT = 129
OP_SIZE = 130
OP_INVERT = 131
OP_AND = 132
OP_OR = 133
OP_XOR = 134
OP_EQUAL = 135
OP_EQUALVERIFY = 136
OP_1ADD = 139
OP_1SUB = 140
OP_2MUL = 141
OP_2DIV = 142
OP_NEGATE = 143
OP_ABS = 144
OP_NOT = 145
OP_0NOTEQUAL = 146
OP_ADD = 147
OP_SUB = 148
OP_MUL = 149
OP_DIV = 150
OP_MOD = 151
OP_LSHIFT = 152
OP_RSHIFT = 153
OP_BOOLAND = 154
OP_BOOLOR = 155
OP_NUMEQUAL = 156
OP_NUMEQUALVERIFY = 157
OP_NUMNOTEQUAL = 158
OP_LESSTHAN = 159
OP_GREATERTHAN = 160
OP_LESSTHANOREQUAL = 161
OP_GREATERTHANOREQUAL = 162
OP_MIN = 163
OP_MAX = 164
OP_WITHIN = 165
OP_RIPEMD160 = 166
OP_SHA1 = 167
OP_SHA256 = 168
OP_HASH160 = 169
OP_HASH256 = 170
OP_CODESEPARATOR = 171
OP_CHECKSIG = 172
OP_CHECKSIGVERIFY = 173
OP_CHECKMULTISIG = 174
OP_CHECKMULTISIGVERIFY = 175
opnames = ['']*256
opnames[0] = 'OP_0'
for i in range(1,76):
opnames[i] ='OP_PUSHDATA'
opnames[76] = 'OP_PUSHDATA1'
opnames[77] = 'OP_PUSHDATA2'
opnames[78] = 'OP_PUSHDATA4'
opnames[79] = 'OP_1NEGATE'
opnames[81] = 'OP_1'
opnames[81] = 'OP_TRUE'
for i in range(1,17):
opnames[80+i] = 'OP_' + str(i)
opnames[97] = 'OP_NOP'
opnames[99] = 'OP_IF'
opnames[100] = 'OP_NOTIF'
opnames[103] = 'OP_ELSE'
opnames[104] = 'OP_ENDIF'
opnames[105] = 'OP_VERIFY'
opnames[106] = 'OP_RETURN'
opnames[107] = 'OP_TOALTSTACK'
opnames[108] = 'OP_FROMALTSTACK'
opnames[115] = 'OP_IFDUP'
opnames[116] = 'OP_DEPTH'
opnames[117] = 'OP_DROP'
opnames[118] = 'OP_DUP'
opnames[119] = 'OP_NIP'
opnames[120] = 'OP_OVER'
opnames[121] = 'OP_PICK'
opnames[122] = 'OP_ROLL'
opnames[123] = 'OP_ROT'
opnames[124] = 'OP_SWAP'
opnames[125] = 'OP_TUCK'
opnames[109] = 'OP_2DROP'
opnames[110] = 'OP_2DUP'
opnames[111] = 'OP_3DUP'
opnames[112] = 'OP_2OVER'
opnames[113] = 'OP_2ROT'
opnames[114] = 'OP_2SWAP'
opnames[126] = 'OP_CAT'
opnames[127] = 'OP_SUBSTR'
opnames[128] = 'OP_LEFT'
opnames[129] = 'OP_RIGHT'
opnames[130] = 'OP_SIZE'
opnames[131] = 'OP_INVERT'
opnames[132] = 'OP_AND'
opnames[133] = 'OP_OR'
opnames[134] = 'OP_XOR'
opnames[135] = 'OP_EQUAL'
opnames[136] = 'OP_EQUALVERIFY'
opnames[139] = 'OP_1ADD'
opnames[140] = 'OP_1SUB'
opnames[141] = 'OP_2MUL'
opnames[142] = 'OP_2DIV'
opnames[143] = 'OP_NEGATE'
opnames[144] = 'OP_ABS'
opnames[145] = 'OP_NOT'
opnames[146] = 'OP_0NOTEQUAL'
opnames[147] = 'OP_ADD'
opnames[148] = 'OP_SUB'
opnames[149] = 'OP_MUL'
opnames[150] = 'OP_DIV'
opnames[151] = 'OP_MOD'
opnames[152] = 'OP_LSHIFT'
opnames[153] = 'OP_RSHIFT'
opnames[154] = 'OP_BOOLAND'
opnames[155] = 'OP_BOOLOR'
opnames[156] = 'OP_NUMEQUAL'
opnames[157] = 'OP_NUMEQUALVERIFY'
opnames[158] = 'OP_NUMNOTEQUAL'
opnames[159] = 'OP_LESSTHAN'
opnames[160] = 'OP_GREATERTHAN'
opnames[161] = 'OP_LESSTHANOREQUAL'
opnames[162] = 'OP_GREATERTHANOREQUAL'
opnames[163] = 'OP_MIN'
opnames[164] = 'OP_MAX'
opnames[165] = 'OP_WITHIN'
opnames[166] = 'OP_RIPEMD160'
opnames[167] = 'OP_SHA1'
opnames[168] = 'OP_SHA256'
opnames[169] = 'OP_HASH160'
opnames[170] = 'OP_HASH256'
opnames[171] = 'OP_CODESEPARATOR'
opnames[172] = 'OP_CHECKSIG'
opnames[173] = 'OP_CHECKSIGVERIFY'
opnames[174] = 'OP_CHECKMULTISIG'
opnames[175] = 'OP_CHECKMULTISIGVERIFY'
opCodeLookup = {}
opCodeLookup['OP_FALSE'] = 0
opCodeLookup['OP_PUSHDATA1'] = 76
opCodeLookup['OP_PUSHDATA2'] = 77
opCodeLookup['OP_PUSHDATA4'] = 78
opCodeLookup['OP_1NEGATE'] = 79
opCodeLookup['OP_1'] = 81
for i in range(1,17):
opCodeLookup['OP_'+str(i)] = 80+i
opCodeLookup['OP_TRUE'] = 81
opCodeLookup['OP_NOP'] = 97
opCodeLookup['OP_IF'] = 99
opCodeLookup['OP_NOTIF'] = 100
opCodeLookup['OP_ELSE'] = 103
opCodeLookup['OP_ENDIF'] = 104
opCodeLookup['OP_VERIFY'] = 105
opCodeLookup['OP_RETURN'] = 106
opCodeLookup['OP_TOALTSTACK'] = 107
opCodeLookup['OP_FROMALTSTACK'] = 108
opCodeLookup['OP_IFDUP'] = 115
opCodeLookup['OP_DEPTH'] = 116
opCodeLookup['OP_DROP'] = 117
opCodeLookup['OP_DUP'] = 118
opCodeLookup['OP_NIP'] = 119
opCodeLookup['OP_OVER'] = 120
opCodeLookup['OP_PICK'] = 121
opCodeLookup['OP_ROLL'] = 122
opCodeLookup['OP_ROT'] = 123
opCodeLookup['OP_SWAP'] = 124
opCodeLookup['OP_TUCK'] = 125
opCodeLookup['OP_2DROP'] = 109
opCodeLookup['OP_2DUP'] = 110
opCodeLookup['OP_3DUP'] = 111
opCodeLookup['OP_2OVER'] = 112
opCodeLookup['OP_2ROT'] = 113
opCodeLookup['OP_2SWAP'] = 114
opCodeLookup['OP_CAT'] = 126
opCodeLookup['OP_SUBSTR'] = 127
opCodeLookup['OP_LEFT'] = 128
opCodeLookup['OP_RIGHT'] = 129
opCodeLookup['OP_SIZE'] = 130
opCodeLookup['OP_INVERT'] = 131
opCodeLookup['OP_AND'] = 132
opCodeLookup['OP_OR'] = 133
opCodeLookup['OP_XOR'] = 134
opCodeLookup['OP_EQUAL'] = 135
opCodeLookup['OP_EQUALVERIFY'] = 136
opCodeLookup['OP_1ADD'] = 139
opCodeLookup['OP_1SUB'] = 140
opCodeLookup['OP_2MUL'] = 141
opCodeLookup['OP_2DIV'] = 142
opCodeLookup['OP_NEGATE'] = 143
opCodeLookup['OP_ABS'] = 144
opCodeLookup['OP_NOT'] = 145
opCodeLookup['OP_0NOTEQUAL'] = 146
opCodeLookup['OP_ADD'] = 147
opCodeLookup['OP_SUB'] = 148
opCodeLookup['OP_MUL'] = 149
opCodeLookup['OP_DIV'] = 150
opCodeLookup['OP_MOD'] = 151
opCodeLookup['OP_LSHIFT'] = 152
opCodeLookup['OP_RSHIFT'] = 153
opCodeLookup['OP_BOOLAND'] = 154
opCodeLookup['OP_BOOLOR'] = 155
opCodeLookup['OP_NUMEQUAL'] = 156
opCodeLookup['OP_NUMEQUALVERIFY'] = 157
opCodeLookup['OP_NUMNOTEQUAL'] = 158
opCodeLookup['OP_LESSTHAN'] = 159
opCodeLookup['OP_GREATERTHAN'] = 160
opCodeLookup['OP_LESSTHANOREQUAL'] = 161
opCodeLookup['OP_GREATERTHANOREQUAL'] = 162
opCodeLookup['OP_MIN'] = 163
opCodeLookup['OP_MAX'] = 164
opCodeLookup['OP_WITHIN'] = 165
opCodeLookup['OP_RIPEMD160'] = 166
opCodeLookup['OP_SHA1'] = 167
opCodeLookup['OP_SHA256'] = 168
opCodeLookup['OP_HASH160'] = 169
opCodeLookup['OP_HASH256'] = 170
opCodeLookup['OP_CODESEPARATOR'] = 171
opCodeLookup['OP_CHECKSIG'] = 172
opCodeLookup['OP_CHECKSIGVERIFY'] = 173
opCodeLookup['OP_CHECKMULTISIG'] = 174
opCodeLookup['OP_CHECKMULTISIGVERIFY'] = 175
#Word Opcode Description
#OP_PUBKEYHASH = 253 Represents a public key hashed with OP_HASH160.
#OP_PUBKEY = 254 Represents a public key compatible with OP_CHECKSIG.
#OP_INVALIDOPCODE = 255 Matches any opcode that is not yet assigned.
#[edit] Reserved words
#Any opcode not assigned is also reserved. Using an unassigned opcode makes the transaction invalid.
#Word Opcode When used...
#OP_RESERVED = 80 Transaction is invalid
#OP_VER = 98 Transaction is invalid
#OP_VERIF = 101 Transaction is invalid
#OP_VERNOTIF = 102 Transaction is invalid
#OP_RESERVED1 = 137 Transaction is invalid
#OP_RESERVED2 = 138 Transaction is invalid
#OP_NOP1 = OP_NOP10 176-185 The word is ignored.
################################################################################
def getOpCode(name):
return int_to_binary(opCodeLookup[name], widthBytes=1)
################################################################################
def getMultisigScriptInfo(rawScript):
"""
Gets the Multi-Sig tx type, as well as all the address-160 strings of
the keys that are needed to satisfy this transaction. This currently
only identifies M-of-N transaction types, returning unknown otherwise.
However, the address list it returns should be valid regardless of
whether the type was unknown: we assume all 20-byte chunks of data
are public key hashes, and 65-byte chunks are public keys.
M==0 (output[0]==0) indicates this isn't a multisig script
"""
scrAddr = ''
addr160List = []
pubKeyList = []
M,N = 0,0
pubKeyStr = Cpp.BtcUtils().getMultisigPubKeyInfoStr(rawScript)
bu = BinaryUnpacker(pubKeyStr)
M = bu.get(UINT8)
N = bu.get(UINT8)
if M==0:
return [0, 0, None, None]
for i in range(N):
pkstr = bu.get(BINARY_CHUNK, 33)
if pkstr[0] == '\x04':
pkstr += bu.get(BINARY_CHUNK, 32)
pubKeyList.append(pkstr)
addr160List.append(hash160(pkstr))
return M, N, addr160List, pubKeyList
################################################################################
def getHash160ListFromMultisigScrAddr(scrAddr):
mslen = len(scrAddr) - 3
if not (mslen%20==0 and scrAddr[0]==SCRADDR_MULTISIG_BYTE):
raise BadAddressError('Supplied ScrAddr is not multisig!')
catList = scrAddr[3:]
return [catList[20*i:20*(i+1)] for i in range(len(catList)/20)]
################################################################################
# These two methods are just easier-to-type wrappers around the C++ methods
def getTxOutScriptType(script):
return Cpp.BtcUtils().getTxOutScriptTypeInt(script)
################################################################################
def getTxInScriptType(txinObj):
"""
NOTE: this method takes a TXIN object, not just the script itself. This
is because this method needs to see the OutPoint to distinguish an
UNKNOWN TxIn from a coinbase-TxIn
"""
script = txinObj.binScript
prevTx = txinObj.outpoint.txHash
return Cpp.BtcUtils().getTxInScriptTypeInt(script, prevTx)
################################################################################
def getTxInP2SHScriptType(txinObj):
"""
If this TxIn is identified as SPEND-P2SH, then it contains a subscript that
is really a TxOut script (which must hash to the value included on the
actual TxOut script).
Use this to get the TxOut script type of the Spend-P2SH subscript
"""
scrType = getTxInScriptType(txinObj)
if not scrType==CPP_TXIN_SPENDP2SH:
return None
lastPush = Cpp.BtcUtils().getLastPushDataInScript(txinObj.binScript)
return getTxOutScriptType(lastPush)
################################################################################
def TxInExtractAddrStrIfAvail(txinObj):
rawScript = txinObj.binScript
prevTxHash = txinObj.outpoint.txHash
scrType = Cpp.BtcUtils().getTxInScriptTypeInt(rawScript, prevTxHash)
lastPush = Cpp.BtcUtils().getLastPushDataInScript(rawScript)
if scrType in [CPP_TXIN_STDUNCOMPR, CPP_TXIN_STDCOMPR]:
return hash160_to_addrStr( hash160(lastPush) )
elif scrType == CPP_TXIN_SPENDP2SH:
return hash160_to_p2shStr( hash160(lastPush) )
else:
return ''
################################################################################
def TxInExtractPreImageIfAvail(txinObj):
rawScript = txinObj.binScript
prevTxHash = txinObj.outpoint.txHash
scrType = Cpp.BtcUtils().getTxInScriptTypeInt(rawScript, prevTxHash)
if scrType == [CPP_TXIN_STDUNCOMPR, CPP_TXIN_STDCOMPR, CPP_TXIN_SPENDP2SH]:
return Cpp.BtcUtils().getLastPushDataInScript(rawScript)
else:
return ''
# Finally done with all the base conversion functions and ECDSA code
# Now define the classes for the objects that will use this
################################################################################
# Transaction Classes
################################################################################
#####
class BlockComponent(object):
def copy(self):
return self.__class__().unserialize(self.serialize())
def serialize(self):
raise NotImplementedError
def unserialize(self):
raise NotImplementedError
################################################################################
class PyOutPoint(BlockComponent):
#def __init__(self, txHash, txOutIndex):
#self.txHash = txHash
#self.txOutIndex = outIndex
def unserialize(self, toUnpack):
if isinstance(toUnpack, BinaryUnpacker):
opData = toUnpack
else:
opData = BinaryUnpacker( toUnpack )
if opData.getRemainingSize() < 36: raise UnserializeError
self.txHash = opData.get(BINARY_CHUNK, 32)
self.txOutIndex = opData.get(UINT32)
return self
def serialize(self):
binOut = BinaryPacker()
binOut.put(BINARY_CHUNK, self.txHash)
binOut.put(UINT32, self.txOutIndex)
return binOut.getBinaryString()
def pprint(self, nIndent=0, endian=BIGENDIAN):
indstr = indent*nIndent
print indstr + 'OutPoint:'
print indstr + indent + 'PrevTxHash:', \
binary_to_hex(self.txHash, endian), \
'(BE)' if endian==BIGENDIAN else '(LE)'
print indstr + indent + 'TxOutIndex:', self.txOutIndex
#####
class PyTxIn(BlockComponent):
def __init__(self):
self.outpoint = UNINITIALIZED
self.binScript = UNINITIALIZED
self.intSeq = 2**32-1
def unserialize(self, toUnpack):
if isinstance(toUnpack, BinaryUnpacker):
txInData = toUnpack
else:
txInData = BinaryUnpacker( toUnpack )
self.outpoint = PyOutPoint().unserialize( txInData.get(BINARY_CHUNK, 36) )
scriptSize = txInData.get(VAR_INT)
if txInData.getRemainingSize() < scriptSize+4: raise UnserializeError
self.binScript = txInData.get(BINARY_CHUNK, scriptSize)
self.intSeq = txInData.get(UINT32)
return self
def getScript(self):
return self.binScript
def serialize(self):
binOut = BinaryPacker()
binOut.put(BINARY_CHUNK, self.outpoint.serialize() )
binOut.put(VAR_INT, len(self.binScript))
binOut.put(BINARY_CHUNK, self.binScript)
binOut.put(UINT32, self.intSeq)
return binOut.getBinaryString()
def pprint(self, nIndent=0, endian=BIGENDIAN):
indstr = indent*nIndent
print indstr + 'PyTxIn:'
print indstr + indent + 'PrevTxHash:', \
binary_to_hex(self.outpoint.txHash, endian), \
'(BE)' if endian==BIGENDIAN else '(LE)'
print indstr + indent + 'TxOutIndex:', self.outpoint.txOutIndex
print indstr + indent + 'Script: ', \
'('+binary_to_hex(self.binScript)[:64]+')'
addrStr = TxInExtractAddrStrIfAvail(self)
if len(addrStr)==0:
addrStr = '<UNKNOWN>'
print indstr + indent + 'Sender: ', addrStr
print indstr + indent + 'Seq: ', self.intSeq
def toString(self, nIndent=0, endian=BIGENDIAN):
indstr = indent*nIndent
indstr2 = indstr + indent
result = indstr + 'PyTxIn:'
result = ''.join([result, '\n', indstr2 + 'PrevTxHash:', \
binary_to_hex(self.outpoint.txHash, endian), \
'(BE)' if endian==BIGENDIAN else '(LE)'])
result = ''.join([result, '\n', indstr2 + 'TxOutIndex:', \
str(self.outpoint.txOutIndex)])
result = ''.join([result, '\n', indstr2 + 'Script: ', \
'('+binary_to_hex(self.binScript)[:64]+')'])
addrStr = TxInExtractAddrStrIfAvail(self)
if len(addrStr)>0:
result = ''.join([result, '\n', indstr2 + 'Sender: ', addrStr])
result = ''.join([result, '\n', indstr2 + 'Seq: ', str(self.intSeq)])
return result
# Before broadcasting a transaction make sure that the script is canonical
# This TX could have been signed by an older version of the software.
# Either on the offline Armory installation which may not have been upgraded
# or on a previous installation of Armory on this computer.
def minimizeDERSignaturePadding(self):
rsLen = binary_to_int(self.binScript[2:3])
rLen = binary_to_int(self.binScript[4:5])
rBin = self.binScript[5:5+rLen]
sLen = binary_to_int(self.binScript[6+rLen:7+rLen])
sBin = self.binScript[7+rLen:7+rLen+sLen]
sigScript = createSigScriptFromRS(rBin, sBin)
newBinScript = int_to_binary(len(sigScript)+1) + sigScript + self.binScript[3+rsLen:]
paddingRemoved = newBinScript != self.binScript
newTxIn = self.copy()
newTxIn.binScript = newBinScript
return paddingRemoved, newTxIn
#####
class PyTxOut(BlockComponent):
def __init__(self):
self.value = UNINITIALIZED
self.binScript = UNINITIALIZED
def unserialize(self, toUnpack):
if isinstance(toUnpack, BinaryUnpacker):
txOutData = toUnpack
else:
txOutData = BinaryUnpacker( toUnpack )
self.value = txOutData.get(UINT64)
scriptSize = txOutData.get(VAR_INT)
if txOutData.getRemainingSize() < scriptSize: raise UnserializeError
self.binScript = txOutData.get(BINARY_CHUNK, scriptSize)
return self
def getValue(self):
return self.value
def getScript(self):
return self.binScript
def serialize(self):
binOut = BinaryPacker()
binOut.put(UINT64, self.value)
binOut.put(VAR_INT, len(self.binScript))
binOut.put(BINARY_CHUNK, self.binScript)
return binOut.getBinaryString()
def pprint(self, nIndent=0, endian=BIGENDIAN):
"""
indstr = indent*nIndent
indstr2 = indent*nIndent + indent
print indstr + 'TxOut:'
print indstr2 + 'Value: ', self.value, '(', float(self.value) / ONE_BTC, ')'
txoutType = getTxOutScriptType(self.binScript)
if txoutType in [CPP_TXOUT_STDPUBKEY33, CPP_TXOUT_STDPUBKEY65]:
print indstr2 + 'Script: PubKey(%s) OP_CHECKSIG' % \
script_to_addrStr(self.binScript)
elif txoutType == CPP_TXOUT_STDHASH160:
print indstr2 + 'Script: OP_DUP OP_HASH160 (%s) OP_EQUALVERIFY OP_CHECKSIG' % \
script_to_addrStr(self.binScript)
elif txoutType == CPP_TXOUT_P2SH:
print indstr2 + 'Script: OP_HASH160 (%s) OP_EQUAL' % \
script_to_addrStr(self.binScript)
else:
opStrList = convertScriptToOpStrings(self.binScript)
print indstr + indent + 'Script: ', ' '.join(opStrList)
"""
print self.toString(nIndent, endian)
def toString(self, nIndent=0, endian=BIGENDIAN):
indstr = indent*nIndent
indstr2 = indent*nIndent + indent
valStr, btcStr = str(self.value), str(float(self.value)/ONE_BTC)
result = indstr + 'TxOut:\n'
result += indstr2 + 'Value: %s (%s)\n' % (valStr, btcStr)
result += indstr2
txoutType = getTxOutScriptType(self.binScript)
if txoutType in [CPP_TXOUT_STDPUBKEY33, CPP_TXOUT_STDPUBKEY65]:
result += 'Script: PubKey(%s) OP_CHECKSIG \n' % \
script_to_addrStr(self.binScript)
elif txoutType == CPP_TXOUT_STDHASH160:
result += 'Script: OP_DUP OP_HASH160 (%s) OP_EQUALVERIFY OP_CHECKSIG' % \
script_to_addrStr(self.binScript)
elif txoutType == CPP_TXOUT_P2SH:
result += 'Script: OP_HASH160 (%s) OP_EQUAL' % \
script_to_addrStr(self.binScript)
else:
opStrList = convertScriptToOpStrings(self.binScript)
result += 'Script: ' + ' '.join(opStrList)
return result
#####
class PyTx(BlockComponent):
def __init__(self):
self.version = UNINITIALIZED
self.inputs = UNINITIALIZED
self.outputs = UNINITIALIZED
self.lockTime = 0
self.thisHash = UNINITIALIZED
def serialize(self):
binOut = BinaryPacker()
binOut.put(UINT32, self.version)
binOut.put(VAR_INT, len(self.inputs))
for txin in self.inputs:
binOut.put(BINARY_CHUNK, txin.serialize())
binOut.put(VAR_INT, len(self.outputs))
for txout in self.outputs:
binOut.put(BINARY_CHUNK, txout.serialize())
binOut.put(UINT32, self.lockTime)
return binOut.getBinaryString()
def unserialize(self, toUnpack):
if isinstance(toUnpack, BinaryUnpacker):
txData = toUnpack
else:
txData = BinaryUnpacker( toUnpack )
startPos = txData.getPosition()
self.inputs = []
self.outputs = []
self.version = txData.get(UINT32)
numInputs = txData.get(VAR_INT)
for i in xrange(numInputs):
self.inputs.append( PyTxIn().unserialize(txData) )
numOutputs = txData.get(VAR_INT)
for i in xrange(numOutputs):
self.outputs.append( PyTxOut().unserialize(txData) )
self.lockTime = txData.get(UINT32)
endPos = txData.getPosition()
self.nBytes = endPos - startPos
self.thisHash = hash256(self.serialize())
return self
# Before broadcasting a transaction make sure that the script is canonical
# This TX could have been signed by an older version of the software.
# Either on the offline Armory installation which may not have been upgraded
# or on a previous installation of Armory on this computer.
def minimizeDERSignaturePadding(self):
paddingRemoved = False
newTx = self.copy()
newTx.inputs = []
for txIn in self.inputs:
paddingRemovedFromTxIn, newTxIn = txIn.minimizeDERSignaturePadding()
if paddingRemovedFromTxIn:
paddingRemoved = True
newTx.inputs.append(newTxIn)
else:
newTx.inputs.append(txIn)
return paddingRemoved, newTx.copy()
def getHash(self):
return hash256(self.serialize())
def getHashHex(self, endianness=LITTLEENDIAN):
return binary_to_hex(self.getHash(), endOut=endianness)
def makeRecipientsList(self):
"""
Make a list of lists, each one containing information about
an output in this tx. Usually contains
[ScriptType, Value, Script]
May include more information if any of the scripts are multi-sig,
such as public keys and multi-sig type (M-of-N)
"""
recipInfoList = []
for txout in self.outputs:
recipInfoList.append([])
scrType = getTxOutScriptType(txout.binScript)
recipInfoList[-1].append(scrType)
recipInfoList[-1].append(txout.value)
recipInfoList[-1].append(txout.binScript)
if scrType == CPP_TXOUT_MULTISIG:
recipInfoList[-1].append(getMultisigScriptInfo(txout.binScript))
else:
recipInfoList[-1].append([])
return recipInfoList
def pprint(self, nIndent=0, endian=BIGENDIAN):
indstr = indent*nIndent
print indstr + 'Transaction:'
print indstr + indent + 'TxHash: ', self.getHashHex(endian), \
'(BE)' if endian==BIGENDIAN else '(LE)'
print indstr + indent + 'Version: ', self.version
print indstr + indent + 'nInputs: ', len(self.inputs)
print indstr + indent + 'nOutputs: ', len(self.outputs)
print indstr + indent + 'LockTime: ', self.lockTime
print indstr + indent + 'Inputs: '
for inp in self.inputs:
inp.pprint(nIndent+2, endian=endian)
print indstr + indent + 'Outputs: '
for out in self.outputs:
out.pprint(nIndent+2, endian=endian)
def toString(self, nIndent=0, endian=BIGENDIAN):
indstr = indent*nIndent
result = indstr + 'Transaction:'
result = ''.join([result, '\n', indstr + indent + 'TxHash: ', self.getHashHex(endian), \
'(BE)' if endian==BIGENDIAN else '(LE)'])
result = ''.join([result, '\n', indstr + indent + 'Version: ', str(self.version)])
result = ''.join([result, '\n', indstr + indent + 'nInputs: ', str(len(self.inputs))])
result = ''.join([result, '\n', indstr + indent + 'nOutputs: ', str(len(self.outputs))])
result = ''.join([result, '\n', indstr + indent + 'LockTime: ', str(self.lockTime)])
result = ''.join([result, '\n', indstr + indent + 'Inputs: '])
for inp in self.inputs:
result = ''.join([result, '\n', inp.toString(nIndent+2, endian=endian)])
print indstr + indent + 'Outputs: '
for out in self.outputs:
result = ''.join([result, '\n', out.toString(nIndent+2, endian=endian)])
return result
def fetchCpp(self):
""" Use the info in this PyTx to get the C++ version from TheBDM """
return TheBDM.getTxByHash(self.getHash())
def pprintHex(self, nIndent=0):
bu = BinaryUnpacker(self.serialize())
theSer = self.serialize()
print binary_to_hex(bu.get(BINARY_CHUNK, 4))
nTxin = bu.get(VAR_INT)
print 'VAR_INT(%d)' % nTxin
for i in range(nTxin):
print binary_to_hex(bu.get(BINARY_CHUNK,32))
print binary_to_hex(bu.get(BINARY_CHUNK,4))
scriptSz = bu.get(VAR_INT)
print 'VAR_IN(%d)' % scriptSz
print binary_to_hex(bu.get(BINARY_CHUNK,scriptSz))
print binary_to_hex(bu.get(BINARY_CHUNK,4))
nTxout = bu.get(VAR_INT)
print 'VAR_INT(%d)' % nTxout
for i in range(nTxout):
print binary_to_hex(bu.get(BINARY_CHUNK,8))
scriptSz = bu.get(VAR_INT)
print binary_to_hex(bu.get(BINARY_CHUNK,scriptSz))
print binary_to_hex(bu.get(BINARY_CHUNK, 4))
################################################################################
################################################################################
# This class can be used for both multi-signature tx collection, as well as
# offline wallet signing (you are collecting signatures for a 1-of-1 tx only
# involving yourself).
class PyTxDistProposal(object):
"""
PyTxDistProposal is created from a PyTx object, and represents
an unsigned transaction, that may require the signatures of
multiple parties before being accepted by the network.
This technique (https://en.bitcoin.it/wiki/BIP_0010) is that
once TxDP is created, the system signing it only needs the
ECDSA private keys and nothing else. This enables the device
providing the signatures to be extremely lightweight, since it
doesn't have to store the blockchain.
For a given TxDP, we will be storing the following structure
in memory. Use a 4-input tx as an example, with the first
being a 2-of-3 multi-sig transaction (unsigned), and the last
is a 2-o-2 P2SH input.
self.scriptTypes = [ CPP_TXOUT_MULTISIG,
CPP_TXOUT_STDHASH160,
CPP_TXOUT_STDHASH160,
CPP_TXOUT_P2SH]
self.inputValues = [ long(23.13 * ONE_BTC),
long( 4.00 * ONE_BTC),
long(10.00 * ONE_BTC),
long( 5.00 * ONE_BTC) ]
self.signatures = [ ['', '', ''],
[''],
[''],
[''], ]
self.inScrAddrList = [ fe0203<a160_1><a160_2><a160_3>,
HASH160PREFIX + a160_4,
HASH160PREFIX + a160_5,
P2SHPREFIX + p2sh160 ]
self.p2shScripts = [ '',
'',
'',
<scriptThatHashesTo_p2sh160>]
# Usually only have public keys on multi-sig TxOuts
self.inPubKeyLists = [ [pubKey1, pubKey2, pubKey3],
[''],
[''],
[pubKey6, pubKey7] ]
self.numSigsNeeded = [ 2,
1,
1,
2 ]
self.relevantTxMap = [ prevTx0Hash: prevTx0.serialize(),
prevTx1Hash: prevTx1.serialize(),
prevTx2Hash: prevTx2.serialize(),
prevTx3Hash: prevTx3.serialize() ]
UPDATE Feb 2012: Before Jan 29, 2012, BIP 0010 used a different technique
for communicating blockchain information to the offline
device. This is no longer the case
Gregory Maxwell identified a reasonable-enough security
risk with the fact that previous BIP 0010 cannot guarantee
validity of stated input values in a TxDP. This is solved
by adding the supporting transactions to the TxDP, so that
the signing device can get the input values from those
tx and verify the hash matches the OutPoint on the tx
being signed (which *is* part of what's being signed).
The concern was that someone could manipulate your online
computer to misrepresent the inputs, and cause you to
send you entire wallet to tx-fees. Not the most useful
attack (for someone trying to steal your coins), but it is
still a risk that can be avoided by adding some "bloat" to
the TxDP
"""
#############################################################################
def __init__(self, pytx=None, txMap={}):
self.pytxObj = UNINITIALIZED
self.uniqueB58 = ''
self.scriptTypes = []
self.signatures = []
self.txOutScripts = []
self.inScrAddrList = []
self.p2shScripts = []
self.inPubKeyLists = []
self.inputValues = []
self.numSigsNeeded = []
self.relevantTxMap = {} # needed to support input values of each TxIn
if pytx:
self.createFromPyTx(pytx, txMap)
#############################################################################
def createFromPyTx(self, pytx, txMap={}, p2shMap={}):
sz = len(pytx.inputs)
self.pytxObj = pytx.copy()
self.uniqueB58 = binary_to_base58(hash256(pytx.serialize()))[:8]
self.scriptTypes = []
self.signatures = []
self.txOutScripts = []
self.inScrAddrList = []
self.inPubKeyLists = []
self.inputValues = []
self.numSigsNeeded = []
self.relevantTxMap = {} # needed to support input values of each TxIn
self.p2shScripts = []
if len(txMap)==0 and not TheBDM.getBDMState()=='BlockchainReady':
# TxDP includes the transactions that supply the inputs to this
# transaction, so the BDM needs to be available to fetch those.
raise BlockchainUnavailableError, ('Must input supporting transactions '
'or access to the blockchain, to '
'create the TxDP')
for i in range(sz):
# First, make sure that we have the previous Tx data available
# We can't continue without it, since BIP 0010 will now require
# the full tx of outputs being spent
outpt = self.pytxObj.inputs[i].outpoint
txhash = outpt.txHash
txidx = outpt.txOutIndex
pyPrevTx = None
if len(txMap)>0:
# If supplied a txMap, we expect it to have everything we need
if not txMap.has_key(txhash):
raise InvalidHashError, ('Could not find the referenced tx '
'in supplied txMap')
pyPrevTx = txMap[txhash].copy()
elif TheBDM.getBDMState()=='BlockchainReady':
cppPrevTx = TheBDM.getTxByHash(txhash)
if not cppPrevTx:
raise InvalidHashError, 'Could not find the referenced tx'
pyPrevTx = PyTx().unserialize(cppPrevTx.serialize())
else:
raise InvalidScriptError, 'No previous-tx data available for TxDP'
self.relevantTxMap[txhash] = pyPrevTx.copy()
# Now we have the previous transaction. We need to pull the
# script out of the specific TxOut so we know how it can be
# spent.
script = pyPrevTx.outputs[txidx].binScript
value = pyPrevTx.outputs[txidx].value
scrType = getTxOutScriptType(script)
self.inputValues.append(value)
self.txOutScripts.append(str(script)) # copy it
self.scriptTypes.append(scrType)
# Make sure we always add an element to each of these
self.numSigsNeeded.append(-1)
self.inScrAddrList.append('')
self.p2shScripts.append('')
self.inPubKeyLists.append([])
self.signatures.append([])
# If this is a P2SH TxOut being spent, we store the information
# about the SUBSCRIPT, since that is ultimately what needs to be
# "solved" to spend the coins. The fact that self.p2shScripts[i]
# will be non-empty is how we know we need to add the serialized
# SUBSCRIPT to the end of the sigScript when signing.
if scrType==CPP_TXOUT_P2SH:
p2shScrAddr = script_to_scrAddr(script)
if not p2shMap.has_key(p2shScrAddr):
raise InvalidScriptError, 'No P2SH script info avail for TxDP'
else:
scriptHash = hash160(p2shMap[p2shScrAddr])
if not SCRADDR_P2SH_BYTE+scriptHash == p2shScrAddr:
raise InvalidScriptError, 'No P2SH script info avail for TxDP'
script = p2shMap[p2shScrAddr]
self.p2shScripts[-1] = script
scrType = getTxOutScriptType(script)
self.scriptTypes[-1] = scrType
# Fill some of the other fields with info needed to spend the script
if scrType==CPP_TXOUT_P2SH:
# Technically, this is just "OP_HASH160 <DATA> OP_EQUAL" in the
# subscript which would be unusual and mostly useless. I'll assume
# here that it was an attempt at recursive P2SH, since they are
# both the same to our code: unspendable
raise InvalidScriptError('Cannot have recursive P2SH scripts!')
elif scrType in CPP_TXOUT_STDSINGLESIG:
self.numSigsNeeded[-1] = 1
self.inScrAddrList[-1] = script_to_scrAddr(script)
self.signatures[-1] = ['']
elif scrType==CPP_TXOUT_MULTISIG:
M, N, a160s, pubs = getMultisigScriptInfo(script)
self.inScrAddrList[-1] = [SCRADDR_P2PKH_BYTE+a for a in a160s]
self.inPubKeyLists[-1] = pubs[:]
self.signatures[-1] = ['']*len(addrs)
self.numSigsNeeded[-1] = M
else:
LOGWARN("Non-standard script for TxIn %d" % i)
LOGWARN(binary_to_hex(script))
pass
return self