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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2010 ArtForz -- public domain half-a-node
  3. # Copyright (c) 2012 Jeff Garzik
  4. # Copyright (c) 2010-2016 The Bitcoin Core developers
  5. # Distributed under the MIT software license, see the accompanying
  6. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
  7. """Bitcoin P2P network half-a-node.
  8. This python code was modified from ArtForz' public domain half-a-node, as
  9. found in the mini-node branch of http://github.com/jgarzik/pynode.
  10. NodeConn: an object which manages p2p connectivity to a bitcoin node
  11. NodeConnCB: a base class that describes the interface for receiving
  12. callbacks with network messages from a NodeConn
  13. CBlock, CTransaction, CBlockHeader, CTxIn, CTxOut, etc....:
  14. data structures that should map to corresponding structures in
  15. bitcoin/primitives
  16. msg_block, msg_tx, msg_headers, etc.:
  17. data structures that represent network messages
  18. ser_*, deser_*: functions that handle serialization/deserialization
  19. """
  20. import asyncore
  21. from codecs import encode
  22. from collections import defaultdict
  23. import copy
  24. import hashlib
  25. from io import BytesIO
  26. import logging
  27. import random
  28. import socket
  29. import struct
  30. import sys
  31. import time
  32. from threading import RLock, Thread
  33. from test_framework.siphash import siphash256
  34. from test_framework.util import hex_str_to_bytes, bytes_to_hex_str
  35. BIP0031_VERSION = 60000
  36. MY_VERSION = 70014 # past bip-31 for ping/pong
  37. MY_SUBVERSION = b"/python-mininode-tester:0.0.3/"
  38. MY_RELAY = 1 # from version 70001 onwards, fRelay should be appended to version messages (BIP37)
  39. MAX_INV_SZ = 50000
  40. MAX_BLOCK_BASE_SIZE = 1000000
  41. COIN = 100000000 # 1 btc in satoshis
  42. NODE_NETWORK = (1 << 0)
  43. NODE_GETUTXO = (1 << 1)
  44. NODE_BLOOM = (1 << 2)
  45. NODE_WITNESS = (1 << 3)
  46. logger = logging.getLogger("TestFramework.mininode")
  47. # Keep our own socket map for asyncore, so that we can track disconnects
  48. # ourselves (to workaround an issue with closing an asyncore socket when
  49. # using select)
  50. mininode_socket_map = dict()
  51. # One lock for synchronizing all data access between the networking thread (see
  52. # NetworkThread below) and the thread running the test logic. For simplicity,
  53. # NodeConn acquires this lock whenever delivering a message to to a NodeConnCB,
  54. # and whenever adding anything to the send buffer (in send_message()). This
  55. # lock should be acquired in the thread running the test logic to synchronize
  56. # access to any data shared with the NodeConnCB or NodeConn.
  57. mininode_lock = RLock()
  58. # Serialization/deserialization tools
  59. def sha256(s):
  60. return hashlib.new('sha256', s).digest()
  61. def ripemd160(s):
  62. return hashlib.new('ripemd160', s).digest()
  63. def hash256(s):
  64. return sha256(sha256(s))
  65. def ser_compact_size(l):
  66. r = b""
  67. if l < 253:
  68. r = struct.pack("B", l)
  69. elif l < 0x10000:
  70. r = struct.pack("<BH", 253, l)
  71. elif l < 0x100000000:
  72. r = struct.pack("<BI", 254, l)
  73. else:
  74. r = struct.pack("<BQ", 255, l)
  75. return r
  76. def deser_compact_size(f):
  77. nit = struct.unpack("<B", f.read(1))[0]
  78. if nit == 253:
  79. nit = struct.unpack("<H", f.read(2))[0]
  80. elif nit == 254:
  81. nit = struct.unpack("<I", f.read(4))[0]
  82. elif nit == 255:
  83. nit = struct.unpack("<Q", f.read(8))[0]
  84. return nit
  85. def deser_string(f):
  86. nit = deser_compact_size(f)
  87. return f.read(nit)
  88. def ser_string(s):
  89. return ser_compact_size(len(s)) + s
  90. def deser_uint256(f):
  91. r = 0
  92. for i in range(8):
  93. t = struct.unpack("<I", f.read(4))[0]
  94. r += t << (i * 32)
  95. return r
  96. def ser_uint256(u):
  97. rs = b""
  98. for i in range(8):
  99. rs += struct.pack("<I", u & 0xFFFFFFFF)
  100. u >>= 32
  101. return rs
  102. def uint256_from_str(s):
  103. r = 0
  104. t = struct.unpack("<IIIIIIII", s[:32])
  105. for i in range(8):
  106. r += t[i] << (i * 32)
  107. return r
  108. def uint256_from_compact(c):
  109. nbytes = (c >> 24) & 0xFF
  110. v = (c & 0xFFFFFF) << (8 * (nbytes - 3))
  111. return v
  112. def deser_vector(f, c):
  113. nit = deser_compact_size(f)
  114. r = []
  115. for i in range(nit):
  116. t = c()
  117. t.deserialize(f)
  118. r.append(t)
  119. return r
  120. # ser_function_name: Allow for an alternate serialization function on the
  121. # entries in the vector (we use this for serializing the vector of transactions
  122. # for a witness block).
  123. def ser_vector(l, ser_function_name=None):
  124. r = ser_compact_size(len(l))
  125. for i in l:
  126. if ser_function_name:
  127. r += getattr(i, ser_function_name)()
  128. else:
  129. r += i.serialize()
  130. return r
  131. def deser_uint256_vector(f):
  132. nit = deser_compact_size(f)
  133. r = []
  134. for i in range(nit):
  135. t = deser_uint256(f)
  136. r.append(t)
  137. return r
  138. def ser_uint256_vector(l):
  139. r = ser_compact_size(len(l))
  140. for i in l:
  141. r += ser_uint256(i)
  142. return r
  143. def deser_string_vector(f):
  144. nit = deser_compact_size(f)
  145. r = []
  146. for i in range(nit):
  147. t = deser_string(f)
  148. r.append(t)
  149. return r
  150. def ser_string_vector(l):
  151. r = ser_compact_size(len(l))
  152. for sv in l:
  153. r += ser_string(sv)
  154. return r
  155. def deser_int_vector(f):
  156. nit = deser_compact_size(f)
  157. r = []
  158. for i in range(nit):
  159. t = struct.unpack("<i", f.read(4))[0]
  160. r.append(t)
  161. return r
  162. def ser_int_vector(l):
  163. r = ser_compact_size(len(l))
  164. for i in l:
  165. r += struct.pack("<i", i)
  166. return r
  167. # Deserialize from a hex string representation (eg from RPC)
  168. def FromHex(obj, hex_string):
  169. obj.deserialize(BytesIO(hex_str_to_bytes(hex_string)))
  170. return obj
  171. # Convert a binary-serializable object to hex (eg for submission via RPC)
  172. def ToHex(obj):
  173. return bytes_to_hex_str(obj.serialize())
  174. # Objects that map to bitcoind objects, which can be serialized/deserialized
  175. class CAddress(object):
  176. def __init__(self):
  177. self.nServices = 1
  178. self.pchReserved = b"\x00" * 10 + b"\xff" * 2
  179. self.ip = "0.0.0.0"
  180. self.port = 0
  181. def deserialize(self, f):
  182. self.nServices = struct.unpack("<Q", f.read(8))[0]
  183. self.pchReserved = f.read(12)
  184. self.ip = socket.inet_ntoa(f.read(4))
  185. self.port = struct.unpack(">H", f.read(2))[0]
  186. def serialize(self):
  187. r = b""
  188. r += struct.pack("<Q", self.nServices)
  189. r += self.pchReserved
  190. r += socket.inet_aton(self.ip)
  191. r += struct.pack(">H", self.port)
  192. return r
  193. def __repr__(self):
  194. return "CAddress(nServices=%i ip=%s port=%i)" % (self.nServices,
  195. self.ip, self.port)
  196. MSG_WITNESS_FLAG = 1<<30
  197. class CInv(object):
  198. typemap = {
  199. 0: "Error",
  200. 1: "TX",
  201. 2: "Block",
  202. 1|MSG_WITNESS_FLAG: "WitnessTx",
  203. 2|MSG_WITNESS_FLAG : "WitnessBlock",
  204. 4: "CompactBlock"
  205. }
  206. def __init__(self, t=0, h=0):
  207. self.type = t
  208. self.hash = h
  209. def deserialize(self, f):
  210. self.type = struct.unpack("<i", f.read(4))[0]
  211. self.hash = deser_uint256(f)
  212. def serialize(self):
  213. r = b""
  214. r += struct.pack("<i", self.type)
  215. r += ser_uint256(self.hash)
  216. return r
  217. def __repr__(self):
  218. return "CInv(type=%s hash=%064x)" \
  219. % (self.typemap[self.type], self.hash)
  220. class CBlockLocator(object):
  221. def __init__(self):
  222. self.nVersion = MY_VERSION
  223. self.vHave = []
  224. def deserialize(self, f):
  225. self.nVersion = struct.unpack("<i", f.read(4))[0]
  226. self.vHave = deser_uint256_vector(f)
  227. def serialize(self):
  228. r = b""
  229. r += struct.pack("<i", self.nVersion)
  230. r += ser_uint256_vector(self.vHave)
  231. return r
  232. def __repr__(self):
  233. return "CBlockLocator(nVersion=%i vHave=%s)" \
  234. % (self.nVersion, repr(self.vHave))
  235. class COutPoint(object):
  236. def __init__(self, hash=0, n=0):
  237. self.hash = hash
  238. self.n = n
  239. def deserialize(self, f):
  240. self.hash = deser_uint256(f)
  241. self.n = struct.unpack("<I", f.read(4))[0]
  242. def serialize(self):
  243. r = b""
  244. r += ser_uint256(self.hash)
  245. r += struct.pack("<I", self.n)
  246. return r
  247. def __repr__(self):
  248. return "COutPoint(hash=%064x n=%i)" % (self.hash, self.n)
  249. class CTxIn(object):
  250. def __init__(self, outpoint=None, scriptSig=b"", nSequence=0):
  251. if outpoint is None:
  252. self.prevout = COutPoint()
  253. else:
  254. self.prevout = outpoint
  255. self.scriptSig = scriptSig
  256. self.nSequence = nSequence
  257. def deserialize(self, f):
  258. self.prevout = COutPoint()
  259. self.prevout.deserialize(f)
  260. self.scriptSig = deser_string(f)
  261. self.nSequence = struct.unpack("<I", f.read(4))[0]
  262. def serialize(self):
  263. r = b""
  264. r += self.prevout.serialize()
  265. r += ser_string(self.scriptSig)
  266. r += struct.pack("<I", self.nSequence)
  267. return r
  268. def __repr__(self):
  269. return "CTxIn(prevout=%s scriptSig=%s nSequence=%i)" \
  270. % (repr(self.prevout), bytes_to_hex_str(self.scriptSig),
  271. self.nSequence)
  272. class CTxOut(object):
  273. def __init__(self, nValue=0, scriptPubKey=b""):
  274. self.nValue = nValue
  275. self.scriptPubKey = scriptPubKey
  276. def deserialize(self, f):
  277. self.nValue = struct.unpack("<q", f.read(8))[0]
  278. self.scriptPubKey = deser_string(f)
  279. def serialize(self):
  280. r = b""
  281. r += struct.pack("<q", self.nValue)
  282. r += ser_string(self.scriptPubKey)
  283. return r
  284. def __repr__(self):
  285. return "CTxOut(nValue=%i.%08i scriptPubKey=%s)" \
  286. % (self.nValue // COIN, self.nValue % COIN,
  287. bytes_to_hex_str(self.scriptPubKey))
  288. class CScriptWitness(object):
  289. def __init__(self):
  290. # stack is a vector of strings
  291. self.stack = []
  292. def __repr__(self):
  293. return "CScriptWitness(%s)" % \
  294. (",".join([bytes_to_hex_str(x) for x in self.stack]))
  295. def is_null(self):
  296. if self.stack:
  297. return False
  298. return True
  299. class CTxInWitness(object):
  300. def __init__(self):
  301. self.scriptWitness = CScriptWitness()
  302. def deserialize(self, f):
  303. self.scriptWitness.stack = deser_string_vector(f)
  304. def serialize(self):
  305. return ser_string_vector(self.scriptWitness.stack)
  306. def __repr__(self):
  307. return repr(self.scriptWitness)
  308. def is_null(self):
  309. return self.scriptWitness.is_null()
  310. class CTxWitness(object):
  311. def __init__(self):
  312. self.vtxinwit = []
  313. def deserialize(self, f):
  314. for i in range(len(self.vtxinwit)):
  315. self.vtxinwit[i].deserialize(f)
  316. def serialize(self):
  317. r = b""
  318. # This is different than the usual vector serialization --
  319. # we omit the length of the vector, which is required to be
  320. # the same length as the transaction's vin vector.
  321. for x in self.vtxinwit:
  322. r += x.serialize()
  323. return r
  324. def __repr__(self):
  325. return "CTxWitness(%s)" % \
  326. (';'.join([repr(x) for x in self.vtxinwit]))
  327. def is_null(self):
  328. for x in self.vtxinwit:
  329. if not x.is_null():
  330. return False
  331. return True
  332. class CTransaction(object):
  333. def __init__(self, tx=None):
  334. if tx is None:
  335. self.nVersion = 1
  336. self.vin = []
  337. self.vout = []
  338. self.wit = CTxWitness()
  339. self.nLockTime = 0
  340. self.sha256 = None
  341. self.hash = None
  342. else:
  343. self.nVersion = tx.nVersion
  344. self.vin = copy.deepcopy(tx.vin)
  345. self.vout = copy.deepcopy(tx.vout)
  346. self.nLockTime = tx.nLockTime
  347. self.sha256 = tx.sha256
  348. self.hash = tx.hash
  349. self.wit = copy.deepcopy(tx.wit)
  350. def deserialize(self, f):
  351. self.nVersion = struct.unpack("<i", f.read(4))[0]
  352. self.vin = deser_vector(f, CTxIn)
  353. flags = 0
  354. if len(self.vin) == 0:
  355. flags = struct.unpack("<B", f.read(1))[0]
  356. # Not sure why flags can't be zero, but this
  357. # matches the implementation in bitcoind
  358. if (flags != 0):
  359. self.vin = deser_vector(f, CTxIn)
  360. self.vout = deser_vector(f, CTxOut)
  361. else:
  362. self.vout = deser_vector(f, CTxOut)
  363. if flags != 0:
  364. self.wit.vtxinwit = [CTxInWitness() for i in range(len(self.vin))]
  365. self.wit.deserialize(f)
  366. self.nLockTime = struct.unpack("<I", f.read(4))[0]
  367. self.sha256 = None
  368. self.hash = None
  369. def serialize_without_witness(self):
  370. r = b""
  371. r += struct.pack("<i", self.nVersion)
  372. r += ser_vector(self.vin)
  373. r += ser_vector(self.vout)
  374. r += struct.pack("<I", self.nLockTime)
  375. return r
  376. # Only serialize with witness when explicitly called for
  377. def serialize_with_witness(self):
  378. flags = 0
  379. if not self.wit.is_null():
  380. flags |= 1
  381. r = b""
  382. r += struct.pack("<i", self.nVersion)
  383. if flags:
  384. dummy = []
  385. r += ser_vector(dummy)
  386. r += struct.pack("<B", flags)
  387. r += ser_vector(self.vin)
  388. r += ser_vector(self.vout)
  389. if flags & 1:
  390. if (len(self.wit.vtxinwit) != len(self.vin)):
  391. # vtxinwit must have the same length as vin
  392. self.wit.vtxinwit = self.wit.vtxinwit[:len(self.vin)]
  393. for i in range(len(self.wit.vtxinwit), len(self.vin)):
  394. self.wit.vtxinwit.append(CTxInWitness())
  395. r += self.wit.serialize()
  396. r += struct.pack("<I", self.nLockTime)
  397. return r
  398. # Regular serialization is without witness -- must explicitly
  399. # call serialize_with_witness to include witness data.
  400. def serialize(self):
  401. return self.serialize_without_witness()
  402. # Recalculate the txid (transaction hash without witness)
  403. def rehash(self):
  404. self.sha256 = None
  405. self.calc_sha256()
  406. # We will only cache the serialization without witness in
  407. # self.sha256 and self.hash -- those are expected to be the txid.
  408. def calc_sha256(self, with_witness=False):
  409. if with_witness:
  410. # Don't cache the result, just return it
  411. return uint256_from_str(hash256(self.serialize_with_witness()))
  412. if self.sha256 is None:
  413. self.sha256 = uint256_from_str(hash256(self.serialize_without_witness()))
  414. self.hash = encode(hash256(self.serialize())[::-1], 'hex_codec').decode('ascii')
  415. def is_valid(self):
  416. self.calc_sha256()
  417. for tout in self.vout:
  418. if tout.nValue < 0 or tout.nValue > 21000000 * COIN:
  419. return False
  420. return True
  421. def __repr__(self):
  422. return "CTransaction(nVersion=%i vin=%s vout=%s wit=%s nLockTime=%i)" \
  423. % (self.nVersion, repr(self.vin), repr(self.vout), repr(self.wit), self.nLockTime)
  424. class CBlockHeader(object):
  425. def __init__(self, header=None):
  426. if header is None:
  427. self.set_null()
  428. else:
  429. self.nVersion = header.nVersion
  430. self.hashPrevBlock = header.hashPrevBlock
  431. self.hashMerkleRoot = header.hashMerkleRoot
  432. self.nTime = header.nTime
  433. self.nBits = header.nBits
  434. self.nNonce = header.nNonce
  435. self.sha256 = header.sha256
  436. self.hash = header.hash
  437. self.calc_sha256()
  438. def set_null(self):
  439. self.nVersion = 1
  440. self.hashPrevBlock = 0
  441. self.hashMerkleRoot = 0
  442. self.nTime = 0
  443. self.nBits = 0
  444. self.nNonce = 0
  445. self.sha256 = None
  446. self.hash = None
  447. def deserialize(self, f):
  448. self.nVersion = struct.unpack("<i", f.read(4))[0]
  449. self.hashPrevBlock = deser_uint256(f)
  450. self.hashMerkleRoot = deser_uint256(f)
  451. self.nTime = struct.unpack("<I", f.read(4))[0]
  452. self.nBits = struct.unpack("<I", f.read(4))[0]
  453. self.nNonce = struct.unpack("<I", f.read(4))[0]
  454. self.sha256 = None
  455. self.hash = None
  456. def serialize(self):
  457. r = b""
  458. r += struct.pack("<i", self.nVersion)
  459. r += ser_uint256(self.hashPrevBlock)
  460. r += ser_uint256(self.hashMerkleRoot)
  461. r += struct.pack("<I", self.nTime)
  462. r += struct.pack("<I", self.nBits)
  463. r += struct.pack("<I", self.nNonce)
  464. return r
  465. def calc_sha256(self):
  466. if self.sha256 is None:
  467. r = b""
  468. r += struct.pack("<i", self.nVersion)
  469. r += ser_uint256(self.hashPrevBlock)
  470. r += ser_uint256(self.hashMerkleRoot)
  471. r += struct.pack("<I", self.nTime)
  472. r += struct.pack("<I", self.nBits)
  473. r += struct.pack("<I", self.nNonce)
  474. self.sha256 = uint256_from_str(hash256(r))
  475. self.hash = encode(hash256(r)[::-1], 'hex_codec').decode('ascii')
  476. def rehash(self):
  477. self.sha256 = None
  478. self.calc_sha256()
  479. return self.sha256
  480. def __repr__(self):
  481. return "CBlockHeader(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nBits=%08x nNonce=%08x)" \
  482. % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot,
  483. time.ctime(self.nTime), self.nBits, self.nNonce)
  484. class CBlock(CBlockHeader):
  485. def __init__(self, header=None):
  486. super(CBlock, self).__init__(header)
  487. self.vtx = []
  488. def deserialize(self, f):
  489. super(CBlock, self).deserialize(f)
  490. self.vtx = deser_vector(f, CTransaction)
  491. def serialize(self, with_witness=False):
  492. r = b""
  493. r += super(CBlock, self).serialize()
  494. if with_witness:
  495. r += ser_vector(self.vtx, "serialize_with_witness")
  496. else:
  497. r += ser_vector(self.vtx)
  498. return r
  499. # Calculate the merkle root given a vector of transaction hashes
  500. @classmethod
  501. def get_merkle_root(cls, hashes):
  502. while len(hashes) > 1:
  503. newhashes = []
  504. for i in range(0, len(hashes), 2):
  505. i2 = min(i+1, len(hashes)-1)
  506. newhashes.append(hash256(hashes[i] + hashes[i2]))
  507. hashes = newhashes
  508. return uint256_from_str(hashes[0])
  509. def calc_merkle_root(self):
  510. hashes = []
  511. for tx in self.vtx:
  512. tx.calc_sha256()
  513. hashes.append(ser_uint256(tx.sha256))
  514. return self.get_merkle_root(hashes)
  515. def calc_witness_merkle_root(self):
  516. # For witness root purposes, the hash of the
  517. # coinbase, with witness, is defined to be 0...0
  518. hashes = [ser_uint256(0)]
  519. for tx in self.vtx[1:]:
  520. # Calculate the hashes with witness data
  521. hashes.append(ser_uint256(tx.calc_sha256(True)))
  522. return self.get_merkle_root(hashes)
  523. def is_valid(self):
  524. self.calc_sha256()
  525. target = uint256_from_compact(self.nBits)
  526. if self.sha256 > target:
  527. return False
  528. for tx in self.vtx:
  529. if not tx.is_valid():
  530. return False
  531. if self.calc_merkle_root() != self.hashMerkleRoot:
  532. return False
  533. return True
  534. def solve(self):
  535. self.rehash()
  536. target = uint256_from_compact(self.nBits)
  537. while self.sha256 > target:
  538. self.nNonce += 1
  539. self.rehash()
  540. def __repr__(self):
  541. return "CBlock(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nBits=%08x nNonce=%08x vtx=%s)" \
  542. % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot,
  543. time.ctime(self.nTime), self.nBits, self.nNonce, repr(self.vtx))
  544. class CUnsignedAlert(object):
  545. def __init__(self):
  546. self.nVersion = 1
  547. self.nRelayUntil = 0
  548. self.nExpiration = 0
  549. self.nID = 0
  550. self.nCancel = 0
  551. self.setCancel = []
  552. self.nMinVer = 0
  553. self.nMaxVer = 0
  554. self.setSubVer = []
  555. self.nPriority = 0
  556. self.strComment = b""
  557. self.strStatusBar = b""
  558. self.strReserved = b""
  559. def deserialize(self, f):
  560. self.nVersion = struct.unpack("<i", f.read(4))[0]
  561. self.nRelayUntil = struct.unpack("<q", f.read(8))[0]
  562. self.nExpiration = struct.unpack("<q", f.read(8))[0]
  563. self.nID = struct.unpack("<i", f.read(4))[0]
  564. self.nCancel = struct.unpack("<i", f.read(4))[0]
  565. self.setCancel = deser_int_vector(f)
  566. self.nMinVer = struct.unpack("<i", f.read(4))[0]
  567. self.nMaxVer = struct.unpack("<i", f.read(4))[0]
  568. self.setSubVer = deser_string_vector(f)
  569. self.nPriority = struct.unpack("<i", f.read(4))[0]
  570. self.strComment = deser_string(f)
  571. self.strStatusBar = deser_string(f)
  572. self.strReserved = deser_string(f)
  573. def serialize(self):
  574. r = b""
  575. r += struct.pack("<i", self.nVersion)
  576. r += struct.pack("<q", self.nRelayUntil)
  577. r += struct.pack("<q", self.nExpiration)
  578. r += struct.pack("<i", self.nID)
  579. r += struct.pack("<i", self.nCancel)
  580. r += ser_int_vector(self.setCancel)
  581. r += struct.pack("<i", self.nMinVer)
  582. r += struct.pack("<i", self.nMaxVer)
  583. r += ser_string_vector(self.setSubVer)
  584. r += struct.pack("<i", self.nPriority)
  585. r += ser_string(self.strComment)
  586. r += ser_string(self.strStatusBar)
  587. r += ser_string(self.strReserved)
  588. return r
  589. def __repr__(self):
  590. return "CUnsignedAlert(nVersion %d, nRelayUntil %d, nExpiration %d, nID %d, nCancel %d, nMinVer %d, nMaxVer %d, nPriority %d, strComment %s, strStatusBar %s, strReserved %s)" \
  591. % (self.nVersion, self.nRelayUntil, self.nExpiration, self.nID,
  592. self.nCancel, self.nMinVer, self.nMaxVer, self.nPriority,
  593. self.strComment, self.strStatusBar, self.strReserved)
  594. class CAlert(object):
  595. def __init__(self):
  596. self.vchMsg = b""
  597. self.vchSig = b""
  598. def deserialize(self, f):
  599. self.vchMsg = deser_string(f)
  600. self.vchSig = deser_string(f)
  601. def serialize(self):
  602. r = b""
  603. r += ser_string(self.vchMsg)
  604. r += ser_string(self.vchSig)
  605. return r
  606. def __repr__(self):
  607. return "CAlert(vchMsg.sz %d, vchSig.sz %d)" \
  608. % (len(self.vchMsg), len(self.vchSig))
  609. class PrefilledTransaction(object):
  610. def __init__(self, index=0, tx = None):
  611. self.index = index
  612. self.tx = tx
  613. def deserialize(self, f):
  614. self.index = deser_compact_size(f)
  615. self.tx = CTransaction()
  616. self.tx.deserialize(f)
  617. def serialize(self, with_witness=False):
  618. r = b""
  619. r += ser_compact_size(self.index)
  620. if with_witness:
  621. r += self.tx.serialize_with_witness()
  622. else:
  623. r += self.tx.serialize_without_witness()
  624. return r
  625. def serialize_with_witness(self):
  626. return self.serialize(with_witness=True)
  627. def __repr__(self):
  628. return "PrefilledTransaction(index=%d, tx=%s)" % (self.index, repr(self.tx))
  629. # This is what we send on the wire, in a cmpctblock message.
  630. class P2PHeaderAndShortIDs(object):
  631. def __init__(self):
  632. self.header = CBlockHeader()
  633. self.nonce = 0
  634. self.shortids_length = 0
  635. self.shortids = []
  636. self.prefilled_txn_length = 0
  637. self.prefilled_txn = []
  638. def deserialize(self, f):
  639. self.header.deserialize(f)
  640. self.nonce = struct.unpack("<Q", f.read(8))[0]
  641. self.shortids_length = deser_compact_size(f)
  642. for i in range(self.shortids_length):
  643. # shortids are defined to be 6 bytes in the spec, so append
  644. # two zero bytes and read it in as an 8-byte number
  645. self.shortids.append(struct.unpack("<Q", f.read(6) + b'\x00\x00')[0])
  646. self.prefilled_txn = deser_vector(f, PrefilledTransaction)
  647. self.prefilled_txn_length = len(self.prefilled_txn)
  648. # When using version 2 compact blocks, we must serialize with_witness.
  649. def serialize(self, with_witness=False):
  650. r = b""
  651. r += self.header.serialize()
  652. r += struct.pack("<Q", self.nonce)
  653. r += ser_compact_size(self.shortids_length)
  654. for x in self.shortids:
  655. # We only want the first 6 bytes
  656. r += struct.pack("<Q", x)[0:6]
  657. if with_witness:
  658. r += ser_vector(self.prefilled_txn, "serialize_with_witness")
  659. else:
  660. r += ser_vector(self.prefilled_txn)
  661. return r
  662. def __repr__(self):
  663. return "P2PHeaderAndShortIDs(header=%s, nonce=%d, shortids_length=%d, shortids=%s, prefilled_txn_length=%d, prefilledtxn=%s" % (repr(self.header), self.nonce, self.shortids_length, repr(self.shortids), self.prefilled_txn_length, repr(self.prefilled_txn))
  664. # P2P version of the above that will use witness serialization (for compact
  665. # block version 2)
  666. class P2PHeaderAndShortWitnessIDs(P2PHeaderAndShortIDs):
  667. def serialize(self):
  668. return super(P2PHeaderAndShortWitnessIDs, self).serialize(with_witness=True)
  669. # Calculate the BIP 152-compact blocks shortid for a given transaction hash
  670. def calculate_shortid(k0, k1, tx_hash):
  671. expected_shortid = siphash256(k0, k1, tx_hash)
  672. expected_shortid &= 0x0000ffffffffffff
  673. return expected_shortid
  674. # This version gets rid of the array lengths, and reinterprets the differential
  675. # encoding into indices that can be used for lookup.
  676. class HeaderAndShortIDs(object):
  677. def __init__(self, p2pheaders_and_shortids = None):
  678. self.header = CBlockHeader()
  679. self.nonce = 0
  680. self.shortids = []
  681. self.prefilled_txn = []
  682. self.use_witness = False
  683. if p2pheaders_and_shortids != None:
  684. self.header = p2pheaders_and_shortids.header
  685. self.nonce = p2pheaders_and_shortids.nonce
  686. self.shortids = p2pheaders_and_shortids.shortids
  687. last_index = -1
  688. for x in p2pheaders_and_shortids.prefilled_txn:
  689. self.prefilled_txn.append(PrefilledTransaction(x.index + last_index + 1, x.tx))
  690. last_index = self.prefilled_txn[-1].index
  691. def to_p2p(self):
  692. if self.use_witness:
  693. ret = P2PHeaderAndShortWitnessIDs()
  694. else:
  695. ret = P2PHeaderAndShortIDs()
  696. ret.header = self.header
  697. ret.nonce = self.nonce
  698. ret.shortids_length = len(self.shortids)
  699. ret.shortids = self.shortids
  700. ret.prefilled_txn_length = len(self.prefilled_txn)
  701. ret.prefilled_txn = []
  702. last_index = -1
  703. for x in self.prefilled_txn:
  704. ret.prefilled_txn.append(PrefilledTransaction(x.index - last_index - 1, x.tx))
  705. last_index = x.index
  706. return ret
  707. def get_siphash_keys(self):
  708. header_nonce = self.header.serialize()
  709. header_nonce += struct.pack("<Q", self.nonce)
  710. hash_header_nonce_as_str = sha256(header_nonce)
  711. key0 = struct.unpack("<Q", hash_header_nonce_as_str[0:8])[0]
  712. key1 = struct.unpack("<Q", hash_header_nonce_as_str[8:16])[0]
  713. return [ key0, key1 ]
  714. # Version 2 compact blocks use wtxid in shortids (rather than txid)
  715. def initialize_from_block(self, block, nonce=0, prefill_list = [0], use_witness = False):
  716. self.header = CBlockHeader(block)
  717. self.nonce = nonce
  718. self.prefilled_txn = [ PrefilledTransaction(i, block.vtx[i]) for i in prefill_list ]
  719. self.shortids = []
  720. self.use_witness = use_witness
  721. [k0, k1] = self.get_siphash_keys()
  722. for i in range(len(block.vtx)):
  723. if i not in prefill_list:
  724. tx_hash = block.vtx[i].sha256
  725. if use_witness:
  726. tx_hash = block.vtx[i].calc_sha256(with_witness=True)
  727. self.shortids.append(calculate_shortid(k0, k1, tx_hash))
  728. def __repr__(self):
  729. return "HeaderAndShortIDs(header=%s, nonce=%d, shortids=%s, prefilledtxn=%s" % (repr(self.header), self.nonce, repr(self.shortids), repr(self.prefilled_txn))
  730. class BlockTransactionsRequest(object):
  731. def __init__(self, blockhash=0, indexes = None):
  732. self.blockhash = blockhash
  733. self.indexes = indexes if indexes != None else []
  734. def deserialize(self, f):
  735. self.blockhash = deser_uint256(f)
  736. indexes_length = deser_compact_size(f)
  737. for i in range(indexes_length):
  738. self.indexes.append(deser_compact_size(f))
  739. def serialize(self):
  740. r = b""
  741. r += ser_uint256(self.blockhash)
  742. r += ser_compact_size(len(self.indexes))
  743. for x in self.indexes:
  744. r += ser_compact_size(x)
  745. return r
  746. # helper to set the differentially encoded indexes from absolute ones
  747. def from_absolute(self, absolute_indexes):
  748. self.indexes = []
  749. last_index = -1
  750. for x in absolute_indexes:
  751. self.indexes.append(x-last_index-1)
  752. last_index = x
  753. def to_absolute(self):
  754. absolute_indexes = []
  755. last_index = -1
  756. for x in self.indexes:
  757. absolute_indexes.append(x+last_index+1)
  758. last_index = absolute_indexes[-1]
  759. return absolute_indexes
  760. def __repr__(self):
  761. return "BlockTransactionsRequest(hash=%064x indexes=%s)" % (self.blockhash, repr(self.indexes))
  762. class BlockTransactions(object):
  763. def __init__(self, blockhash=0, transactions = None):
  764. self.blockhash = blockhash
  765. self.transactions = transactions if transactions != None else []
  766. def deserialize(self, f):
  767. self.blockhash = deser_uint256(f)
  768. self.transactions = deser_vector(f, CTransaction)
  769. def serialize(self, with_witness=False):
  770. r = b""
  771. r += ser_uint256(self.blockhash)
  772. if with_witness:
  773. r += ser_vector(self.transactions, "serialize_with_witness")
  774. else:
  775. r += ser_vector(self.transactions)
  776. return r
  777. def __repr__(self):
  778. return "BlockTransactions(hash=%064x transactions=%s)" % (self.blockhash, repr(self.transactions))
  779. # Objects that correspond to messages on the wire
  780. class msg_version(object):
  781. command = b"version"
  782. def __init__(self):
  783. self.nVersion = MY_VERSION
  784. self.nServices = 1
  785. self.nTime = int(time.time())
  786. self.addrTo = CAddress()
  787. self.addrFrom = CAddress()
  788. self.nNonce = random.getrandbits(64)
  789. self.strSubVer = MY_SUBVERSION
  790. self.nStartingHeight = -1
  791. self.nRelay = MY_RELAY
  792. def deserialize(self, f):
  793. self.nVersion = struct.unpack("<i", f.read(4))[0]
  794. if self.nVersion == 10300:
  795. self.nVersion = 300
  796. self.nServices = struct.unpack("<Q", f.read(8))[0]
  797. self.nTime = struct.unpack("<q", f.read(8))[0]
  798. self.addrTo = CAddress()
  799. self.addrTo.deserialize(f)
  800. if self.nVersion >= 106:
  801. self.addrFrom = CAddress()
  802. self.addrFrom.deserialize(f)
  803. self.nNonce = struct.unpack("<Q", f.read(8))[0]
  804. self.strSubVer = deser_string(f)
  805. else:
  806. self.addrFrom = None
  807. self.nNonce = None
  808. self.strSubVer = None
  809. self.nStartingHeight = None
  810. if self.nVersion >= 209:
  811. self.nStartingHeight = struct.unpack("<i", f.read(4))[0]
  812. else:
  813. self.nStartingHeight = None
  814. if self.nVersion >= 70001:
  815. # Relay field is optional for version 70001 onwards
  816. try:
  817. self.nRelay = struct.unpack("<b", f.read(1))[0]
  818. except:
  819. self.nRelay = 0
  820. else:
  821. self.nRelay = 0
  822. def serialize(self):
  823. r = b""
  824. r += struct.pack("<i", self.nVersion)
  825. r += struct.pack("<Q", self.nServices)
  826. r += struct.pack("<q", self.nTime)
  827. r += self.addrTo.serialize()
  828. r += self.addrFrom.serialize()
  829. r += struct.pack("<Q", self.nNonce)
  830. r += ser_string(self.strSubVer)
  831. r += struct.pack("<i", self.nStartingHeight)
  832. r += struct.pack("<b", self.nRelay)
  833. return r
  834. def __repr__(self):
  835. return 'msg_version(nVersion=%i nServices=%i nTime=%s addrTo=%s addrFrom=%s nNonce=0x%016X strSubVer=%s nStartingHeight=%i nRelay=%i)' \
  836. % (self.nVersion, self.nServices, time.ctime(self.nTime),
  837. repr(self.addrTo), repr(self.addrFrom), self.nNonce,
  838. self.strSubVer, self.nStartingHeight, self.nRelay)
  839. class msg_verack(object):
  840. command = b"verack"
  841. def __init__(self):
  842. pass
  843. def deserialize(self, f):
  844. pass
  845. def serialize(self):
  846. return b""
  847. def __repr__(self):
  848. return "msg_verack()"
  849. class msg_addr(object):
  850. command = b"addr"
  851. def __init__(self):
  852. self.addrs = []
  853. def deserialize(self, f):
  854. self.addrs = deser_vector(f, CAddress)
  855. def serialize(self):
  856. return ser_vector(self.addrs)
  857. def __repr__(self):
  858. return "msg_addr(addrs=%s)" % (repr(self.addrs))
  859. class msg_alert(object):
  860. command = b"alert"
  861. def __init__(self):
  862. self.alert = CAlert()
  863. def deserialize(self, f):
  864. self.alert = CAlert()
  865. self.alert.deserialize(f)
  866. def serialize(self):
  867. r = b""
  868. r += self.alert.serialize()
  869. return r
  870. def __repr__(self):
  871. return "msg_alert(alert=%s)" % (repr(self.alert), )
  872. class msg_inv(object):
  873. command = b"inv"
  874. def __init__(self, inv=None):
  875. if inv is None:
  876. self.inv = []
  877. else:
  878. self.inv = inv
  879. def deserialize(self, f):
  880. self.inv = deser_vector(f, CInv)
  881. def serialize(self):
  882. return ser_vector(self.inv)
  883. def __repr__(self):
  884. return "msg_inv(inv=%s)" % (repr(self.inv))
  885. class msg_getdata(object):
  886. command = b"getdata"
  887. def __init__(self, inv=None):
  888. self.inv = inv if inv != None else []
  889. def deserialize(self, f):
  890. self.inv = deser_vector(f, CInv)
  891. def serialize(self):
  892. return ser_vector(self.inv)
  893. def __repr__(self):
  894. return "msg_getdata(inv=%s)" % (repr(self.inv))
  895. class msg_getblocks(object):
  896. command = b"getblocks"
  897. def __init__(self):
  898. self.locator = CBlockLocator()
  899. self.hashstop = 0
  900. def deserialize(self, f):
  901. self.locator = CBlockLocator()
  902. self.locator.deserialize(f)
  903. self.hashstop = deser_uint256(f)
  904. def serialize(self):
  905. r = b""
  906. r += self.locator.serialize()
  907. r += ser_uint256(self.hashstop)
  908. return r
  909. def __repr__(self):
  910. return "msg_getblocks(locator=%s hashstop=%064x)" \
  911. % (repr(self.locator), self.hashstop)
  912. class msg_tx(object):
  913. command = b"tx"
  914. def __init__(self, tx=CTransaction()):
  915. self.tx = tx
  916. def deserialize(self, f):
  917. self.tx.deserialize(f)
  918. def serialize(self):
  919. return self.tx.serialize_without_witness()
  920. def __repr__(self):
  921. return "msg_tx(tx=%s)" % (repr(self.tx))
  922. class msg_witness_tx(msg_tx):
  923. def serialize(self):
  924. return self.tx.serialize_with_witness()
  925. class msg_block(object):
  926. command = b"block"
  927. def __init__(self, block=None):
  928. if block is None:
  929. self.block = CBlock()
  930. else:
  931. self.block = block
  932. def deserialize(self, f):
  933. self.block.deserialize(f)
  934. def serialize(self):
  935. return self.block.serialize()
  936. def __repr__(self):
  937. return "msg_block(block=%s)" % (repr(self.block))
  938. # for cases where a user needs tighter control over what is sent over the wire
  939. # note that the user must supply the name of the command, and the data
  940. class msg_generic(object):
  941. def __init__(self, command, data=None):
  942. self.command = command
  943. self.data = data
  944. def serialize(self):
  945. return self.data
  946. def __repr__(self):
  947. return "msg_generic()"
  948. class msg_witness_block(msg_block):
  949. def serialize(self):
  950. r = self.block.serialize(with_witness=True)
  951. return r
  952. class msg_getaddr(object):
  953. command = b"getaddr"
  954. def __init__(self):
  955. pass
  956. def deserialize(self, f):
  957. pass
  958. def serialize(self):
  959. return b""
  960. def __repr__(self):
  961. return "msg_getaddr()"
  962. class msg_ping_prebip31(object):
  963. command = b"ping"
  964. def __init__(self):
  965. pass
  966. def deserialize(self, f):
  967. pass
  968. def serialize(self):
  969. return b""
  970. def __repr__(self):
  971. return "msg_ping() (pre-bip31)"
  972. class msg_ping(object):
  973. command = b"ping"
  974. def __init__(self, nonce=0):
  975. self.nonce = nonce
  976. def deserialize(self, f):
  977. self.nonce = struct.unpack("<Q", f.read(8))[0]
  978. def serialize(self):
  979. r = b""
  980. r += struct.pack("<Q", self.nonce)
  981. return r
  982. def __repr__(self):
  983. return "msg_ping(nonce=%08x)" % self.nonce
  984. class msg_pong(object):
  985. command = b"pong"
  986. def __init__(self, nonce=0):
  987. self.nonce = nonce
  988. def deserialize(self, f):
  989. self.nonce = struct.unpack("<Q", f.read(8))[0]
  990. def serialize(self):
  991. r = b""
  992. r += struct.pack("<Q", self.nonce)
  993. return r
  994. def __repr__(self):
  995. return "msg_pong(nonce=%08x)" % self.nonce
  996. class msg_mempool(object):
  997. command = b"mempool"
  998. def __init__(self):
  999. pass
  1000. def deserialize(self, f):
  1001. pass
  1002. def serialize(self):
  1003. return b""
  1004. def __repr__(self):
  1005. return "msg_mempool()"
  1006. class msg_sendheaders(object):
  1007. command = b"sendheaders"
  1008. def __init__(self):
  1009. pass
  1010. def deserialize(self, f):
  1011. pass
  1012. def serialize(self):
  1013. return b""
  1014. def __repr__(self):
  1015. return "msg_sendheaders()"
  1016. # getheaders message has
  1017. # number of entries
  1018. # vector of hashes
  1019. # hash_stop (hash of last desired block header, 0 to get as many as possible)
  1020. class msg_getheaders(object):
  1021. command = b"getheaders"
  1022. def __init__(self):
  1023. self.locator = CBlockLocator()
  1024. self.hashstop = 0
  1025. def deserialize(self, f):
  1026. self.locator = CBlockLocator()
  1027. self.locator.deserialize(f)
  1028. self.hashstop = deser_uint256(f)
  1029. def serialize(self):
  1030. r = b""
  1031. r += self.locator.serialize()
  1032. r += ser_uint256(self.hashstop)
  1033. return r
  1034. def __repr__(self):
  1035. return "msg_getheaders(locator=%s, stop=%064x)" \
  1036. % (repr(self.locator), self.hashstop)
  1037. # headers message has
  1038. # <count> <vector of block headers>
  1039. class msg_headers(object):
  1040. command = b"headers"
  1041. def __init__(self):
  1042. self.headers = []
  1043. def deserialize(self, f):
  1044. # comment in bitcoind indicates these should be deserialized as blocks
  1045. blocks = deser_vector(f, CBlock)
  1046. for x in blocks:
  1047. self.headers.append(CBlockHeader(x))
  1048. def serialize(self):
  1049. blocks = [CBlock(x) for x in self.headers]
  1050. return ser_vector(blocks)
  1051. def __repr__(self):
  1052. return "msg_headers(headers=%s)" % repr(self.headers)
  1053. class msg_reject(object):
  1054. command = b"reject"
  1055. REJECT_MALFORMED = 1
  1056. def __init__(self):
  1057. self.message = b""
  1058. self.code = 0
  1059. self.reason = b""
  1060. self.data = 0
  1061. def deserialize(self, f):
  1062. self.message = deser_string(f)
  1063. self.code = struct.unpack("<B", f.read(1))[0]
  1064. self.reason = deser_string(f)
  1065. if (self.code != self.REJECT_MALFORMED and
  1066. (self.message == b"block" or self.message == b"tx")):
  1067. self.data = deser_uint256(f)
  1068. def serialize(self):
  1069. r = ser_string(self.message)
  1070. r += struct.pack("<B", self.code)
  1071. r += ser_string(self.reason)
  1072. if (self.code != self.REJECT_MALFORMED and
  1073. (self.message == b"block" or self.message == b"tx")):
  1074. r += ser_uint256(self.data)
  1075. return r
  1076. def __repr__(self):
  1077. return "msg_reject: %s %d %s [%064x]" \
  1078. % (self.message, self.code, self.reason, self.data)
  1079. # Helper function
  1080. def wait_until(predicate, *, attempts=float('inf'), timeout=float('inf')):
  1081. if attempts == float('inf') and timeout == float('inf'):
  1082. timeout = 60
  1083. attempt = 0
  1084. elapsed = 0
  1085. while attempt < attempts and elapsed < timeout:
  1086. with mininode_lock:
  1087. if predicate():
  1088. return True
  1089. attempt += 1
  1090. elapsed += 0.05
  1091. time.sleep(0.05)
  1092. return False
  1093. class msg_feefilter(object):
  1094. command = b"feefilter"
  1095. def __init__(self, feerate=0):
  1096. self.feerate = feerate
  1097. def deserialize(self, f):
  1098. self.feerate = struct.unpack("<Q", f.read(8))[0]
  1099. def serialize(self):
  1100. r = b""
  1101. r += struct.pack("<Q", self.feerate)
  1102. return r
  1103. def __repr__(self):
  1104. return "msg_feefilter(feerate=%08x)" % self.feerate
  1105. class msg_sendcmpct(object):
  1106. command = b"sendcmpct"
  1107. def __init__(self):
  1108. self.announce = False
  1109. self.version = 1
  1110. def deserialize(self, f):
  1111. self.announce = struct.unpack("<?", f.read(1))[0]
  1112. self.version = struct.unpack("<Q", f.read(8))[0]
  1113. def serialize(self):
  1114. r = b""
  1115. r += struct.pack("<?", self.announce)
  1116. r += struct.pack("<Q", self.version)
  1117. return r
  1118. def __repr__(self):
  1119. return "msg_sendcmpct(announce=%s, version=%lu)" % (self.announce, self.version)
  1120. class msg_cmpctblock(object):
  1121. command = b"cmpctblock"
  1122. def __init__(self, header_and_shortids = None):
  1123. self.header_and_shortids = header_and_shortids
  1124. def deserialize(self, f):
  1125. self.header_and_shortids = P2PHeaderAndShortIDs()
  1126. self.header_and_shortids.deserialize(f)
  1127. def serialize(self):
  1128. r = b""
  1129. r += self.header_and_shortids.serialize()
  1130. return r
  1131. def __repr__(self):
  1132. return "msg_cmpctblock(HeaderAndShortIDs=%s)" % repr(self.header_and_shortids)
  1133. class msg_getblocktxn(object):
  1134. command = b"getblocktxn"
  1135. def __init__(self):
  1136. self.block_txn_request = None
  1137. def deserialize(self, f):
  1138. self.block_txn_request = BlockTransactionsRequest()
  1139. self.block_txn_request.deserialize(f)
  1140. def serialize(self):
  1141. r = b""
  1142. r += self.block_txn_request.serialize()
  1143. return r
  1144. def __repr__(self):
  1145. return "msg_getblocktxn(block_txn_request=%s)" % (repr(self.block_txn_request))
  1146. class msg_blocktxn(object):
  1147. command = b"blocktxn"
  1148. def __init__(self):
  1149. self.block_transactions = BlockTransactions()
  1150. def deserialize(self, f):
  1151. self.block_transactions.deserialize(f)
  1152. def serialize(self):
  1153. r = b""
  1154. r += self.block_transactions.serialize()
  1155. return r
  1156. def __repr__(self):
  1157. return "msg_blocktxn(block_transactions=%s)" % (repr(self.block_transactions))
  1158. class msg_witness_blocktxn(msg_blocktxn):
  1159. def serialize(self):
  1160. r = b""
  1161. r += self.block_transactions.serialize(with_witness=True)
  1162. return r
  1163. class NodeConnCB(object):
  1164. """Callback and helper functions for P2P connection to a bitcoind node.
  1165. Individual testcases should subclass this and override the on_* methods
  1166. if they want to alter message handling behaviour.
  1167. """
  1168. def __init__(self):
  1169. # Track whether we have a P2P connection open to the node
  1170. self.connected = False
  1171. self.connection = None
  1172. # Track number of messages of each type received and the most recent
  1173. # message of each type
  1174. self.message_count = defaultdict(int)
  1175. self.last_message = {}
  1176. # A count of the number of ping messages we've sent to the node
  1177. self.ping_counter = 1
  1178. # deliver_sleep_time is helpful for debugging race conditions in p2p
  1179. # tests; it causes message delivery to sleep for the specified time
  1180. # before acquiring the global lock and delivering the next message.
  1181. self.deliver_sleep_time = None
  1182. # Remember the services our peer has advertised
  1183. self.peer_services = None
  1184. # Message receiving methods
  1185. def deliver(self, conn, message):
  1186. """Receive message and dispatch message to appropriate callback.
  1187. We keep a count of how many of each message type has been received
  1188. and the most recent message of each type.
  1189. Optionally waits for deliver_sleep_time before dispatching message.
  1190. """
  1191. deliver_sleep = self.get_deliver_sleep_time()
  1192. if deliver_sleep is not None:
  1193. time.sleep(deliver_sleep)
  1194. with mininode_lock:
  1195. try:
  1196. command = message.command.decode('ascii')
  1197. self.message_count[command] += 1
  1198. self.last_message[command] = message
  1199. getattr(self, 'on_' + command)(conn, message)
  1200. except:
  1201. print("ERROR delivering %s (%s)" % (repr(message),
  1202. sys.exc_info()[0]))
  1203. def set_deliver_sleep_time(self, value):
  1204. with mininode_lock:
  1205. self.deliver_sleep_time = value
  1206. def get_deliver_sleep_time(self):
  1207. with mininode_lock:
  1208. return self.deliver_sleep_time
  1209. # Callback methods. Can be overridden by subclasses in individual test
  1210. # cases to provide custom message handling behaviour.
  1211. def on_open(self, conn):
  1212. self.connected = True
  1213. def on_close(self, conn):
  1214. self.connected = False
  1215. self.connection = None
  1216. def on_addr(self, conn, message): pass
  1217. def on_alert(self, conn, message): pass
  1218. def on_block(self, conn, message): pass
  1219. def on_blocktxn(self, conn, message): pass
  1220. def on_cmpctblock(self, conn, message): pass
  1221. def on_feefilter(self, conn, message): pass
  1222. def on_getaddr(self, conn, message): pass
  1223. def on_getblocks(self, conn, message): pass
  1224. def on_getblocktxn(self, conn, message): pass
  1225. def on_getdata(self, conn, message): pass
  1226. def on_getheaders(self, conn, message): pass
  1227. def on_headers(self, conn, message): pass
  1228. def on_mempool(self, conn): pass
  1229. def on_pong(self, conn, message): pass
  1230. def on_reject(self, conn, message): pass
  1231. def on_sendcmpct(self, conn, message): pass
  1232. def on_sendheaders(self, conn, message): pass
  1233. def on_tx(self, conn, message): pass
  1234. def on_inv(self, conn, message):
  1235. want = msg_getdata()
  1236. for i in message.inv:
  1237. if i.type != 0:
  1238. want.inv.append(i)
  1239. if len(want.inv):
  1240. conn.send_message(want)
  1241. def on_ping(self, conn, message):
  1242. if conn.ver_send > BIP0031_VERSION:
  1243. conn.send_message(msg_pong(message.nonce))
  1244. def on_verack(self, conn, message):
  1245. conn.ver_recv = conn.ver_send
  1246. self.verack_received = True
  1247. def on_version(self, conn, message):
  1248. if message.nVersion >= 209:
  1249. conn.send_message(msg_verack())
  1250. conn.ver_send = min(MY_VERSION, message.nVersion)
  1251. if message.nVersion < 209:
  1252. conn.ver_recv = conn.ver_send
  1253. conn.nServices = message.nServices
  1254. # Connection helper methods
  1255. def add_connection(self, conn):
  1256. self.connection = conn
  1257. def wait_for_disconnect(self, timeout=60):
  1258. test_function = lambda: not self.connected
  1259. assert wait_until(test_function, timeout=timeout)
  1260. # Message receiving helper methods
  1261. def wait_for_block(self, blockhash, timeout=60):
  1262. test_function = lambda: self.last_message.get("block") and self.last_message["block"].block.rehash() == blockhash
  1263. assert wait_until(test_function, timeout=timeout)
  1264. def wait_for_getdata(self, timeout=60):
  1265. test_function = lambda: self.last_message.get("getdata")
  1266. assert wait_until(test_function, timeout=timeout)
  1267. def wait_for_getheaders(self, timeout=60):
  1268. test_function = lambda: self.last_message.get("getheaders")
  1269. assert wait_until(test_function, timeout=timeout)
  1270. def wait_for_inv(self, expected_inv, timeout=60):
  1271. """Waits for an INV message and checks that the first inv object in the message was as expected."""
  1272. if len(expected_inv) > 1:
  1273. raise NotImplementedError("wait_for_inv() will only verify the first inv object")
  1274. test_function = lambda: self.last_message.get("inv") and \
  1275. self.last_message["inv"].inv[0].type == expected_inv[0].type and \
  1276. self.last_message["inv"].inv[0].hash == expected_inv[0].hash
  1277. assert wait_until(test_function, timeout=timeout)
  1278. def wait_for_verack(self, timeout=60):
  1279. test_function = lambda: self.message_count["verack"]
  1280. assert wait_until(test_function, timeout=timeout)
  1281. # Message sending helper functions
  1282. def send_message(self, message):
  1283. if self.connection:
  1284. self.connection.send_message(message)
  1285. else:
  1286. logger.error("Cannot send message. No connection to node!")
  1287. def send_and_ping(self, message):
  1288. self.send_message(message)
  1289. self.sync_with_ping()
  1290. # Sync up with the node
  1291. def sync_with_ping(self, timeout=60):
  1292. self.send_message(msg_ping(nonce=self.ping_counter))
  1293. test_function = lambda: self.last_message.get("pong") and self.last_message["pong"].nonce == self.ping_counter
  1294. assert wait_until(test_function, timeout=timeout)
  1295. self.ping_counter += 1
  1296. return True
  1297. # The actual NodeConn class
  1298. # This class provides an interface for a p2p connection to a specified node
  1299. class NodeConn(asyncore.dispatcher):
  1300. messagemap = {
  1301. b"version": msg_version,
  1302. b"verack": msg_verack,
  1303. b"addr": msg_addr,
  1304. b"alert": msg_alert,
  1305. b"inv": msg_inv,
  1306. b"getdata": msg_getdata,
  1307. b"getblocks": msg_getblocks,
  1308. b"tx": msg_tx,
  1309. b"block": msg_block,
  1310. b"getaddr": msg_getaddr,
  1311. b"ping": msg_ping,
  1312. b"pong": msg_pong,
  1313. b"headers": msg_headers,
  1314. b"getheaders": msg_getheaders,
  1315. b"reject": msg_reject,
  1316. b"mempool": msg_mempool,
  1317. b"feefilter": msg_feefilter,
  1318. b"sendheaders": msg_sendheaders,
  1319. b"sendcmpct": msg_sendcmpct,
  1320. b"cmpctblock": msg_cmpctblock,
  1321. b"getblocktxn": msg_getblocktxn,
  1322. b"blocktxn": msg_blocktxn
  1323. }
  1324. MAGIC_BYTES = {
  1325. "mainnet": b"\xf9\xbe\xb4\xd9", # mainnet
  1326. "testnet3": b"\x0b\x11\x09\x07", # testnet3
  1327. "regtest": b"\xfa\xbf\xb5\xda", # regtest
  1328. }
  1329. def __init__(self, dstaddr, dstport, rpc, callback, net="regtest", services=NODE_NETWORK, send_version=True):
  1330. asyncore.dispatcher.__init__(self, map=mininode_socket_map)
  1331. self.dstaddr = dstaddr
  1332. self.dstport = dstport
  1333. self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
  1334. self.sendbuf = b""
  1335. self.recvbuf = b""
  1336. self.ver_send = 209
  1337. self.ver_recv = 209
  1338. self.last_sent = 0
  1339. self.state = "connecting"
  1340. self.network = net
  1341. self.cb = callback
  1342. self.disconnect = False
  1343. self.nServices = 0
  1344. if send_version:
  1345. # stuff version msg into sendbuf
  1346. vt = msg_version()
  1347. vt.nServices = services
  1348. vt.addrTo.ip = self.dstaddr
  1349. vt.addrTo.port = self.dstport
  1350. vt.addrFrom.ip = "0.0.0.0"
  1351. vt.addrFrom.port = 0
  1352. self.send_message(vt, True)
  1353. logger.info('Connecting to Bitcoin Node: %s:%d' % (self.dstaddr, self.dstport))
  1354. try:
  1355. self.connect((dstaddr, dstport))
  1356. except:
  1357. self.handle_close()
  1358. self.rpc = rpc
  1359. def handle_connect(self):
  1360. if self.state != "connected":
  1361. logger.debug("Connected & Listening: %s:%d" % (self.dstaddr, self.dstport))
  1362. self.state = "connected"
  1363. self.cb.on_open(self)
  1364. def handle_close(self):
  1365. logger.debug("Closing connection to: %s:%d" % (self.dstaddr, self.dstport))
  1366. self.state = "closed"
  1367. self.recvbuf = b""
  1368. self.sendbuf = b""
  1369. try:
  1370. self.close()
  1371. except:
  1372. pass
  1373. self.cb.on_close(self)
  1374. def handle_read(self):
  1375. try:
  1376. t = self.recv(8192)
  1377. if len(t) > 0:
  1378. self.recvbuf += t
  1379. self.got_data()
  1380. except:
  1381. pass
  1382. def readable(self):
  1383. return True
  1384. def writable(self):
  1385. with mininode_lock:
  1386. pre_connection = self.state == "connecting"
  1387. length = len(self.sendbuf)
  1388. return (length > 0 or pre_connection)
  1389. def handle_write(self):
  1390. with mininode_lock:
  1391. # asyncore does not expose socket connection, only the first read/write
  1392. # event, thus we must check connection manually here to know when we
  1393. # actually connect
  1394. if self.state == "connecting":
  1395. self.handle_connect()
  1396. if not self.writable():
  1397. return
  1398. try:
  1399. sent = self.send(self.sendbuf)
  1400. except:
  1401. self.handle_close()
  1402. return
  1403. self.sendbuf = self.sendbuf[sent:]
  1404. def got_data(self):
  1405. try:
  1406. while True:
  1407. if len(self.recvbuf) < 4:
  1408. return
  1409. if self.recvbuf[:4] != self.MAGIC_BYTES[self.network]:
  1410. raise ValueError("got garbage %s" % repr(self.recvbuf))
  1411. if self.ver_recv < 209:
  1412. if len(self.recvbuf) < 4 + 12 + 4:
  1413. return
  1414. command = self.recvbuf[4:4+12].split(b"\x00", 1)[0]
  1415. msglen = struct.unpack("<i", self.recvbuf[4+12:4+12+4])[0]
  1416. checksum = None
  1417. if len(self.recvbuf) < 4 + 12 + 4 + msglen:
  1418. return
  1419. msg = self.recvbuf[4+12+4:4+12+4+msglen]
  1420. self.recvbuf = self.recvbuf[4+12+4+msglen:]
  1421. else:
  1422. if len(self.recvbuf) < 4 + 12 + 4 + 4:
  1423. return
  1424. command = self.recvbuf[4:4+12].split(b"\x00", 1)[0]
  1425. msglen = struct.unpack("<i", self.recvbuf[4+12:4+12+4])[0]
  1426. checksum = self.recvbuf[4+12+4:4+12+4+4]
  1427. if len(self.recvbuf) < 4 + 12 + 4 + 4 + msglen:
  1428. return
  1429. msg = self.recvbuf[4+12+4+4:4+12+4+4+msglen]
  1430. th = sha256(msg)
  1431. h = sha256(th)
  1432. if checksum != h[:4]:
  1433. raise ValueError("got bad checksum " + repr(self.recvbuf))
  1434. self.recvbuf = self.recvbuf[4+12+4+4+msglen:]
  1435. if command in self.messagemap:
  1436. f = BytesIO(msg)
  1437. t = self.messagemap[command]()
  1438. t.deserialize(f)
  1439. self.got_message(t)
  1440. else:
  1441. logger.warning("Received unknown command from %s:%d: '%s' %s" % (self.dstaddr, self.dstport, command, repr(msg)))
  1442. except Exception as e:
  1443. logger.exception('got_data:', repr(e))
  1444. def send_message(self, message, pushbuf=False):
  1445. if self.state != "connected" and not pushbuf:
  1446. raise IOError('Not connected, no pushbuf')
  1447. self._log_message("send", message)
  1448. command = message.command
  1449. data = message.serialize()
  1450. tmsg = self.MAGIC_BYTES[self.network]
  1451. tmsg += command
  1452. tmsg += b"\x00" * (12 - len(command))
  1453. tmsg += struct.pack("<I", len(data))
  1454. if self.ver_send >= 209:
  1455. th = sha256(data)
  1456. h = sha256(th)
  1457. tmsg += h[:4]
  1458. tmsg += data
  1459. with mininode_lock:
  1460. self.sendbuf += tmsg
  1461. self.last_sent = time.time()
  1462. def got_message(self, message):
  1463. if message.command == b"version":
  1464. if message.nVersion <= BIP0031_VERSION:
  1465. self.messagemap[b'ping'] = msg_ping_prebip31
  1466. if self.last_sent + 30 * 60 < time.time():
  1467. self.send_message(self.messagemap[b'ping']())
  1468. self._log_message("receive", message)
  1469. self.cb.deliver(self, message)
  1470. def _log_message(self, direction, msg):
  1471. if direction == "send":
  1472. log_message = "Send message to "
  1473. elif direction == "receive":
  1474. log_message = "Received message from "
  1475. log_message += "%s:%d: %s" % (self.dstaddr, self.dstport, repr(msg)[:500])
  1476. if len(log_message) > 500:
  1477. log_message += "... (msg truncated)"
  1478. logger.debug(log_message)
  1479. def disconnect_node(self):
  1480. self.disconnect = True
  1481. class NetworkThread(Thread):
  1482. def run(self):
  1483. while mininode_socket_map:
  1484. # We check for whether to disconnect outside of the asyncore
  1485. # loop to workaround the behavior of asyncore when using
  1486. # select
  1487. disconnected = []
  1488. for fd, obj in mininode_socket_map.items():
  1489. if obj.disconnect:
  1490. disconnected.append(obj)
  1491. [ obj.handle_close() for obj in disconnected ]
  1492. asyncore.loop(0.1, use_poll=True, map=mininode_socket_map, count=1)
  1493. # An exception we can raise if we detect a potential disconnect
  1494. # (p2p or rpc) before the test is complete
  1495. class EarlyDisconnectError(Exception):
  1496. def __init__(self, value):
  1497. self.value = value
  1498. def __str__(self):
  1499. return repr(self.value)