Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2015-2016 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_SIZE = 10000
  21. MAX_SCRIPT_ELEMENT_SIZE = 520
  22. MAX_SCRIPT_OPCODES = 201
  23. OPCODE_NAMES = {}
  24. def hash160(s):
  25. return hashlib.new('ripemd160', sha256(s)).digest()
  26. _opcode_instances = []
  27. class CScriptOp(int):
  28. """A single script opcode"""
  29. __slots__ = []
  30. @staticmethod
  31. def encode_op_pushdata(d):
  32. """Encode a PUSHDATA op, returning bytes"""
  33. if len(d) < 0x4c:
  34. return b'' + bchr(len(d)) + d # OP_PUSHDATA
  35. elif len(d) <= 0xff:
  36. return b'\x4c' + bchr(len(d)) + d # OP_PUSHDATA1
  37. elif len(d) <= 0xffff:
  38. return b'\x4d' + struct.pack(b'<H', len(d)) + d # OP_PUSHDATA2
  39. elif len(d) <= 0xffffffff:
  40. return b'\x4e' + struct.pack(b'<I', len(d)) + d # OP_PUSHDATA4
  41. else:
  42. raise ValueError("Data too long to encode in a PUSHDATA op")
  43. @staticmethod
  44. def encode_op_n(n):
  45. """Encode a small integer op, returning an opcode"""
  46. if not (0 <= n <= 16):
  47. raise ValueError('Integer must be in range 0 <= n <= 16, got %d' % n)
  48. if n == 0:
  49. return OP_0
  50. else:
  51. return CScriptOp(OP_1 + n-1)
  52. def decode_op_n(self):
  53. """Decode a small integer opcode, returning an integer"""
  54. if self == OP_0:
  55. return 0
  56. if not (self == OP_0 or OP_1 <= self <= OP_16):
  57. raise ValueError('op %r is not an OP_N' % self)
  58. return int(self - OP_1+1)
  59. def is_small_int(self):
  60. """Return true if the op pushes a small integer to the stack"""
  61. if 0x51 <= self <= 0x60 or self == 0:
  62. return True
  63. else:
  64. return False
  65. def __str__(self):
  66. return repr(self)
  67. def __repr__(self):
  68. if self in OPCODE_NAMES:
  69. return OPCODE_NAMES[self]
  70. else:
  71. return 'CScriptOp(0x%x)' % self
  72. def __new__(cls, n):
  73. try:
  74. return _opcode_instances[n]
  75. except IndexError:
  76. assert len(_opcode_instances) == n
  77. _opcode_instances.append(super(CScriptOp, cls).__new__(cls, n))
  78. return _opcode_instances[n]
  79. # Populate opcode instance table
  80. for n in range(0xff+1):
  81. CScriptOp(n)
  82. # push value
  83. OP_0 = CScriptOp(0x00)
  84. OP_FALSE = OP_0
  85. OP_PUSHDATA1 = CScriptOp(0x4c)
  86. OP_PUSHDATA2 = CScriptOp(0x4d)
  87. OP_PUSHDATA4 = CScriptOp(0x4e)
  88. OP_1NEGATE = CScriptOp(0x4f)
  89. OP_RESERVED = CScriptOp(0x50)
  90. OP_1 = CScriptOp(0x51)
  91. OP_TRUE=OP_1
  92. OP_2 = CScriptOp(0x52)
  93. OP_3 = CScriptOp(0x53)
  94. OP_4 = CScriptOp(0x54)
  95. OP_5 = CScriptOp(0x55)
  96. OP_6 = CScriptOp(0x56)
  97. OP_7 = CScriptOp(0x57)
  98. OP_8 = CScriptOp(0x58)
  99. OP_9 = CScriptOp(0x59)
  100. OP_10 = CScriptOp(0x5a)
  101. OP_11 = CScriptOp(0x5b)
  102. OP_12 = CScriptOp(0x5c)
  103. OP_13 = CScriptOp(0x5d)
  104. OP_14 = CScriptOp(0x5e)
  105. OP_15 = CScriptOp(0x5f)
  106. OP_16 = CScriptOp(0x60)
  107. # control
  108. OP_NOP = CScriptOp(0x61)
  109. OP_VER = CScriptOp(0x62)
  110. OP_IF = CScriptOp(0x63)
  111. OP_NOTIF = CScriptOp(0x64)
  112. OP_VERIF = CScriptOp(0x65)
  113. OP_VERNOTIF = CScriptOp(0x66)
  114. OP_ELSE = CScriptOp(0x67)
  115. OP_ENDIF = CScriptOp(0x68)
  116. OP_VERIFY = CScriptOp(0x69)
  117. OP_RETURN = CScriptOp(0x6a)
  118. # stack ops
  119. OP_TOALTSTACK = CScriptOp(0x6b)
  120. OP_FROMALTSTACK = CScriptOp(0x6c)
  121. OP_2DROP = CScriptOp(0x6d)
  122. OP_2DUP = CScriptOp(0x6e)
  123. OP_3DUP = CScriptOp(0x6f)
  124. OP_2OVER = CScriptOp(0x70)
  125. OP_2ROT = CScriptOp(0x71)
  126. OP_2SWAP = CScriptOp(0x72)
  127. OP_IFDUP = CScriptOp(0x73)
  128. OP_DEPTH = CScriptOp(0x74)
  129. OP_DROP = CScriptOp(0x75)
  130. OP_DUP = CScriptOp(0x76)
  131. OP_NIP = CScriptOp(0x77)
  132. OP_OVER = CScriptOp(0x78)
  133. OP_PICK = CScriptOp(0x79)
  134. OP_ROLL = CScriptOp(0x7a)
  135. OP_ROT = CScriptOp(0x7b)
  136. OP_SWAP = CScriptOp(0x7c)
  137. OP_TUCK = CScriptOp(0x7d)
  138. # splice ops
  139. OP_CAT = CScriptOp(0x7e)
  140. OP_SUBSTR = CScriptOp(0x7f)
  141. OP_LEFT = CScriptOp(0x80)
  142. OP_RIGHT = CScriptOp(0x81)
  143. OP_SIZE = CScriptOp(0x82)
  144. # bit logic
  145. OP_INVERT = CScriptOp(0x83)
  146. OP_AND = CScriptOp(0x84)
  147. OP_OR = CScriptOp(0x85)
  148. OP_XOR = CScriptOp(0x86)
  149. OP_EQUAL = CScriptOp(0x87)
  150. OP_EQUALVERIFY = CScriptOp(0x88)
  151. OP_RESERVED1 = CScriptOp(0x89)
  152. OP_RESERVED2 = CScriptOp(0x8a)
  153. # numeric
  154. OP_1ADD = CScriptOp(0x8b)
  155. OP_1SUB = CScriptOp(0x8c)
  156. OP_2MUL = CScriptOp(0x8d)
  157. OP_2DIV = CScriptOp(0x8e)
  158. OP_NEGATE = CScriptOp(0x8f)
  159. OP_ABS = CScriptOp(0x90)
  160. OP_NOT = CScriptOp(0x91)
  161. OP_0NOTEQUAL = CScriptOp(0x92)
  162. OP_ADD = CScriptOp(0x93)
  163. OP_SUB = CScriptOp(0x94)
  164. OP_MUL = CScriptOp(0x95)
  165. OP_DIV = CScriptOp(0x96)
  166. OP_MOD = CScriptOp(0x97)
  167. OP_LSHIFT = CScriptOp(0x98)
  168. OP_RSHIFT = CScriptOp(0x99)
  169. OP_BOOLAND = CScriptOp(0x9a)
  170. OP_BOOLOR = CScriptOp(0x9b)
  171. OP_NUMEQUAL = CScriptOp(0x9c)
  172. OP_NUMEQUALVERIFY = CScriptOp(0x9d)
  173. OP_NUMNOTEQUAL = CScriptOp(0x9e)
  174. OP_LESSTHAN = CScriptOp(0x9f)
  175. OP_GREATERTHAN = CScriptOp(0xa0)
  176. OP_LESSTHANOREQUAL = CScriptOp(0xa1)
  177. OP_GREATERTHANOREQUAL = CScriptOp(0xa2)
  178. OP_MIN = CScriptOp(0xa3)
  179. OP_MAX = CScriptOp(0xa4)
  180. OP_WITHIN = CScriptOp(0xa5)
  181. # crypto
  182. OP_RIPEMD160 = CScriptOp(0xa6)
  183. OP_SHA1 = CScriptOp(0xa7)
  184. OP_SHA256 = CScriptOp(0xa8)
  185. OP_HASH160 = CScriptOp(0xa9)
  186. OP_HASH256 = CScriptOp(0xaa)
  187. OP_CODESEPARATOR = CScriptOp(0xab)
  188. OP_CHECKSIG = CScriptOp(0xac)
  189. OP_CHECKSIGVERIFY = CScriptOp(0xad)
  190. OP_CHECKMULTISIG = CScriptOp(0xae)
  191. OP_CHECKMULTISIGVERIFY = CScriptOp(0xaf)
  192. # expansion
  193. OP_NOP1 = CScriptOp(0xb0)
  194. OP_CHECKLOCKTIMEVERIFY = CScriptOp(0xb1)
  195. OP_CHECKSEQUENCEVERIFY = CScriptOp(0xb2)
  196. OP_NOP4 = CScriptOp(0xb3)
  197. OP_NOP5 = CScriptOp(0xb4)
  198. OP_NOP6 = CScriptOp(0xb5)
  199. OP_NOP7 = CScriptOp(0xb6)
  200. OP_NOP8 = CScriptOp(0xb7)
  201. OP_NOP9 = CScriptOp(0xb8)
  202. OP_NOP10 = CScriptOp(0xb9)
  203. # template matching params
  204. OP_SMALLINTEGER = CScriptOp(0xfa)
  205. OP_PUBKEYS = CScriptOp(0xfb)
  206. OP_PUBKEYHASH = CScriptOp(0xfd)
  207. OP_PUBKEY = CScriptOp(0xfe)
  208. OP_INVALIDOPCODE = CScriptOp(0xff)
  209. VALID_OPCODES = {
  210. OP_1NEGATE,
  211. OP_RESERVED,
  212. OP_1,
  213. OP_2,
  214. OP_3,
  215. OP_4,
  216. OP_5,
  217. OP_6,
  218. OP_7,
  219. OP_8,
  220. OP_9,
  221. OP_10,
  222. OP_11,
  223. OP_12,
  224. OP_13,
  225. OP_14,
  226. OP_15,
  227. OP_16,
  228. OP_NOP,
  229. OP_VER,
  230. OP_IF,
  231. OP_NOTIF,
  232. OP_VERIF,
  233. OP_VERNOTIF,
  234. OP_ELSE,
  235. OP_ENDIF,
  236. OP_VERIFY,
  237. OP_RETURN,
  238. OP_TOALTSTACK,
  239. OP_FROMALTSTACK,
  240. OP_2DROP,
  241. OP_2DUP,
  242. OP_3DUP,
  243. OP_2OVER,
  244. OP_2ROT,
  245. OP_2SWAP,
  246. OP_IFDUP,
  247. OP_DEPTH,
  248. OP_DROP,
  249. OP_DUP,
  250. OP_NIP,
  251. OP_OVER,
  252. OP_PICK,
  253. OP_ROLL,
  254. OP_ROT,
  255. OP_SWAP,
  256. OP_TUCK,
  257. OP_CAT,
  258. OP_SUBSTR,
  259. OP_LEFT,
  260. OP_RIGHT,
  261. OP_SIZE,
  262. OP_INVERT,
  263. OP_AND,
  264. OP_OR,
  265. OP_XOR,
  266. OP_EQUAL,
  267. OP_EQUALVERIFY,
  268. OP_RESERVED1,
  269. OP_RESERVED2,
  270. OP_1ADD,
  271. OP_1SUB,
  272. OP_2MUL,
  273. OP_2DIV,
  274. OP_NEGATE,
  275. OP_ABS,
  276. OP_NOT,
  277. OP_0NOTEQUAL,
  278. OP_ADD,
  279. OP_SUB,
  280. OP_MUL,
  281. OP_DIV,
  282. OP_MOD,
  283. OP_LSHIFT,
  284. OP_RSHIFT,
  285. OP_BOOLAND,
  286. OP_BOOLOR,
  287. OP_NUMEQUAL,
  288. OP_NUMEQUALVERIFY,
  289. OP_NUMNOTEQUAL,
  290. OP_LESSTHAN,
  291. OP_GREATERTHAN,
  292. OP_LESSTHANOREQUAL,
  293. OP_GREATERTHANOREQUAL,
  294. OP_MIN,
  295. OP_MAX,
  296. OP_WITHIN,
  297. OP_RIPEMD160,
  298. OP_SHA1,
  299. OP_SHA256,
  300. OP_HASH160,
  301. OP_HASH256,
  302. OP_CODESEPARATOR,
  303. OP_CHECKSIG,
  304. OP_CHECKSIGVERIFY,
  305. OP_CHECKMULTISIG,
  306. OP_CHECKMULTISIGVERIFY,
  307. OP_NOP1,
  308. OP_CHECKLOCKTIMEVERIFY,
  309. OP_CHECKSEQUENCEVERIFY,
  310. OP_NOP4,
  311. OP_NOP5,
  312. OP_NOP6,
  313. OP_NOP7,
  314. OP_NOP8,
  315. OP_NOP9,
  316. OP_NOP10,
  317. OP_SMALLINTEGER,
  318. OP_PUBKEYS,
  319. OP_PUBKEYHASH,
  320. OP_PUBKEY,
  321. }
  322. OPCODE_NAMES.update({
  323. OP_0 : 'OP_0',
  324. OP_PUSHDATA1 : 'OP_PUSHDATA1',
  325. OP_PUSHDATA2 : 'OP_PUSHDATA2',
  326. OP_PUSHDATA4 : 'OP_PUSHDATA4',
  327. OP_1NEGATE : 'OP_1NEGATE',
  328. OP_RESERVED : 'OP_RESERVED',
  329. OP_1 : 'OP_1',
  330. OP_2 : 'OP_2',
  331. OP_3 : 'OP_3',
  332. OP_4 : 'OP_4',
  333. OP_5 : 'OP_5',
  334. OP_6 : 'OP_6',
  335. OP_7 : 'OP_7',
  336. OP_8 : 'OP_8',
  337. OP_9 : 'OP_9',
  338. OP_10 : 'OP_10',
  339. OP_11 : 'OP_11',
  340. OP_12 : 'OP_12',
  341. OP_13 : 'OP_13',
  342. OP_14 : 'OP_14',
  343. OP_15 : 'OP_15',
  344. OP_16 : 'OP_16',
  345. OP_NOP : 'OP_NOP',
  346. OP_VER : 'OP_VER',
  347. OP_IF : 'OP_IF',
  348. OP_NOTIF : 'OP_NOTIF',
  349. OP_VERIF : 'OP_VERIF',
  350. OP_VERNOTIF : 'OP_VERNOTIF',
  351. OP_ELSE : 'OP_ELSE',
  352. OP_ENDIF : 'OP_ENDIF',
  353. OP_VERIFY : 'OP_VERIFY',
  354. OP_RETURN : 'OP_RETURN',
  355. OP_TOALTSTACK : 'OP_TOALTSTACK',
  356. OP_FROMALTSTACK : 'OP_FROMALTSTACK',
  357. OP_2DROP : 'OP_2DROP',
  358. OP_2DUP : 'OP_2DUP',
  359. OP_3DUP : 'OP_3DUP',
  360. OP_2OVER : 'OP_2OVER',
  361. OP_2ROT : 'OP_2ROT',
  362. OP_2SWAP : 'OP_2SWAP',
  363. OP_IFDUP : 'OP_IFDUP',
  364. OP_DEPTH : 'OP_DEPTH',
  365. OP_DROP : 'OP_DROP',
  366. OP_DUP : 'OP_DUP',
  367. OP_NIP : 'OP_NIP',
  368. OP_OVER : 'OP_OVER',
  369. OP_PICK : 'OP_PICK',
  370. OP_ROLL : 'OP_ROLL',
  371. OP_ROT : 'OP_ROT',
  372. OP_SWAP : 'OP_SWAP',
  373. OP_TUCK : 'OP_TUCK',
  374. OP_CAT : 'OP_CAT',
  375. OP_SUBSTR : 'OP_SUBSTR',
  376. OP_LEFT : 'OP_LEFT',
  377. OP_RIGHT : 'OP_RIGHT',
  378. OP_SIZE : 'OP_SIZE',
  379. OP_INVERT : 'OP_INVERT',
  380. OP_AND : 'OP_AND',
  381. OP_OR : 'OP_OR',
  382. OP_XOR : 'OP_XOR',
  383. OP_EQUAL : 'OP_EQUAL',
  384. OP_EQUALVERIFY : 'OP_EQUALVERIFY',
  385. OP_RESERVED1 : 'OP_RESERVED1',
  386. OP_RESERVED2 : 'OP_RESERVED2',
  387. OP_1ADD : 'OP_1ADD',
  388. OP_1SUB : 'OP_1SUB',
  389. OP_2MUL : 'OP_2MUL',
  390. OP_2DIV : 'OP_2DIV',
  391. OP_NEGATE : 'OP_NEGATE',
  392. OP_ABS : 'OP_ABS',
  393. OP_NOT : 'OP_NOT',
  394. OP_0NOTEQUAL : 'OP_0NOTEQUAL',
  395. OP_ADD : 'OP_ADD',
  396. OP_SUB : 'OP_SUB',
  397. OP_MUL : 'OP_MUL',
  398. OP_DIV : 'OP_DIV',
  399. OP_MOD : 'OP_MOD',
  400. OP_LSHIFT : 'OP_LSHIFT',
  401. OP_RSHIFT : 'OP_RSHIFT',
  402. OP_BOOLAND : 'OP_BOOLAND',
  403. OP_BOOLOR : 'OP_BOOLOR',
  404. OP_NUMEQUAL : 'OP_NUMEQUAL',
  405. OP_NUMEQUALVERIFY : 'OP_NUMEQUALVERIFY',
  406. OP_NUMNOTEQUAL : 'OP_NUMNOTEQUAL',
  407. OP_LESSTHAN : 'OP_LESSTHAN',
  408. OP_GREATERTHAN : 'OP_GREATERTHAN',
  409. OP_LESSTHANOREQUAL : 'OP_LESSTHANOREQUAL',
  410. OP_GREATERTHANOREQUAL : 'OP_GREATERTHANOREQUAL',
  411. OP_MIN : 'OP_MIN',
  412. OP_MAX : 'OP_MAX',
  413. OP_WITHIN : 'OP_WITHIN',
  414. OP_RIPEMD160 : 'OP_RIPEMD160',
  415. OP_SHA1 : 'OP_SHA1',
  416. OP_SHA256 : 'OP_SHA256',
  417. OP_HASH160 : 'OP_HASH160',
  418. OP_HASH256 : 'OP_HASH256',
  419. OP_CODESEPARATOR : 'OP_CODESEPARATOR',
  420. OP_CHECKSIG : 'OP_CHECKSIG',
  421. OP_CHECKSIGVERIFY : 'OP_CHECKSIGVERIFY',
  422. OP_CHECKMULTISIG : 'OP_CHECKMULTISIG',
  423. OP_CHECKMULTISIGVERIFY : 'OP_CHECKMULTISIGVERIFY',
  424. OP_NOP1 : 'OP_NOP1',
  425. OP_CHECKLOCKTIMEVERIFY : 'OP_CHECKLOCKTIMEVERIFY',
  426. OP_CHECKSEQUENCEVERIFY : 'OP_CHECKSEQUENCEVERIFY',
  427. OP_NOP4 : 'OP_NOP4',
  428. OP_NOP5 : 'OP_NOP5',
  429. OP_NOP6 : 'OP_NOP6',
  430. OP_NOP7 : 'OP_NOP7',
  431. OP_NOP8 : 'OP_NOP8',
  432. OP_NOP9 : 'OP_NOP9',
  433. OP_NOP10 : 'OP_NOP10',
  434. OP_SMALLINTEGER : 'OP_SMALLINTEGER',
  435. OP_PUBKEYS : 'OP_PUBKEYS',
  436. OP_PUBKEYHASH : 'OP_PUBKEYHASH',
  437. OP_PUBKEY : 'OP_PUBKEY',
  438. OP_INVALIDOPCODE : 'OP_INVALIDOPCODE',
  439. })
  440. OPCODES_BY_NAME = {
  441. 'OP_0' : OP_0,
  442. 'OP_PUSHDATA1' : OP_PUSHDATA1,
  443. 'OP_PUSHDATA2' : OP_PUSHDATA2,
  444. 'OP_PUSHDATA4' : OP_PUSHDATA4,
  445. 'OP_1NEGATE' : OP_1NEGATE,
  446. 'OP_RESERVED' : OP_RESERVED,
  447. 'OP_1' : OP_1,
  448. 'OP_2' : OP_2,
  449. 'OP_3' : OP_3,
  450. 'OP_4' : OP_4,
  451. 'OP_5' : OP_5,
  452. 'OP_6' : OP_6,
  453. 'OP_7' : OP_7,
  454. 'OP_8' : OP_8,
  455. 'OP_9' : OP_9,
  456. 'OP_10' : OP_10,
  457. 'OP_11' : OP_11,
  458. 'OP_12' : OP_12,
  459. 'OP_13' : OP_13,
  460. 'OP_14' : OP_14,
  461. 'OP_15' : OP_15,
  462. 'OP_16' : OP_16,
  463. 'OP_NOP' : OP_NOP,
  464. 'OP_VER' : OP_VER,
  465. 'OP_IF' : OP_IF,
  466. 'OP_NOTIF' : OP_NOTIF,
  467. 'OP_VERIF' : OP_VERIF,
  468. 'OP_VERNOTIF' : OP_VERNOTIF,
  469. 'OP_ELSE' : OP_ELSE,
  470. 'OP_ENDIF' : OP_ENDIF,
  471. 'OP_VERIFY' : OP_VERIFY,
  472. 'OP_RETURN' : OP_RETURN,
  473. 'OP_TOALTSTACK' : OP_TOALTSTACK,
  474. 'OP_FROMALTSTACK' : OP_FROMALTSTACK,
  475. 'OP_2DROP' : OP_2DROP,
  476. 'OP_2DUP' : OP_2DUP,
  477. 'OP_3DUP' : OP_3DUP,
  478. 'OP_2OVER' : OP_2OVER,
  479. 'OP_2ROT' : OP_2ROT,
  480. 'OP_2SWAP' : OP_2SWAP,
  481. 'OP_IFDUP' : OP_IFDUP,
  482. 'OP_DEPTH' : OP_DEPTH,
  483. 'OP_DROP' : OP_DROP,
  484. 'OP_DUP' : OP_DUP,
  485. 'OP_NIP' : OP_NIP,
  486. 'OP_OVER' : OP_OVER,
  487. 'OP_PICK' : OP_PICK,
  488. 'OP_ROLL' : OP_ROLL,
  489. 'OP_ROT' : OP_ROT,
  490. 'OP_SWAP' : OP_SWAP,
  491. 'OP_TUCK' : OP_TUCK,
  492. 'OP_CAT' : OP_CAT,
  493. 'OP_SUBSTR' : OP_SUBSTR,
  494. 'OP_LEFT' : OP_LEFT,
  495. 'OP_RIGHT' : OP_RIGHT,
  496. 'OP_SIZE' : OP_SIZE,
  497. 'OP_INVERT' : OP_INVERT,
  498. 'OP_AND' : OP_AND,
  499. 'OP_OR' : OP_OR,
  500. 'OP_XOR' : OP_XOR,
  501. 'OP_EQUAL' : OP_EQUAL,
  502. 'OP_EQUALVERIFY' : OP_EQUALVERIFY,
  503. 'OP_RESERVED1' : OP_RESERVED1,
  504. 'OP_RESERVED2' : OP_RESERVED2,
  505. 'OP_1ADD' : OP_1ADD,
  506. 'OP_1SUB' : OP_1SUB,
  507. 'OP_2MUL' : OP_2MUL,
  508. 'OP_2DIV' : OP_2DIV,
  509. 'OP_NEGATE' : OP_NEGATE,
  510. 'OP_ABS' : OP_ABS,
  511. 'OP_NOT' : OP_NOT,
  512. 'OP_0NOTEQUAL' : OP_0NOTEQUAL,
  513. 'OP_ADD' : OP_ADD,
  514. 'OP_SUB' : OP_SUB,
  515. 'OP_MUL' : OP_MUL,
  516. 'OP_DIV' : OP_DIV,
  517. 'OP_MOD' : OP_MOD,
  518. 'OP_LSHIFT' : OP_LSHIFT,
  519. 'OP_RSHIFT' : OP_RSHIFT,
  520. 'OP_BOOLAND' : OP_BOOLAND,
  521. 'OP_BOOLOR' : OP_BOOLOR,
  522. 'OP_NUMEQUAL' : OP_NUMEQUAL,
  523. 'OP_NUMEQUALVERIFY' : OP_NUMEQUALVERIFY,
  524. 'OP_NUMNOTEQUAL' : OP_NUMNOTEQUAL,
  525. 'OP_LESSTHAN' : OP_LESSTHAN,
  526. 'OP_GREATERTHAN' : OP_GREATERTHAN,
  527. 'OP_LESSTHANOREQUAL' : OP_LESSTHANOREQUAL,
  528. 'OP_GREATERTHANOREQUAL' : OP_GREATERTHANOREQUAL,
  529. 'OP_MIN' : OP_MIN,
  530. 'OP_MAX' : OP_MAX,
  531. 'OP_WITHIN' : OP_WITHIN,
  532. 'OP_RIPEMD160' : OP_RIPEMD160,
  533. 'OP_SHA1' : OP_SHA1,
  534. 'OP_SHA256' : OP_SHA256,
  535. 'OP_HASH160' : OP_HASH160,
  536. 'OP_HASH256' : OP_HASH256,
  537. 'OP_CODESEPARATOR' : OP_CODESEPARATOR,
  538. 'OP_CHECKSIG' : OP_CHECKSIG,
  539. 'OP_CHECKSIGVERIFY' : OP_CHECKSIGVERIFY,
  540. 'OP_CHECKMULTISIG' : OP_CHECKMULTISIG,
  541. 'OP_CHECKMULTISIGVERIFY' : OP_CHECKMULTISIGVERIFY,
  542. 'OP_NOP1' : OP_NOP1,
  543. 'OP_CHECKLOCKTIMEVERIFY' : OP_CHECKLOCKTIMEVERIFY,
  544. 'OP_CHECKSEQUENCEVERIFY' : OP_CHECKSEQUENCEVERIFY,
  545. 'OP_NOP4' : OP_NOP4,
  546. 'OP_NOP5' : OP_NOP5,
  547. 'OP_NOP6' : OP_NOP6,
  548. 'OP_NOP7' : OP_NOP7,
  549. 'OP_NOP8' : OP_NOP8,
  550. 'OP_NOP9' : OP_NOP9,
  551. 'OP_NOP10' : OP_NOP10,
  552. 'OP_SMALLINTEGER' : OP_SMALLINTEGER,
  553. 'OP_PUBKEYS' : OP_PUBKEYS,
  554. 'OP_PUBKEYHASH' : OP_PUBKEYHASH,
  555. 'OP_PUBKEY' : OP_PUBKEY,
  556. }
  557. class CScriptInvalidError(Exception):
  558. """Base class for CScript exceptions"""
  559. pass
  560. class CScriptTruncatedPushDataError(CScriptInvalidError):
  561. """Invalid pushdata due to truncation"""
  562. def __init__(self, msg, data):
  563. self.data = data
  564. super(CScriptTruncatedPushDataError, self).__init__(msg)
  565. # This is used, eg, for blockchain heights in coinbase scripts (bip34)
  566. class CScriptNum(object):
  567. def __init__(self, d=0):
  568. self.value = d
  569. @staticmethod
  570. def encode(obj):
  571. r = bytearray(0)
  572. if obj.value == 0:
  573. return bytes(r)
  574. neg = obj.value < 0
  575. absvalue = -obj.value if neg else obj.value
  576. while (absvalue):
  577. r.append(absvalue & 0xff)
  578. absvalue >>= 8
  579. if r[-1] & 0x80:
  580. r.append(0x80 if neg else 0)
  581. elif neg:
  582. r[-1] |= 0x80
  583. return bytes(bchr(len(r)) + r)
  584. class CScript(bytes):
  585. """Serialized script
  586. A bytes subclass, so you can use this directly whenever bytes are accepted.
  587. Note that this means that indexing does *not* work - you'll get an index by
  588. byte rather than opcode. This format was chosen for efficiency so that the
  589. general case would not require creating a lot of little CScriptOP objects.
  590. iter(script) however does iterate by opcode.
  591. """
  592. @classmethod
  593. def __coerce_instance(cls, other):
  594. # Coerce other into bytes
  595. if isinstance(other, CScriptOp):
  596. other = bchr(other)
  597. elif isinstance(other, CScriptNum):
  598. if (other.value == 0):
  599. other = bchr(CScriptOp(OP_0))
  600. else:
  601. other = CScriptNum.encode(other)
  602. elif isinstance(other, int):
  603. if 0 <= other <= 16:
  604. other = bytes(bchr(CScriptOp.encode_op_n(other)))
  605. elif other == -1:
  606. other = bytes(bchr(OP_1NEGATE))
  607. else:
  608. other = CScriptOp.encode_op_pushdata(bn2vch(other))
  609. elif isinstance(other, (bytes, bytearray)):
  610. other = CScriptOp.encode_op_pushdata(other)
  611. return other
  612. def __add__(self, other):
  613. # Do the coercion outside of the try block so that errors in it are
  614. # noticed.
  615. other = self.__coerce_instance(other)
  616. try:
  617. # bytes.__add__ always returns bytes instances unfortunately
  618. return CScript(super(CScript, self).__add__(other))
  619. except TypeError:
  620. raise TypeError('Can not add a %r instance to a CScript' % other.__class__)
  621. def join(self, iterable):
  622. # join makes no sense for a CScript()
  623. raise NotImplementedError
  624. def __new__(cls, value=b''):
  625. if isinstance(value, bytes) or isinstance(value, bytearray):
  626. return super(CScript, cls).__new__(cls, value)
  627. else:
  628. def coerce_iterable(iterable):
  629. for instance in iterable:
  630. yield cls.__coerce_instance(instance)
  631. # Annoyingly on both python2 and python3 bytes.join() always
  632. # returns a bytes instance even when subclassed.
  633. return super(CScript, cls).__new__(cls, b''.join(coerce_iterable(value)))
  634. def raw_iter(self):
  635. """Raw iteration
  636. Yields tuples of (opcode, data, sop_idx) so that the different possible
  637. PUSHDATA encodings can be accurately distinguished, as well as
  638. determining the exact opcode byte indexes. (sop_idx)
  639. """
  640. i = 0
  641. while i < len(self):
  642. sop_idx = i
  643. opcode = bord(self[i])
  644. i += 1
  645. if opcode > OP_PUSHDATA4:
  646. yield (opcode, None, sop_idx)
  647. else:
  648. datasize = None
  649. pushdata_type = None
  650. if opcode < OP_PUSHDATA1:
  651. pushdata_type = 'PUSHDATA(%d)' % opcode
  652. datasize = opcode
  653. elif opcode == OP_PUSHDATA1:
  654. pushdata_type = 'PUSHDATA1'
  655. if i >= len(self):
  656. raise CScriptInvalidError('PUSHDATA1: missing data length')
  657. datasize = bord(self[i])
  658. i += 1
  659. elif opcode == OP_PUSHDATA2:
  660. pushdata_type = 'PUSHDATA2'
  661. if i + 1 >= len(self):
  662. raise CScriptInvalidError('PUSHDATA2: missing data length')
  663. datasize = bord(self[i]) + (bord(self[i+1]) << 8)
  664. i += 2
  665. elif opcode == OP_PUSHDATA4:
  666. pushdata_type = 'PUSHDATA4'
  667. if i + 3 >= len(self):
  668. raise CScriptInvalidError('PUSHDATA4: missing data length')
  669. datasize = bord(self[i]) + (bord(self[i+1]) << 8) + (bord(self[i+2]) << 16) + (bord(self[i+3]) << 24)
  670. i += 4
  671. else:
  672. assert False # shouldn't happen
  673. data = bytes(self[i:i+datasize])
  674. # Check for truncation
  675. if len(data) < datasize:
  676. raise CScriptTruncatedPushDataError('%s: truncated data' % pushdata_type, data)
  677. i += datasize
  678. yield (opcode, data, sop_idx)
  679. def __iter__(self):
  680. """'Cooked' iteration
  681. Returns either a CScriptOP instance, an integer, or bytes, as
  682. appropriate.
  683. See raw_iter() if you need to distinguish the different possible
  684. PUSHDATA encodings.
  685. """
  686. for (opcode, data, sop_idx) in self.raw_iter():
  687. if data is not None:
  688. yield data
  689. else:
  690. opcode = CScriptOp(opcode)
  691. if opcode.is_small_int():
  692. yield opcode.decode_op_n()
  693. else:
  694. yield CScriptOp(opcode)
  695. def __repr__(self):
  696. # For Python3 compatibility add b before strings so testcases don't
  697. # need to change
  698. def _repr(o):
  699. if isinstance(o, bytes):
  700. return b"x('%s')" % hexlify(o).decode('ascii')
  701. else:
  702. return repr(o)
  703. ops = []
  704. i = iter(self)
  705. while True:
  706. op = None
  707. try:
  708. op = _repr(next(i))
  709. except CScriptTruncatedPushDataError as err:
  710. op = '%s...<ERROR: %s>' % (_repr(err.data), err)
  711. break
  712. except CScriptInvalidError as err:
  713. op = '<ERROR: %s>' % err
  714. break
  715. except StopIteration:
  716. break
  717. finally:
  718. if op is not None:
  719. ops.append(op)
  720. return "CScript([%s])" % ', '.join(ops)
  721. def GetSigOpCount(self, fAccurate):
  722. """Get the SigOp count.
  723. fAccurate - Accurately count CHECKMULTISIG, see BIP16 for details.
  724. Note that this is consensus-critical.
  725. """
  726. n = 0
  727. lastOpcode = OP_INVALIDOPCODE
  728. for (opcode, data, sop_idx) in self.raw_iter():
  729. if opcode in (OP_CHECKSIG, OP_CHECKSIGVERIFY):
  730. n += 1
  731. elif opcode in (OP_CHECKMULTISIG, OP_CHECKMULTISIGVERIFY):
  732. if fAccurate and (OP_1 <= lastOpcode <= OP_16):
  733. n += opcode.decode_op_n()
  734. else:
  735. n += 20
  736. lastOpcode = opcode
  737. return n
  738. SIGHASH_ALL = 1
  739. SIGHASH_NONE = 2
  740. SIGHASH_SINGLE = 3
  741. SIGHASH_ANYONECANPAY = 0x80
  742. def FindAndDelete(script, sig):
  743. """Consensus critical, see FindAndDelete() in Satoshi codebase"""
  744. r = b''
  745. last_sop_idx = sop_idx = 0
  746. skip = True
  747. for (opcode, data, sop_idx) in script.raw_iter():
  748. if not skip:
  749. r += script[last_sop_idx:sop_idx]
  750. last_sop_idx = sop_idx
  751. if script[sop_idx:sop_idx + len(sig)] == sig:
  752. skip = True
  753. else:
  754. skip = False
  755. if not skip:
  756. r += script[last_sop_idx:]
  757. return CScript(r)
  758. def SignatureHash(script, txTo, inIdx, hashtype):
  759. """Consensus-correct SignatureHash
  760. Returns (hash, err) to precisely match the consensus-critical behavior of
  761. the SIGHASH_SINGLE bug. (inIdx is *not* checked for validity)
  762. """
  763. 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'
  764. if inIdx >= len(txTo.vin):
  765. return (HASH_ONE, "inIdx %d out of range (%d)" % (inIdx, len(txTo.vin)))
  766. txtmp = CTransaction(txTo)
  767. for txin in txtmp.vin:
  768. txin.scriptSig = b''
  769. txtmp.vin[inIdx].scriptSig = FindAndDelete(script, CScript([OP_CODESEPARATOR]))
  770. if (hashtype & 0x1f) == SIGHASH_NONE:
  771. txtmp.vout = []
  772. for i in range(len(txtmp.vin)):
  773. if i != inIdx:
  774. txtmp.vin[i].nSequence = 0
  775. elif (hashtype & 0x1f) == SIGHASH_SINGLE:
  776. outIdx = inIdx
  777. if outIdx >= len(txtmp.vout):
  778. return (HASH_ONE, "outIdx %d out of range (%d)" % (outIdx, len(txtmp.vout)))
  779. tmp = txtmp.vout[outIdx]
  780. txtmp.vout = []
  781. for i in range(outIdx):
  782. txtmp.vout.append(CTxOut(-1))
  783. txtmp.vout.append(tmp)
  784. for i in range(len(txtmp.vin)):
  785. if i != inIdx:
  786. txtmp.vin[i].nSequence = 0
  787. if hashtype & SIGHASH_ANYONECANPAY:
  788. tmp = txtmp.vin[inIdx]
  789. txtmp.vin = []
  790. txtmp.vin.append(tmp)
  791. s = txtmp.serialize()
  792. s += struct.pack(b"<I", hashtype)
  793. hash = hash256(s)
  794. return (hash, None)
  795. # TODO: Allow cached hashPrevouts/hashSequence/hashOutputs to be provided.
  796. # Performance optimization probably not necessary for python tests, however.
  797. # Note that this corresponds to sigversion == 1 in EvalScript, which is used
  798. # for version 0 witnesses.
  799. def SegwitVersion1SignatureHash(script, txTo, inIdx, hashtype, amount):
  800. hashPrevouts = 0
  801. hashSequence = 0
  802. hashOutputs = 0
  803. if not (hashtype & SIGHASH_ANYONECANPAY):
  804. serialize_prevouts = bytes()
  805. for i in txTo.vin:
  806. serialize_prevouts += i.prevout.serialize()
  807. hashPrevouts = uint256_from_str(hash256(serialize_prevouts))
  808. if (not (hashtype & SIGHASH_ANYONECANPAY) and (hashtype & 0x1f) != SIGHASH_SINGLE and (hashtype & 0x1f) != SIGHASH_NONE):
  809. serialize_sequence = bytes()
  810. for i in txTo.vin:
  811. serialize_sequence += struct.pack("<I", i.nSequence)
  812. hashSequence = uint256_from_str(hash256(serialize_sequence))
  813. if ((hashtype & 0x1f) != SIGHASH_SINGLE and (hashtype & 0x1f) != SIGHASH_NONE):
  814. serialize_outputs = bytes()
  815. for o in txTo.vout:
  816. serialize_outputs += o.serialize()
  817. hashOutputs = uint256_from_str(hash256(serialize_outputs))
  818. elif ((hashtype & 0x1f) == SIGHASH_SINGLE and inIdx < len(txTo.vout)):
  819. serialize_outputs = txTo.vout[inIdx].serialize()
  820. hashOutputs = uint256_from_str(hash256(serialize_outputs))
  821. ss = bytes()
  822. ss += struct.pack("<i", txTo.nVersion)
  823. ss += ser_uint256(hashPrevouts)
  824. ss += ser_uint256(hashSequence)
  825. ss += txTo.vin[inIdx].prevout.serialize()
  826. ss += ser_string(script)
  827. ss += struct.pack("<q", amount)
  828. ss += struct.pack("<I", txTo.vin[inIdx].nSequence)
  829. ss += ser_uint256(hashOutputs)
  830. ss += struct.pack("<i", txTo.nLockTime)
  831. ss += struct.pack("<I", hashtype)
  832. return hash256(ss)