You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

script.py 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2015-2017 The Bitcoin Core developers
  3. # Distributed under the MIT software license, see the accompanying
  4. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. """Functionality to build scripts, as well as SignatureHash().
  6. This file is modified from python-bitcoinlib.
  7. """
  8. from .mininode import CTransaction, CTxOut, sha256, hash256, uint256_from_str, ser_uint256, ser_string
  9. from binascii import hexlify
  10. import hashlib
  11. import sys
  12. bchr = chr
  13. bord = ord
  14. if sys.version > '3':
  15. long = int
  16. bchr = lambda x: bytes([x])
  17. bord = lambda x: x
  18. import struct
  19. from .bignum import bn2vch
  20. MAX_SCRIPT_ELEMENT_SIZE = 520
  21. OPCODE_NAMES = {}
  22. def hash160(s):
  23. return hashlib.new('ripemd160', sha256(s)).digest()
  24. _opcode_instances = []
  25. class CScriptOp(int):
  26. """A single script opcode"""
  27. __slots__ = []
  28. @staticmethod
  29. def encode_op_pushdata(d):
  30. """Encode a PUSHDATA op, returning bytes"""
  31. if len(d) < 0x4c:
  32. return b'' + bchr(len(d)) + d # OP_PUSHDATA
  33. elif len(d) <= 0xff:
  34. return b'\x4c' + bchr(len(d)) + d # OP_PUSHDATA1
  35. elif len(d) <= 0xffff:
  36. return b'\x4d' + struct.pack(b'<H', len(d)) + d # OP_PUSHDATA2
  37. elif len(d) <= 0xffffffff:
  38. return b'\x4e' + struct.pack(b'<I', len(d)) + d # OP_PUSHDATA4
  39. else:
  40. raise ValueError("Data too long to encode in a PUSHDATA op")
  41. @staticmethod
  42. def encode_op_n(n):
  43. """Encode a small integer op, returning an opcode"""
  44. if not (0 <= n <= 16):
  45. raise ValueError('Integer must be in range 0 <= n <= 16, got %d' % n)
  46. if n == 0:
  47. return OP_0
  48. else:
  49. return CScriptOp(OP_1 + n-1)
  50. def decode_op_n(self):
  51. """Decode a small integer opcode, returning an integer"""
  52. if self == OP_0:
  53. return 0
  54. if not (self == OP_0 or OP_1 <= self <= OP_16):
  55. raise ValueError('op %r is not an OP_N' % self)
  56. return int(self - OP_1+1)
  57. def is_small_int(self):
  58. """Return true if the op pushes a small integer to the stack"""
  59. if 0x51 <= self <= 0x60 or self == 0:
  60. return True
  61. else:
  62. return False
  63. def __str__(self):
  64. return repr(self)
  65. def __repr__(self):
  66. if self in OPCODE_NAMES:
  67. return OPCODE_NAMES[self]
  68. else:
  69. return 'CScriptOp(0x%x)' % self
  70. def __new__(cls, n):
  71. try:
  72. return _opcode_instances[n]
  73. except IndexError:
  74. assert len(_opcode_instances) == n
  75. _opcode_instances.append(super(CScriptOp, cls).__new__(cls, n))
  76. return _opcode_instances[n]
  77. # Populate opcode instance table
  78. for n in range(0xff+1):
  79. CScriptOp(n)
  80. # push value
  81. OP_0 = CScriptOp(0x00)
  82. OP_FALSE = OP_0
  83. OP_PUSHDATA1 = CScriptOp(0x4c)
  84. OP_PUSHDATA2 = CScriptOp(0x4d)
  85. OP_PUSHDATA4 = CScriptOp(0x4e)
  86. OP_1NEGATE = CScriptOp(0x4f)
  87. OP_RESERVED = CScriptOp(0x50)
  88. OP_1 = CScriptOp(0x51)
  89. OP_TRUE=OP_1
  90. OP_2 = CScriptOp(0x52)
  91. OP_3 = CScriptOp(0x53)
  92. OP_4 = CScriptOp(0x54)
  93. OP_5 = CScriptOp(0x55)
  94. OP_6 = CScriptOp(0x56)
  95. OP_7 = CScriptOp(0x57)
  96. OP_8 = CScriptOp(0x58)
  97. OP_9 = CScriptOp(0x59)
  98. OP_10 = CScriptOp(0x5a)
  99. OP_11 = CScriptOp(0x5b)
  100. OP_12 = CScriptOp(0x5c)
  101. OP_13 = CScriptOp(0x5d)
  102. OP_14 = CScriptOp(0x5e)
  103. OP_15 = CScriptOp(0x5f)
  104. OP_16 = CScriptOp(0x60)
  105. # control
  106. OP_NOP = CScriptOp(0x61)
  107. OP_VER = CScriptOp(0x62)
  108. OP_IF = CScriptOp(0x63)
  109. OP_NOTIF = CScriptOp(0x64)
  110. OP_VERIF = CScriptOp(0x65)
  111. OP_VERNOTIF = CScriptOp(0x66)
  112. OP_ELSE = CScriptOp(0x67)
  113. OP_ENDIF = CScriptOp(0x68)
  114. OP_VERIFY = CScriptOp(0x69)
  115. OP_RETURN = CScriptOp(0x6a)
  116. # stack ops
  117. OP_TOALTSTACK = CScriptOp(0x6b)
  118. OP_FROMALTSTACK = CScriptOp(0x6c)
  119. OP_2DROP = CScriptOp(0x6d)
  120. OP_2DUP = CScriptOp(0x6e)
  121. OP_3DUP = CScriptOp(0x6f)
  122. OP_2OVER = CScriptOp(0x70)
  123. OP_2ROT = CScriptOp(0x71)
  124. OP_2SWAP = CScriptOp(0x72)
  125. OP_IFDUP = CScriptOp(0x73)
  126. OP_DEPTH = CScriptOp(0x74)
  127. OP_DROP = CScriptOp(0x75)
  128. OP_DUP = CScriptOp(0x76)
  129. OP_NIP = CScriptOp(0x77)
  130. OP_OVER = CScriptOp(0x78)
  131. OP_PICK = CScriptOp(0x79)
  132. OP_ROLL = CScriptOp(0x7a)
  133. OP_ROT = CScriptOp(0x7b)
  134. OP_SWAP = CScriptOp(0x7c)
  135. OP_TUCK = CScriptOp(0x7d)
  136. # splice ops
  137. OP_CAT = CScriptOp(0x7e)
  138. OP_SUBSTR = CScriptOp(0x7f)
  139. OP_LEFT = CScriptOp(0x80)
  140. OP_RIGHT = CScriptOp(0x81)
  141. OP_SIZE = CScriptOp(0x82)
  142. # bit logic
  143. OP_INVERT = CScriptOp(0x83)
  144. OP_AND = CScriptOp(0x84)
  145. OP_OR = CScriptOp(0x85)
  146. OP_XOR = CScriptOp(0x86)
  147. OP_EQUAL = CScriptOp(0x87)
  148. OP_EQUALVERIFY = CScriptOp(0x88)
  149. OP_RESERVED1 = CScriptOp(0x89)
  150. OP_RESERVED2 = CScriptOp(0x8a)
  151. # numeric
  152. OP_1ADD = CScriptOp(0x8b)
  153. OP_1SUB = CScriptOp(0x8c)
  154. OP_2MUL = CScriptOp(0x8d)
  155. OP_2DIV = CScriptOp(0x8e)
  156. OP_NEGATE = CScriptOp(0x8f)
  157. OP_ABS = CScriptOp(0x90)
  158. OP_NOT = CScriptOp(0x91)
  159. OP_0NOTEQUAL = CScriptOp(0x92)
  160. OP_ADD = CScriptOp(0x93)
  161. OP_SUB = CScriptOp(0x94)
  162. OP_MUL = CScriptOp(0x95)
  163. OP_DIV = CScriptOp(0x96)
  164. OP_MOD = CScriptOp(0x97)
  165. OP_LSHIFT = CScriptOp(0x98)
  166. OP_RSHIFT = CScriptOp(0x99)
  167. OP_BOOLAND = CScriptOp(0x9a)
  168. OP_BOOLOR = CScriptOp(0x9b)
  169. OP_NUMEQUAL = CScriptOp(0x9c)
  170. OP_NUMEQUALVERIFY = CScriptOp(0x9d)
  171. OP_NUMNOTEQUAL = CScriptOp(0x9e)
  172. OP_LESSTHAN = CScriptOp(0x9f)
  173. OP_GREATERTHAN = CScriptOp(0xa0)
  174. OP_LESSTHANOREQUAL = CScriptOp(0xa1)
  175. OP_GREATERTHANOREQUAL = CScriptOp(0xa2)
  176. OP_MIN = CScriptOp(0xa3)
  177. OP_MAX = CScriptOp(0xa4)
  178. OP_WITHIN = CScriptOp(0xa5)
  179. # crypto
  180. OP_RIPEMD160 = CScriptOp(0xa6)
  181. OP_SHA1 = CScriptOp(0xa7)
  182. OP_SHA256 = CScriptOp(0xa8)
  183. OP_HASH160 = CScriptOp(0xa9)
  184. OP_HASH256 = CScriptOp(0xaa)
  185. OP_CODESEPARATOR = CScriptOp(0xab)
  186. OP_CHECKSIG = CScriptOp(0xac)
  187. OP_CHECKSIGVERIFY = CScriptOp(0xad)
  188. OP_CHECKMULTISIG = CScriptOp(0xae)
  189. OP_CHECKMULTISIGVERIFY = CScriptOp(0xaf)
  190. # expansion
  191. OP_NOP1 = CScriptOp(0xb0)
  192. OP_CHECKLOCKTIMEVERIFY = CScriptOp(0xb1)
  193. OP_CHECKSEQUENCEVERIFY = CScriptOp(0xb2)
  194. OP_NOP4 = CScriptOp(0xb3)
  195. OP_NOP5 = CScriptOp(0xb4)
  196. OP_NOP6 = CScriptOp(0xb5)
  197. OP_NOP7 = CScriptOp(0xb6)
  198. OP_NOP8 = CScriptOp(0xb7)
  199. OP_NOP9 = CScriptOp(0xb8)
  200. OP_NOP10 = CScriptOp(0xb9)
  201. # template matching params
  202. OP_SMALLINTEGER = CScriptOp(0xfa)
  203. OP_PUBKEYS = CScriptOp(0xfb)
  204. OP_PUBKEYHASH = CScriptOp(0xfd)
  205. OP_PUBKEY = CScriptOp(0xfe)
  206. OP_INVALIDOPCODE = CScriptOp(0xff)
  207. OPCODE_NAMES.update({
  208. OP_0 : 'OP_0',
  209. OP_PUSHDATA1 : 'OP_PUSHDATA1',
  210. OP_PUSHDATA2 : 'OP_PUSHDATA2',
  211. OP_PUSHDATA4 : 'OP_PUSHDATA4',
  212. OP_1NEGATE : 'OP_1NEGATE',
  213. OP_RESERVED : 'OP_RESERVED',
  214. OP_1 : 'OP_1',
  215. OP_2 : 'OP_2',
  216. OP_3 : 'OP_3',
  217. OP_4 : 'OP_4',
  218. OP_5 : 'OP_5',
  219. OP_6 : 'OP_6',
  220. OP_7 : 'OP_7',
  221. OP_8 : 'OP_8',
  222. OP_9 : 'OP_9',
  223. OP_10 : 'OP_10',
  224. OP_11 : 'OP_11',
  225. OP_12 : 'OP_12',
  226. OP_13 : 'OP_13',
  227. OP_14 : 'OP_14',
  228. OP_15 : 'OP_15',
  229. OP_16 : 'OP_16',
  230. OP_NOP : 'OP_NOP',
  231. OP_VER : 'OP_VER',
  232. OP_IF : 'OP_IF',
  233. OP_NOTIF : 'OP_NOTIF',
  234. OP_VERIF : 'OP_VERIF',
  235. OP_VERNOTIF : 'OP_VERNOTIF',
  236. OP_ELSE : 'OP_ELSE',
  237. OP_ENDIF : 'OP_ENDIF',
  238. OP_VERIFY : 'OP_VERIFY',
  239. OP_RETURN : 'OP_RETURN',
  240. OP_TOALTSTACK : 'OP_TOALTSTACK',
  241. OP_FROMALTSTACK : 'OP_FROMALTSTACK',
  242. OP_2DROP : 'OP_2DROP',
  243. OP_2DUP : 'OP_2DUP',
  244. OP_3DUP : 'OP_3DUP',
  245. OP_2OVER : 'OP_2OVER',
  246. OP_2ROT : 'OP_2ROT',
  247. OP_2SWAP : 'OP_2SWAP',
  248. OP_IFDUP : 'OP_IFDUP',
  249. OP_DEPTH : 'OP_DEPTH',
  250. OP_DROP : 'OP_DROP',
  251. OP_DUP : 'OP_DUP',
  252. OP_NIP : 'OP_NIP',
  253. OP_OVER : 'OP_OVER',
  254. OP_PICK : 'OP_PICK',
  255. OP_ROLL : 'OP_ROLL',
  256. OP_ROT : 'OP_ROT',
  257. OP_SWAP : 'OP_SWAP',
  258. OP_TUCK : 'OP_TUCK',
  259. OP_CAT : 'OP_CAT',
  260. OP_SUBSTR : 'OP_SUBSTR',
  261. OP_LEFT : 'OP_LEFT',
  262. OP_RIGHT : 'OP_RIGHT',
  263. OP_SIZE : 'OP_SIZE',
  264. OP_INVERT : 'OP_INVERT',
  265. OP_AND : 'OP_AND',
  266. OP_OR : 'OP_OR',
  267. OP_XOR : 'OP_XOR',
  268. OP_EQUAL : 'OP_EQUAL',
  269. OP_EQUALVERIFY : 'OP_EQUALVERIFY',
  270. OP_RESERVED1 : 'OP_RESERVED1',
  271. OP_RESERVED2 : 'OP_RESERVED2',
  272. OP_1ADD : 'OP_1ADD',
  273. OP_1SUB : 'OP_1SUB',
  274. OP_2MUL : 'OP_2MUL',
  275. OP_2DIV : 'OP_2DIV',
  276. OP_NEGATE : 'OP_NEGATE',
  277. OP_ABS : 'OP_ABS',
  278. OP_NOT : 'OP_NOT',
  279. OP_0NOTEQUAL : 'OP_0NOTEQUAL',
  280. OP_ADD : 'OP_ADD',
  281. OP_SUB : 'OP_SUB',
  282. OP_MUL : 'OP_MUL',
  283. OP_DIV : 'OP_DIV',
  284. OP_MOD : 'OP_MOD',
  285. OP_LSHIFT : 'OP_LSHIFT',
  286. OP_RSHIFT : 'OP_RSHIFT',
  287. OP_BOOLAND : 'OP_BOOLAND',
  288. OP_BOOLOR : 'OP_BOOLOR',
  289. OP_NUMEQUAL : 'OP_NUMEQUAL',
  290. OP_NUMEQUALVERIFY : 'OP_NUMEQUALVERIFY',
  291. OP_NUMNOTEQUAL : 'OP_NUMNOTEQUAL',
  292. OP_LESSTHAN : 'OP_LESSTHAN',
  293. OP_GREATERTHAN : 'OP_GREATERTHAN',
  294. OP_LESSTHANOREQUAL : 'OP_LESSTHANOREQUAL',
  295. OP_GREATERTHANOREQUAL : 'OP_GREATERTHANOREQUAL',
  296. OP_MIN : 'OP_MIN',
  297. OP_MAX : 'OP_MAX',
  298. OP_WITHIN : 'OP_WITHIN',
  299. OP_RIPEMD160 : 'OP_RIPEMD160',
  300. OP_SHA1 : 'OP_SHA1',
  301. OP_SHA256 : 'OP_SHA256',
  302. OP_HASH160 : 'OP_HASH160',
  303. OP_HASH256 : 'OP_HASH256',
  304. OP_CODESEPARATOR : 'OP_CODESEPARATOR',
  305. OP_CHECKSIG : 'OP_CHECKSIG',
  306. OP_CHECKSIGVERIFY : 'OP_CHECKSIGVERIFY',
  307. OP_CHECKMULTISIG : 'OP_CHECKMULTISIG',
  308. OP_CHECKMULTISIGVERIFY : 'OP_CHECKMULTISIGVERIFY',
  309. OP_NOP1 : 'OP_NOP1',
  310. OP_CHECKLOCKTIMEVERIFY : 'OP_CHECKLOCKTIMEVERIFY',
  311. OP_CHECKSEQUENCEVERIFY : 'OP_CHECKSEQUENCEVERIFY',
  312. OP_NOP4 : 'OP_NOP4',
  313. OP_NOP5 : 'OP_NOP5',
  314. OP_NOP6 : 'OP_NOP6',
  315. OP_NOP7 : 'OP_NOP7',
  316. OP_NOP8 : 'OP_NOP8',
  317. OP_NOP9 : 'OP_NOP9',
  318. OP_NOP10 : 'OP_NOP10',
  319. OP_SMALLINTEGER : 'OP_SMALLINTEGER',
  320. OP_PUBKEYS : 'OP_PUBKEYS',
  321. OP_PUBKEYHASH : 'OP_PUBKEYHASH',
  322. OP_PUBKEY : 'OP_PUBKEY',
  323. OP_INVALIDOPCODE : 'OP_INVALIDOPCODE',
  324. })
  325. class CScriptInvalidError(Exception):
  326. """Base class for CScript exceptions"""
  327. pass
  328. class CScriptTruncatedPushDataError(CScriptInvalidError):
  329. """Invalid pushdata due to truncation"""
  330. def __init__(self, msg, data):
  331. self.data = data
  332. super(CScriptTruncatedPushDataError, self).__init__(msg)
  333. # This is used, eg, for blockchain heights in coinbase scripts (bip34)
  334. class CScriptNum():
  335. def __init__(self, d=0):
  336. self.value = d
  337. @staticmethod
  338. def encode(obj):
  339. r = bytearray(0)
  340. if obj.value == 0:
  341. return bytes(r)
  342. neg = obj.value < 0
  343. absvalue = -obj.value if neg else obj.value
  344. while (absvalue):
  345. r.append(absvalue & 0xff)
  346. absvalue >>= 8
  347. if r[-1] & 0x80:
  348. r.append(0x80 if neg else 0)
  349. elif neg:
  350. r[-1] |= 0x80
  351. return bytes(bchr(len(r)) + r)
  352. class CScript(bytes):
  353. """Serialized script
  354. A bytes subclass, so you can use this directly whenever bytes are accepted.
  355. Note that this means that indexing does *not* work - you'll get an index by
  356. byte rather than opcode. This format was chosen for efficiency so that the
  357. general case would not require creating a lot of little CScriptOP objects.
  358. iter(script) however does iterate by opcode.
  359. """
  360. @classmethod
  361. def __coerce_instance(cls, other):
  362. # Coerce other into bytes
  363. if isinstance(other, CScriptOp):
  364. other = bchr(other)
  365. elif isinstance(other, CScriptNum):
  366. if (other.value == 0):
  367. other = bchr(CScriptOp(OP_0))
  368. else:
  369. other = CScriptNum.encode(other)
  370. elif isinstance(other, int):
  371. if 0 <= other <= 16:
  372. other = bytes(bchr(CScriptOp.encode_op_n(other)))
  373. elif other == -1:
  374. other = bytes(bchr(OP_1NEGATE))
  375. else:
  376. other = CScriptOp.encode_op_pushdata(bn2vch(other))
  377. elif isinstance(other, (bytes, bytearray)):
  378. other = CScriptOp.encode_op_pushdata(other)
  379. return other
  380. def __add__(self, other):
  381. # Do the coercion outside of the try block so that errors in it are
  382. # noticed.
  383. other = self.__coerce_instance(other)
  384. try:
  385. # bytes.__add__ always returns bytes instances unfortunately
  386. return CScript(super(CScript, self).__add__(other))
  387. except TypeError:
  388. raise TypeError('Can not add a %r instance to a CScript' % other.__class__)
  389. def join(self, iterable):
  390. # join makes no sense for a CScript()
  391. raise NotImplementedError
  392. def __new__(cls, value=b''):
  393. if isinstance(value, bytes) or isinstance(value, bytearray):
  394. return super(CScript, cls).__new__(cls, value)
  395. else:
  396. def coerce_iterable(iterable):
  397. for instance in iterable:
  398. yield cls.__coerce_instance(instance)
  399. # Annoyingly on both python2 and python3 bytes.join() always
  400. # returns a bytes instance even when subclassed.
  401. return super(CScript, cls).__new__(cls, b''.join(coerce_iterable(value)))
  402. def raw_iter(self):
  403. """Raw iteration
  404. Yields tuples of (opcode, data, sop_idx) so that the different possible
  405. PUSHDATA encodings can be accurately distinguished, as well as
  406. determining the exact opcode byte indexes. (sop_idx)
  407. """
  408. i = 0
  409. while i < len(self):
  410. sop_idx = i
  411. opcode = bord(self[i])
  412. i += 1
  413. if opcode > OP_PUSHDATA4:
  414. yield (opcode, None, sop_idx)
  415. else:
  416. datasize = None
  417. pushdata_type = None
  418. if opcode < OP_PUSHDATA1:
  419. pushdata_type = 'PUSHDATA(%d)' % opcode
  420. datasize = opcode
  421. elif opcode == OP_PUSHDATA1:
  422. pushdata_type = 'PUSHDATA1'
  423. if i >= len(self):
  424. raise CScriptInvalidError('PUSHDATA1: missing data length')
  425. datasize = bord(self[i])
  426. i += 1
  427. elif opcode == OP_PUSHDATA2:
  428. pushdata_type = 'PUSHDATA2'
  429. if i + 1 >= len(self):
  430. raise CScriptInvalidError('PUSHDATA2: missing data length')
  431. datasize = bord(self[i]) + (bord(self[i+1]) << 8)
  432. i += 2
  433. elif opcode == OP_PUSHDATA4:
  434. pushdata_type = 'PUSHDATA4'
  435. if i + 3 >= len(self):
  436. raise CScriptInvalidError('PUSHDATA4: missing data length')
  437. datasize = bord(self[i]) + (bord(self[i+1]) << 8) + (bord(self[i+2]) << 16) + (bord(self[i+3]) << 24)
  438. i += 4
  439. else:
  440. assert False # shouldn't happen
  441. data = bytes(self[i:i+datasize])
  442. # Check for truncation
  443. if len(data) < datasize:
  444. raise CScriptTruncatedPushDataError('%s: truncated data' % pushdata_type, data)
  445. i += datasize
  446. yield (opcode, data, sop_idx)
  447. def __iter__(self):
  448. """'Cooked' iteration
  449. Returns either a CScriptOP instance, an integer, or bytes, as
  450. appropriate.
  451. See raw_iter() if you need to distinguish the different possible
  452. PUSHDATA encodings.
  453. """
  454. for (opcode, data, sop_idx) in self.raw_iter():
  455. if data is not None:
  456. yield data
  457. else:
  458. opcode = CScriptOp(opcode)
  459. if opcode.is_small_int():
  460. yield opcode.decode_op_n()
  461. else:
  462. yield CScriptOp(opcode)
  463. def __repr__(self):
  464. def _repr(o):
  465. if isinstance(o, bytes):
  466. return "x('%s')" % hexlify(o).decode('ascii')
  467. else:
  468. return repr(o)
  469. ops = []
  470. i = iter(self)
  471. while True:
  472. op = None
  473. try:
  474. op = _repr(next(i))
  475. except CScriptTruncatedPushDataError as err:
  476. op = '%s...<ERROR: %s>' % (_repr(err.data), err)
  477. break
  478. except CScriptInvalidError as err:
  479. op = '<ERROR: %s>' % err
  480. break
  481. except StopIteration:
  482. break
  483. finally:
  484. if op is not None:
  485. ops.append(op)
  486. return "CScript([%s])" % ', '.join(ops)
  487. def GetSigOpCount(self, fAccurate):
  488. """Get the SigOp count.
  489. fAccurate - Accurately count CHECKMULTISIG, see BIP16 for details.
  490. Note that this is consensus-critical.
  491. """
  492. n = 0
  493. lastOpcode = OP_INVALIDOPCODE
  494. for (opcode, data, sop_idx) in self.raw_iter():
  495. if opcode in (OP_CHECKSIG, OP_CHECKSIGVERIFY):
  496. n += 1
  497. elif opcode in (OP_CHECKMULTISIG, OP_CHECKMULTISIGVERIFY):
  498. if fAccurate and (OP_1 <= lastOpcode <= OP_16):
  499. n += opcode.decode_op_n()
  500. else:
  501. n += 20
  502. lastOpcode = opcode
  503. return n
  504. SIGHASH_ALL = 1
  505. SIGHASH_NONE = 2
  506. SIGHASH_SINGLE = 3
  507. SIGHASH_ANYONECANPAY = 0x80
  508. def FindAndDelete(script, sig):
  509. """Consensus critical, see FindAndDelete() in Satoshi codebase"""
  510. r = b''
  511. last_sop_idx = sop_idx = 0
  512. skip = True
  513. for (opcode, data, sop_idx) in script.raw_iter():
  514. if not skip:
  515. r += script[last_sop_idx:sop_idx]
  516. last_sop_idx = sop_idx
  517. if script[sop_idx:sop_idx + len(sig)] == sig:
  518. skip = True
  519. else:
  520. skip = False
  521. if not skip:
  522. r += script[last_sop_idx:]
  523. return CScript(r)
  524. def SignatureHash(script, txTo, inIdx, hashtype):
  525. """Consensus-correct SignatureHash
  526. Returns (hash, err) to precisely match the consensus-critical behavior of
  527. the SIGHASH_SINGLE bug. (inIdx is *not* checked for validity)
  528. """
  529. HASH_ONE = b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
  530. if inIdx >= len(txTo.vin):
  531. return (HASH_ONE, "inIdx %d out of range (%d)" % (inIdx, len(txTo.vin)))
  532. txtmp = CTransaction(txTo)
  533. for txin in txtmp.vin:
  534. txin.scriptSig = b''
  535. txtmp.vin[inIdx].scriptSig = FindAndDelete(script, CScript([OP_CODESEPARATOR]))
  536. if (hashtype & 0x1f) == SIGHASH_NONE:
  537. txtmp.vout = []
  538. for i in range(len(txtmp.vin)):
  539. if i != inIdx:
  540. txtmp.vin[i].nSequence = 0
  541. elif (hashtype & 0x1f) == SIGHASH_SINGLE:
  542. outIdx = inIdx
  543. if outIdx >= len(txtmp.vout):
  544. return (HASH_ONE, "outIdx %d out of range (%d)" % (outIdx, len(txtmp.vout)))
  545. tmp = txtmp.vout[outIdx]
  546. txtmp.vout = []
  547. for i in range(outIdx):
  548. txtmp.vout.append(CTxOut(-1))
  549. txtmp.vout.append(tmp)
  550. for i in range(len(txtmp.vin)):
  551. if i != inIdx:
  552. txtmp.vin[i].nSequence = 0
  553. if hashtype & SIGHASH_ANYONECANPAY:
  554. tmp = txtmp.vin[inIdx]
  555. txtmp.vin = []
  556. txtmp.vin.append(tmp)
  557. s = txtmp.serialize_without_witness()
  558. s += struct.pack(b"<I", hashtype)
  559. hash = hash256(s)
  560. return (hash, None)
  561. # TODO: Allow cached hashPrevouts/hashSequence/hashOutputs to be provided.
  562. # Performance optimization probably not necessary for python tests, however.
  563. # Note that this corresponds to sigversion == 1 in EvalScript, which is used
  564. # for version 0 witnesses.
  565. def SegwitVersion1SignatureHash(script, txTo, inIdx, hashtype, amount):
  566. hashPrevouts = 0
  567. hashSequence = 0
  568. hashOutputs = 0
  569. if not (hashtype & SIGHASH_ANYONECANPAY):
  570. serialize_prevouts = bytes()
  571. for i in txTo.vin:
  572. serialize_prevouts += i.prevout.serialize()
  573. hashPrevouts = uint256_from_str(hash256(serialize_prevouts))
  574. if (not (hashtype & SIGHASH_ANYONECANPAY) and (hashtype & 0x1f) != SIGHASH_SINGLE and (hashtype & 0x1f) != SIGHASH_NONE):
  575. serialize_sequence = bytes()
  576. for i in txTo.vin:
  577. serialize_sequence += struct.pack("<I", i.nSequence)
  578. hashSequence = uint256_from_str(hash256(serialize_sequence))
  579. if ((hashtype & 0x1f) != SIGHASH_SINGLE and (hashtype & 0x1f) != SIGHASH_NONE):
  580. serialize_outputs = bytes()
  581. for o in txTo.vout:
  582. serialize_outputs += o.serialize()
  583. hashOutputs = uint256_from_str(hash256(serialize_outputs))
  584. elif ((hashtype & 0x1f) == SIGHASH_SINGLE and inIdx < len(txTo.vout)):
  585. serialize_outputs = txTo.vout[inIdx].serialize()
  586. hashOutputs = uint256_from_str(hash256(serialize_outputs))
  587. ss = bytes()
  588. ss += struct.pack("<i", txTo.nVersion)
  589. ss += ser_uint256(hashPrevouts)
  590. ss += ser_uint256(hashSequence)
  591. ss += txTo.vin[inIdx].prevout.serialize()
  592. ss += ser_string(script)
  593. ss += struct.pack("<q", amount)
  594. ss += struct.pack("<I", txTo.vin[inIdx].nSequence)
  595. ss += ser_uint256(hashOutputs)
  596. ss += struct.pack("<i", txTo.nLockTime)
  597. ss += struct.pack("<I", hashtype)
  598. return hash256(ss)