選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

mininode.py 56KB

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