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

mininode.py 52KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752
  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. #
  8. # mininode.py - Bitcoin P2P network half-a-node
  9. #
  10. # This python code was modified from ArtForz' public domain half-a-node, as
  11. # found in the mini-node branch of http://github.com/jgarzik/pynode.
  12. #
  13. # NodeConn: an object which manages p2p connectivity to a bitcoin node
  14. # NodeConnCB: a base class that describes the interface for receiving
  15. # callbacks with network messages from a NodeConn
  16. # CBlock, CTransaction, CBlockHeader, CTxIn, CTxOut, etc....:
  17. # data structures that should map to corresponding structures in
  18. # bitcoin/primitives
  19. # msg_block, msg_tx, msg_headers, etc.:
  20. # data structures that represent network messages
  21. # ser_*, deser_*: functions that handle serialization/deserialization
  22. import struct
  23. import socket
  24. import asyncore
  25. import time
  26. import sys
  27. import random
  28. from .util import hex_str_to_bytes, bytes_to_hex_str
  29. from io import BytesIO
  30. from codecs import encode
  31. import hashlib
  32. from threading import RLock
  33. from threading import Thread
  34. import logging
  35. import copy
  36. from test_framework.siphash import siphash256
  37. BIP0031_VERSION = 60000
  38. MY_VERSION = 70014 # past bip-31 for ping/pong
  39. MY_SUBVERSION = b"/python-mininode-tester:0.0.3/"
  40. MAX_INV_SZ = 50000
  41. MAX_BLOCK_SIZE = 1000000
  42. COIN = 100000000 # 1 btc in satoshis
  43. NODE_NETWORK = (1 << 0)
  44. NODE_GETUTXO = (1 << 1)
  45. NODE_BLOOM = (1 << 2)
  46. NODE_WITNESS = (1 << 3)
  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()]*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 nLockTime=%i)" \
  423. % (self.nVersion, repr(self.vin), repr(self.vout), 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. def get_merkle_root(self, hashes):
  501. while len(hashes) > 1:
  502. newhashes = []
  503. for i in range(0, len(hashes), 2):
  504. i2 = min(i+1, len(hashes)-1)
  505. newhashes.append(hash256(hashes[i] + hashes[i2]))
  506. hashes = newhashes
  507. return uint256_from_str(hashes[0])
  508. def calc_merkle_root(self):
  509. hashes = []
  510. for tx in self.vtx:
  511. tx.calc_sha256()
  512. hashes.append(ser_uint256(tx.sha256))
  513. return self.get_merkle_root(hashes)
  514. def calc_witness_merkle_root(self):
  515. # For witness root purposes, the hash of the
  516. # coinbase, with witness, is defined to be 0...0
  517. hashes = [ser_uint256(0)]
  518. for tx in self.vtx[1:]:
  519. # Calculate the hashes with witness data
  520. hashes.append(ser_uint256(tx.calc_sha256(True)))
  521. return self.get_merkle_root(hashes)
  522. def is_valid(self):
  523. self.calc_sha256()
  524. target = uint256_from_compact(self.nBits)
  525. if self.sha256 > target:
  526. return False
  527. for tx in self.vtx:
  528. if not tx.is_valid():
  529. return False
  530. if self.calc_merkle_root() != self.hashMerkleRoot:
  531. return False
  532. return True
  533. def solve(self):
  534. self.rehash()
  535. target = uint256_from_compact(self.nBits)
  536. while self.sha256 > target:
  537. self.nNonce += 1
  538. self.rehash()
  539. def __repr__(self):
  540. return "CBlock(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nBits=%08x nNonce=%08x vtx=%s)" \
  541. % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot,
  542. time.ctime(self.nTime), self.nBits, self.nNonce, repr(self.vtx))
  543. class CUnsignedAlert(object):
  544. def __init__(self):
  545. self.nVersion = 1
  546. self.nRelayUntil = 0
  547. self.nExpiration = 0
  548. self.nID = 0
  549. self.nCancel = 0
  550. self.setCancel = []
  551. self.nMinVer = 0
  552. self.nMaxVer = 0
  553. self.setSubVer = []
  554. self.nPriority = 0
  555. self.strComment = b""
  556. self.strStatusBar = b""
  557. self.strReserved = b""
  558. def deserialize(self, f):
  559. self.nVersion = struct.unpack("<i", f.read(4))[0]
  560. self.nRelayUntil = struct.unpack("<q", f.read(8))[0]
  561. self.nExpiration = struct.unpack("<q", f.read(8))[0]
  562. self.nID = struct.unpack("<i", f.read(4))[0]
  563. self.nCancel = struct.unpack("<i", f.read(4))[0]
  564. self.setCancel = deser_int_vector(f)
  565. self.nMinVer = struct.unpack("<i", f.read(4))[0]
  566. self.nMaxVer = struct.unpack("<i", f.read(4))[0]
  567. self.setSubVer = deser_string_vector(f)
  568. self.nPriority = struct.unpack("<i", f.read(4))[0]
  569. self.strComment = deser_string(f)
  570. self.strStatusBar = deser_string(f)
  571. self.strReserved = deser_string(f)
  572. def serialize(self):
  573. r = b""
  574. r += struct.pack("<i", self.nVersion)
  575. r += struct.pack("<q", self.nRelayUntil)
  576. r += struct.pack("<q", self.nExpiration)
  577. r += struct.pack("<i", self.nID)
  578. r += struct.pack("<i", self.nCancel)
  579. r += ser_int_vector(self.setCancel)
  580. r += struct.pack("<i", self.nMinVer)
  581. r += struct.pack("<i", self.nMaxVer)
  582. r += ser_string_vector(self.setSubVer)
  583. r += struct.pack("<i", self.nPriority)
  584. r += ser_string(self.strComment)
  585. r += ser_string(self.strStatusBar)
  586. r += ser_string(self.strReserved)
  587. return r
  588. def __repr__(self):
  589. return "CUnsignedAlert(nVersion %d, nRelayUntil %d, nExpiration %d, nID %d, nCancel %d, nMinVer %d, nMaxVer %d, nPriority %d, strComment %s, strStatusBar %s, strReserved %s)" \
  590. % (self.nVersion, self.nRelayUntil, self.nExpiration, self.nID,
  591. self.nCancel, self.nMinVer, self.nMaxVer, self.nPriority,
  592. self.strComment, self.strStatusBar, self.strReserved)
  593. class CAlert(object):
  594. def __init__(self):
  595. self.vchMsg = b""
  596. self.vchSig = b""
  597. def deserialize(self, f):
  598. self.vchMsg = deser_string(f)
  599. self.vchSig = deser_string(f)
  600. def serialize(self):
  601. r = b""
  602. r += ser_string(self.vchMsg)
  603. r += ser_string(self.vchSig)
  604. return r
  605. def __repr__(self):
  606. return "CAlert(vchMsg.sz %d, vchSig.sz %d)" \
  607. % (len(self.vchMsg), len(self.vchSig))
  608. class PrefilledTransaction(object):
  609. def __init__(self, index=0, tx = None):
  610. self.index = index
  611. self.tx = tx
  612. def deserialize(self, f):
  613. self.index = deser_compact_size(f)
  614. self.tx = CTransaction()
  615. self.tx.deserialize(f)
  616. def serialize(self, with_witness=False):
  617. r = b""
  618. r += ser_compact_size(self.index)
  619. if with_witness:
  620. r += self.tx.serialize_with_witness()
  621. else:
  622. r += self.tx.serialize_without_witness()
  623. return r
  624. def __repr__(self):
  625. return "PrefilledTransaction(index=%d, tx=%s)" % (self.index, repr(self.tx))
  626. # This is what we send on the wire, in a cmpctblock message.
  627. class P2PHeaderAndShortIDs(object):
  628. def __init__(self):
  629. self.header = CBlockHeader()
  630. self.nonce = 0
  631. self.shortids_length = 0
  632. self.shortids = []
  633. self.prefilled_txn_length = 0
  634. self.prefilled_txn = []
  635. def deserialize(self, f):
  636. self.header.deserialize(f)
  637. self.nonce = struct.unpack("<Q", f.read(8))[0]
  638. self.shortids_length = deser_compact_size(f)
  639. for i in range(self.shortids_length):
  640. # shortids are defined to be 6 bytes in the spec, so append
  641. # two zero bytes and read it in as an 8-byte number
  642. self.shortids.append(struct.unpack("<Q", f.read(6) + b'\x00\x00')[0])
  643. self.prefilled_txn = deser_vector(f, PrefilledTransaction)
  644. self.prefilled_txn_length = len(self.prefilled_txn)
  645. def serialize(self, with_witness=False):
  646. r = b""
  647. r += self.header.serialize()
  648. r += struct.pack("<Q", self.nonce)
  649. r += ser_compact_size(self.shortids_length)
  650. for x in self.shortids:
  651. # We only want the first 6 bytes
  652. r += struct.pack("<Q", x)[0:6]
  653. r += ser_vector(self.prefilled_txn)
  654. return r
  655. def __repr__(self):
  656. 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))
  657. # Calculate the BIP 152-compact blocks shortid for a given transaction hash
  658. def calculate_shortid(k0, k1, tx_hash):
  659. expected_shortid = siphash256(k0, k1, tx_hash)
  660. expected_shortid &= 0x0000ffffffffffff
  661. return expected_shortid
  662. # This version gets rid of the array lengths, and reinterprets the differential
  663. # encoding into indices that can be used for lookup.
  664. class HeaderAndShortIDs(object):
  665. def __init__(self, p2pheaders_and_shortids = None):
  666. self.header = CBlockHeader()
  667. self.nonce = 0
  668. self.shortids = []
  669. self.prefilled_txn = []
  670. if p2pheaders_and_shortids != None:
  671. self.header = p2pheaders_and_shortids.header
  672. self.nonce = p2pheaders_and_shortids.nonce
  673. self.shortids = p2pheaders_and_shortids.shortids
  674. last_index = -1
  675. for x in p2pheaders_and_shortids.prefilled_txn:
  676. self.prefilled_txn.append(PrefilledTransaction(x.index + last_index + 1, x.tx))
  677. last_index = self.prefilled_txn[-1].index
  678. def to_p2p(self):
  679. ret = P2PHeaderAndShortIDs()
  680. ret.header = self.header
  681. ret.nonce = self.nonce
  682. ret.shortids_length = len(self.shortids)
  683. ret.shortids = self.shortids
  684. ret.prefilled_txn_length = len(self.prefilled_txn)
  685. ret.prefilled_txn = []
  686. last_index = -1
  687. for x in self.prefilled_txn:
  688. ret.prefilled_txn.append(PrefilledTransaction(x.index - last_index - 1, x.tx))
  689. last_index = x.index
  690. return ret
  691. def get_siphash_keys(self):
  692. header_nonce = self.header.serialize()
  693. header_nonce += struct.pack("<Q", self.nonce)
  694. hash_header_nonce_as_str = sha256(header_nonce)
  695. key0 = struct.unpack("<Q", hash_header_nonce_as_str[0:8])[0]
  696. key1 = struct.unpack("<Q", hash_header_nonce_as_str[8:16])[0]
  697. return [ key0, key1 ]
  698. def initialize_from_block(self, block, nonce=0, prefill_list = [0]):
  699. self.header = CBlockHeader(block)
  700. self.nonce = nonce
  701. self.prefilled_txn = [ PrefilledTransaction(i, block.vtx[i]) for i in prefill_list ]
  702. self.shortids = []
  703. [k0, k1] = self.get_siphash_keys()
  704. for i in range(len(block.vtx)):
  705. if i not in prefill_list:
  706. self.shortids.append(calculate_shortid(k0, k1, block.vtx[i].sha256))
  707. def __repr__(self):
  708. return "HeaderAndShortIDs(header=%s, nonce=%d, shortids=%s, prefilledtxn=%s" % (repr(self.header), self.nonce, repr(self.shortids), repr(self.prefilled_txn))
  709. class BlockTransactionsRequest(object):
  710. def __init__(self, blockhash=0, indexes = None):
  711. self.blockhash = blockhash
  712. self.indexes = indexes if indexes != None else []
  713. def deserialize(self, f):
  714. self.blockhash = deser_uint256(f)
  715. indexes_length = deser_compact_size(f)
  716. for i in range(indexes_length):
  717. self.indexes.append(deser_compact_size(f))
  718. def serialize(self):
  719. r = b""
  720. r += ser_uint256(self.blockhash)
  721. r += ser_compact_size(len(self.indexes))
  722. for x in self.indexes:
  723. r += ser_compact_size(x)
  724. return r
  725. # helper to set the differentially encoded indexes from absolute ones
  726. def from_absolute(self, absolute_indexes):
  727. self.indexes = []
  728. last_index = -1
  729. for x in absolute_indexes:
  730. self.indexes.append(x-last_index-1)
  731. last_index = x
  732. def to_absolute(self):
  733. absolute_indexes = []
  734. last_index = -1
  735. for x in self.indexes:
  736. absolute_indexes.append(x+last_index+1)
  737. last_index = absolute_indexes[-1]
  738. return absolute_indexes
  739. def __repr__(self):
  740. return "BlockTransactionsRequest(hash=%064x indexes=%s)" % (self.blockhash, repr(self.indexes))
  741. class BlockTransactions(object):
  742. def __init__(self, blockhash=0, transactions = None):
  743. self.blockhash = blockhash
  744. self.transactions = transactions if transactions != None else []
  745. def deserialize(self, f):
  746. self.blockhash = deser_uint256(f)
  747. self.transactions = deser_vector(f, CTransaction)
  748. def serialize(self, with_witness=False):
  749. r = b""
  750. r += ser_uint256(self.blockhash)
  751. if with_witness:
  752. r += ser_vector(self.transactions, "serialize_with_witness")
  753. else:
  754. r += ser_vector(self.transactions)
  755. return r
  756. def __repr__(self):
  757. return "BlockTransactions(hash=%064x transactions=%s)" % (self.blockhash, repr(self.transactions))
  758. # Objects that correspond to messages on the wire
  759. class msg_version(object):
  760. command = b"version"
  761. def __init__(self):
  762. self.nVersion = MY_VERSION
  763. self.nServices = 1
  764. self.nTime = int(time.time())
  765. self.addrTo = CAddress()
  766. self.addrFrom = CAddress()
  767. self.nNonce = random.getrandbits(64)
  768. self.strSubVer = MY_SUBVERSION
  769. self.nStartingHeight = -1
  770. def deserialize(self, f):
  771. self.nVersion = struct.unpack("<i", f.read(4))[0]
  772. if self.nVersion == 10300:
  773. self.nVersion = 300
  774. self.nServices = struct.unpack("<Q", f.read(8))[0]
  775. self.nTime = struct.unpack("<q", f.read(8))[0]
  776. self.addrTo = CAddress()
  777. self.addrTo.deserialize(f)
  778. if self.nVersion >= 106:
  779. self.addrFrom = CAddress()
  780. self.addrFrom.deserialize(f)
  781. self.nNonce = struct.unpack("<Q", f.read(8))[0]
  782. self.strSubVer = deser_string(f)
  783. if self.nVersion >= 209:
  784. self.nStartingHeight = struct.unpack("<i", f.read(4))[0]
  785. else:
  786. self.nStartingHeight = None
  787. else:
  788. self.addrFrom = None
  789. self.nNonce = None
  790. self.strSubVer = None
  791. self.nStartingHeight = None
  792. def serialize(self):
  793. r = b""
  794. r += struct.pack("<i", self.nVersion)
  795. r += struct.pack("<Q", self.nServices)
  796. r += struct.pack("<q", self.nTime)
  797. r += self.addrTo.serialize()
  798. r += self.addrFrom.serialize()
  799. r += struct.pack("<Q", self.nNonce)
  800. r += ser_string(self.strSubVer)
  801. r += struct.pack("<i", self.nStartingHeight)
  802. return r
  803. def __repr__(self):
  804. return 'msg_version(nVersion=%i nServices=%i nTime=%s addrTo=%s addrFrom=%s nNonce=0x%016X strSubVer=%s nStartingHeight=%i)' \
  805. % (self.nVersion, self.nServices, time.ctime(self.nTime),
  806. repr(self.addrTo), repr(self.addrFrom), self.nNonce,
  807. self.strSubVer, self.nStartingHeight)
  808. class msg_verack(object):
  809. command = b"verack"
  810. def __init__(self):
  811. pass
  812. def deserialize(self, f):
  813. pass
  814. def serialize(self):
  815. return b""
  816. def __repr__(self):
  817. return "msg_verack()"
  818. class msg_addr(object):
  819. command = b"addr"
  820. def __init__(self):
  821. self.addrs = []
  822. def deserialize(self, f):
  823. self.addrs = deser_vector(f, CAddress)
  824. def serialize(self):
  825. return ser_vector(self.addrs)
  826. def __repr__(self):
  827. return "msg_addr(addrs=%s)" % (repr(self.addrs))
  828. class msg_alert(object):
  829. command = b"alert"
  830. def __init__(self):
  831. self.alert = CAlert()
  832. def deserialize(self, f):
  833. self.alert = CAlert()
  834. self.alert.deserialize(f)
  835. def serialize(self):
  836. r = b""
  837. r += self.alert.serialize()
  838. return r
  839. def __repr__(self):
  840. return "msg_alert(alert=%s)" % (repr(self.alert), )
  841. class msg_inv(object):
  842. command = b"inv"
  843. def __init__(self, inv=None):
  844. if inv is None:
  845. self.inv = []
  846. else:
  847. self.inv = inv
  848. def deserialize(self, f):
  849. self.inv = deser_vector(f, CInv)
  850. def serialize(self):
  851. return ser_vector(self.inv)
  852. def __repr__(self):
  853. return "msg_inv(inv=%s)" % (repr(self.inv))
  854. class msg_getdata(object):
  855. command = b"getdata"
  856. def __init__(self, inv=None):
  857. self.inv = inv if inv != None else []
  858. def deserialize(self, f):
  859. self.inv = deser_vector(f, CInv)
  860. def serialize(self):
  861. return ser_vector(self.inv)
  862. def __repr__(self):
  863. return "msg_getdata(inv=%s)" % (repr(self.inv))
  864. class msg_getblocks(object):
  865. command = b"getblocks"
  866. def __init__(self):
  867. self.locator = CBlockLocator()
  868. self.hashstop = 0
  869. def deserialize(self, f):
  870. self.locator = CBlockLocator()
  871. self.locator.deserialize(f)
  872. self.hashstop = deser_uint256(f)
  873. def serialize(self):
  874. r = b""
  875. r += self.locator.serialize()
  876. r += ser_uint256(self.hashstop)
  877. return r
  878. def __repr__(self):
  879. return "msg_getblocks(locator=%s hashstop=%064x)" \
  880. % (repr(self.locator), self.hashstop)
  881. class msg_tx(object):
  882. command = b"tx"
  883. def __init__(self, tx=CTransaction()):
  884. self.tx = tx
  885. def deserialize(self, f):
  886. self.tx.deserialize(f)
  887. def serialize(self):
  888. return self.tx.serialize_without_witness()
  889. def __repr__(self):
  890. return "msg_tx(tx=%s)" % (repr(self.tx))
  891. class msg_witness_tx(msg_tx):
  892. def serialize(self):
  893. return self.tx.serialize_with_witness()
  894. class msg_block(object):
  895. command = b"block"
  896. def __init__(self, block=None):
  897. if block is None:
  898. self.block = CBlock()
  899. else:
  900. self.block = block
  901. def deserialize(self, f):
  902. self.block.deserialize(f)
  903. def serialize(self):
  904. return self.block.serialize()
  905. def __repr__(self):
  906. return "msg_block(block=%s)" % (repr(self.block))
  907. # for cases where a user needs tighter control over what is sent over the wire
  908. # note that the user must supply the name of the command, and the data
  909. class msg_generic(object):
  910. def __init__(self, command, data=None):
  911. self.command = command
  912. self.data = data
  913. def serialize(self):
  914. return self.data
  915. def __repr__(self):
  916. return "msg_generic()"
  917. class msg_witness_block(msg_block):
  918. def serialize(self):
  919. r = self.block.serialize(with_witness=True)
  920. return r
  921. class msg_getaddr(object):
  922. command = b"getaddr"
  923. def __init__(self):
  924. pass
  925. def deserialize(self, f):
  926. pass
  927. def serialize(self):
  928. return b""
  929. def __repr__(self):
  930. return "msg_getaddr()"
  931. class msg_ping_prebip31(object):
  932. command = b"ping"
  933. def __init__(self):
  934. pass
  935. def deserialize(self, f):
  936. pass
  937. def serialize(self):
  938. return b""
  939. def __repr__(self):
  940. return "msg_ping() (pre-bip31)"
  941. class msg_ping(object):
  942. command = b"ping"
  943. def __init__(self, nonce=0):
  944. self.nonce = nonce
  945. def deserialize(self, f):
  946. self.nonce = struct.unpack("<Q", f.read(8))[0]
  947. def serialize(self):
  948. r = b""
  949. r += struct.pack("<Q", self.nonce)
  950. return r
  951. def __repr__(self):
  952. return "msg_ping(nonce=%08x)" % self.nonce
  953. class msg_pong(object):
  954. command = b"pong"
  955. def __init__(self, nonce=0):
  956. self.nonce = nonce
  957. def deserialize(self, f):
  958. self.nonce = struct.unpack("<Q", f.read(8))[0]
  959. def serialize(self):
  960. r = b""
  961. r += struct.pack("<Q", self.nonce)
  962. return r
  963. def __repr__(self):
  964. return "msg_pong(nonce=%08x)" % self.nonce
  965. class msg_mempool(object):
  966. command = b"mempool"
  967. def __init__(self):
  968. pass
  969. def deserialize(self, f):
  970. pass
  971. def serialize(self):
  972. return b""
  973. def __repr__(self):
  974. return "msg_mempool()"
  975. class msg_sendheaders(object):
  976. command = b"sendheaders"
  977. def __init__(self):
  978. pass
  979. def deserialize(self, f):
  980. pass
  981. def serialize(self):
  982. return b""
  983. def __repr__(self):
  984. return "msg_sendheaders()"
  985. # getheaders message has
  986. # number of entries
  987. # vector of hashes
  988. # hash_stop (hash of last desired block header, 0 to get as many as possible)
  989. class msg_getheaders(object):
  990. command = b"getheaders"
  991. def __init__(self):
  992. self.locator = CBlockLocator()
  993. self.hashstop = 0
  994. def deserialize(self, f):
  995. self.locator = CBlockLocator()
  996. self.locator.deserialize(f)
  997. self.hashstop = deser_uint256(f)
  998. def serialize(self):
  999. r = b""
  1000. r += self.locator.serialize()
  1001. r += ser_uint256(self.hashstop)
  1002. return r
  1003. def __repr__(self):
  1004. return "msg_getheaders(locator=%s, stop=%064x)" \
  1005. % (repr(self.locator), self.hashstop)
  1006. # headers message has
  1007. # <count> <vector of block headers>
  1008. class msg_headers(object):
  1009. command = b"headers"
  1010. def __init__(self):
  1011. self.headers = []
  1012. def deserialize(self, f):
  1013. # comment in bitcoind indicates these should be deserialized as blocks
  1014. blocks = deser_vector(f, CBlock)
  1015. for x in blocks:
  1016. self.headers.append(CBlockHeader(x))
  1017. def serialize(self):
  1018. blocks = [CBlock(x) for x in self.headers]
  1019. return ser_vector(blocks)
  1020. def __repr__(self):
  1021. return "msg_headers(headers=%s)" % repr(self.headers)
  1022. class msg_reject(object):
  1023. command = b"reject"
  1024. REJECT_MALFORMED = 1
  1025. def __init__(self):
  1026. self.message = b""
  1027. self.code = 0
  1028. self.reason = b""
  1029. self.data = 0
  1030. def deserialize(self, f):
  1031. self.message = deser_string(f)
  1032. self.code = struct.unpack("<B", f.read(1))[0]
  1033. self.reason = deser_string(f)
  1034. if (self.code != self.REJECT_MALFORMED and
  1035. (self.message == b"block" or self.message == b"tx")):
  1036. self.data = deser_uint256(f)
  1037. def serialize(self):
  1038. r = ser_string(self.message)
  1039. r += struct.pack("<B", self.code)
  1040. r += ser_string(self.reason)
  1041. if (self.code != self.REJECT_MALFORMED and
  1042. (self.message == b"block" or self.message == b"tx")):
  1043. r += ser_uint256(self.data)
  1044. return r
  1045. def __repr__(self):
  1046. return "msg_reject: %s %d %s [%064x]" \
  1047. % (self.message, self.code, self.reason, self.data)
  1048. # Helper function
  1049. def wait_until(predicate, attempts=float('inf'), timeout=float('inf')):
  1050. attempt = 0
  1051. elapsed = 0
  1052. while attempt < attempts and elapsed < timeout:
  1053. with mininode_lock:
  1054. if predicate():
  1055. return True
  1056. attempt += 1
  1057. elapsed += 0.05
  1058. time.sleep(0.05)
  1059. return False
  1060. class msg_feefilter(object):
  1061. command = b"feefilter"
  1062. def __init__(self, feerate=0):
  1063. self.feerate = feerate
  1064. def deserialize(self, f):
  1065. self.feerate = struct.unpack("<Q", f.read(8))[0]
  1066. def serialize(self):
  1067. r = b""
  1068. r += struct.pack("<Q", self.feerate)
  1069. return r
  1070. def __repr__(self):
  1071. return "msg_feefilter(feerate=%08x)" % self.feerate
  1072. class msg_sendcmpct(object):
  1073. command = b"sendcmpct"
  1074. def __init__(self):
  1075. self.announce = False
  1076. self.version = 1
  1077. def deserialize(self, f):
  1078. self.announce = struct.unpack("<?", f.read(1))[0]
  1079. self.version = struct.unpack("<Q", f.read(8))[0]
  1080. def serialize(self):
  1081. r = b""
  1082. r += struct.pack("<?", self.announce)
  1083. r += struct.pack("<Q", self.version)
  1084. return r
  1085. def __repr__(self):
  1086. return "msg_sendcmpct(announce=%s, version=%lu)" % (self.announce, self.version)
  1087. class msg_cmpctblock(object):
  1088. command = b"cmpctblock"
  1089. def __init__(self, header_and_shortids = None):
  1090. self.header_and_shortids = header_and_shortids
  1091. def deserialize(self, f):
  1092. self.header_and_shortids = P2PHeaderAndShortIDs()
  1093. self.header_and_shortids.deserialize(f)
  1094. def serialize(self):
  1095. r = b""
  1096. r += self.header_and_shortids.serialize()
  1097. return r
  1098. def __repr__(self):
  1099. return "msg_cmpctblock(HeaderAndShortIDs=%s)" % repr(self.header_and_shortids)
  1100. class msg_getblocktxn(object):
  1101. command = b"getblocktxn"
  1102. def __init__(self):
  1103. self.block_txn_request = None
  1104. def deserialize(self, f):
  1105. self.block_txn_request = BlockTransactionsRequest()
  1106. self.block_txn_request.deserialize(f)
  1107. def serialize(self):
  1108. r = b""
  1109. r += self.block_txn_request.serialize()
  1110. return r
  1111. def __repr__(self):
  1112. return "msg_getblocktxn(block_txn_request=%s)" % (repr(self.block_txn_request))
  1113. class msg_blocktxn(object):
  1114. command = b"blocktxn"
  1115. def __init__(self):
  1116. self.block_transactions = BlockTransactions()
  1117. def deserialize(self, f):
  1118. self.block_transactions.deserialize(f)
  1119. def serialize(self):
  1120. r = b""
  1121. r += self.block_transactions.serialize()
  1122. return r
  1123. def __repr__(self):
  1124. return "msg_blocktxn(block_transactions=%s)" % (repr(self.block_transactions))
  1125. # This is what a callback should look like for NodeConn
  1126. # Reimplement the on_* functions to provide handling for events
  1127. class NodeConnCB(object):
  1128. def __init__(self):
  1129. self.verack_received = False
  1130. # deliver_sleep_time is helpful for debugging race conditions in p2p
  1131. # tests; it causes message delivery to sleep for the specified time
  1132. # before acquiring the global lock and delivering the next message.
  1133. self.deliver_sleep_time = None
  1134. # Remember the services our peer has advertised
  1135. self.peer_services = None
  1136. def set_deliver_sleep_time(self, value):
  1137. with mininode_lock:
  1138. self.deliver_sleep_time = value
  1139. def get_deliver_sleep_time(self):
  1140. with mininode_lock:
  1141. return self.deliver_sleep_time
  1142. # Spin until verack message is received from the node.
  1143. # Tests may want to use this as a signal that the test can begin.
  1144. # This can be called from the testing thread, so it needs to acquire the
  1145. # global lock.
  1146. def wait_for_verack(self):
  1147. while True:
  1148. with mininode_lock:
  1149. if self.verack_received:
  1150. return
  1151. time.sleep(0.05)
  1152. def deliver(self, conn, message):
  1153. deliver_sleep = self.get_deliver_sleep_time()
  1154. if deliver_sleep is not None:
  1155. time.sleep(deliver_sleep)
  1156. with mininode_lock:
  1157. try:
  1158. getattr(self, 'on_' + message.command.decode('ascii'))(conn, message)
  1159. except:
  1160. print("ERROR delivering %s (%s)" % (repr(message),
  1161. sys.exc_info()[0]))
  1162. def on_version(self, conn, message):
  1163. if message.nVersion >= 209:
  1164. conn.send_message(msg_verack())
  1165. conn.ver_send = min(MY_VERSION, message.nVersion)
  1166. if message.nVersion < 209:
  1167. conn.ver_recv = conn.ver_send
  1168. conn.nServices = message.nServices
  1169. def on_verack(self, conn, message):
  1170. conn.ver_recv = conn.ver_send
  1171. self.verack_received = True
  1172. def on_inv(self, conn, message):
  1173. want = msg_getdata()
  1174. for i in message.inv:
  1175. if i.type != 0:
  1176. want.inv.append(i)
  1177. if len(want.inv):
  1178. conn.send_message(want)
  1179. def on_addr(self, conn, message): pass
  1180. def on_alert(self, conn, message): pass
  1181. def on_getdata(self, conn, message): pass
  1182. def on_getblocks(self, conn, message): pass
  1183. def on_tx(self, conn, message): pass
  1184. def on_block(self, conn, message): pass
  1185. def on_getaddr(self, conn, message): pass
  1186. def on_headers(self, conn, message): pass
  1187. def on_getheaders(self, conn, message): pass
  1188. def on_ping(self, conn, message):
  1189. if conn.ver_send > BIP0031_VERSION:
  1190. conn.send_message(msg_pong(message.nonce))
  1191. def on_reject(self, conn, message): pass
  1192. def on_close(self, conn): pass
  1193. def on_mempool(self, conn): pass
  1194. def on_pong(self, conn, message): pass
  1195. def on_feefilter(self, conn, message): pass
  1196. def on_sendheaders(self, conn, message): pass
  1197. def on_sendcmpct(self, conn, message): pass
  1198. def on_cmpctblock(self, conn, message): pass
  1199. def on_getblocktxn(self, conn, message): pass
  1200. def on_blocktxn(self, conn, message): pass
  1201. # More useful callbacks and functions for NodeConnCB's which have a single NodeConn
  1202. class SingleNodeConnCB(NodeConnCB):
  1203. def __init__(self):
  1204. NodeConnCB.__init__(self)
  1205. self.connection = None
  1206. self.ping_counter = 1
  1207. self.last_pong = msg_pong()
  1208. def add_connection(self, conn):
  1209. self.connection = conn
  1210. # Wrapper for the NodeConn's send_message function
  1211. def send_message(self, message):
  1212. self.connection.send_message(message)
  1213. def send_and_ping(self, message):
  1214. self.send_message(message)
  1215. self.sync_with_ping()
  1216. def on_pong(self, conn, message):
  1217. self.last_pong = message
  1218. # Sync up with the node
  1219. def sync_with_ping(self, timeout=30):
  1220. def received_pong():
  1221. return (self.last_pong.nonce == self.ping_counter)
  1222. self.send_message(msg_ping(nonce=self.ping_counter))
  1223. success = wait_until(received_pong, timeout=timeout)
  1224. self.ping_counter += 1
  1225. return success
  1226. # The actual NodeConn class
  1227. # This class provides an interface for a p2p connection to a specified node
  1228. class NodeConn(asyncore.dispatcher):
  1229. messagemap = {
  1230. b"version": msg_version,
  1231. b"verack": msg_verack,
  1232. b"addr": msg_addr,
  1233. b"alert": msg_alert,
  1234. b"inv": msg_inv,
  1235. b"getdata": msg_getdata,
  1236. b"getblocks": msg_getblocks,
  1237. b"tx": msg_tx,
  1238. b"block": msg_block,
  1239. b"getaddr": msg_getaddr,
  1240. b"ping": msg_ping,
  1241. b"pong": msg_pong,
  1242. b"headers": msg_headers,
  1243. b"getheaders": msg_getheaders,
  1244. b"reject": msg_reject,
  1245. b"mempool": msg_mempool,
  1246. b"feefilter": msg_feefilter,
  1247. b"sendheaders": msg_sendheaders,
  1248. b"sendcmpct": msg_sendcmpct,
  1249. b"cmpctblock": msg_cmpctblock,
  1250. b"getblocktxn": msg_getblocktxn,
  1251. b"blocktxn": msg_blocktxn
  1252. }
  1253. MAGIC_BYTES = {
  1254. "mainnet": b"\xf9\xbe\xb4\xd9", # mainnet
  1255. "testnet3": b"\x0b\x11\x09\x07", # testnet3
  1256. "regtest": b"\xfa\xbf\xb5\xda", # regtest
  1257. }
  1258. def __init__(self, dstaddr, dstport, rpc, callback, net="regtest", services=NODE_NETWORK):
  1259. asyncore.dispatcher.__init__(self, map=mininode_socket_map)
  1260. self.log = logging.getLogger("NodeConn(%s:%d)" % (dstaddr, dstport))
  1261. self.dstaddr = dstaddr
  1262. self.dstport = dstport
  1263. self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
  1264. self.sendbuf = b""
  1265. self.recvbuf = b""
  1266. self.ver_send = 209
  1267. self.ver_recv = 209
  1268. self.last_sent = 0
  1269. self.state = "connecting"
  1270. self.network = net
  1271. self.cb = callback
  1272. self.disconnect = False
  1273. self.nServices = 0
  1274. # stuff version msg into sendbuf
  1275. vt = msg_version()
  1276. vt.nServices = services
  1277. vt.addrTo.ip = self.dstaddr
  1278. vt.addrTo.port = self.dstport
  1279. vt.addrFrom.ip = "0.0.0.0"
  1280. vt.addrFrom.port = 0
  1281. self.send_message(vt, True)
  1282. print('MiniNode: Connecting to Bitcoin Node IP # ' + dstaddr + ':' \
  1283. + str(dstport))
  1284. try:
  1285. self.connect((dstaddr, dstport))
  1286. except:
  1287. self.handle_close()
  1288. self.rpc = rpc
  1289. def show_debug_msg(self, msg):
  1290. self.log.debug(msg)
  1291. def handle_connect(self):
  1292. self.show_debug_msg("MiniNode: Connected & Listening: \n")
  1293. self.state = "connected"
  1294. def handle_close(self):
  1295. self.show_debug_msg("MiniNode: Closing Connection to %s:%d... "
  1296. % (self.dstaddr, self.dstport))
  1297. self.state = "closed"
  1298. self.recvbuf = b""
  1299. self.sendbuf = b""
  1300. try:
  1301. self.close()
  1302. except:
  1303. pass
  1304. self.cb.on_close(self)
  1305. def handle_read(self):
  1306. try:
  1307. t = self.recv(8192)
  1308. if len(t) > 0:
  1309. self.recvbuf += t
  1310. self.got_data()
  1311. except:
  1312. pass
  1313. def readable(self):
  1314. return True
  1315. def writable(self):
  1316. with mininode_lock:
  1317. length = len(self.sendbuf)
  1318. return (length > 0)
  1319. def handle_write(self):
  1320. with mininode_lock:
  1321. try:
  1322. sent = self.send(self.sendbuf)
  1323. except:
  1324. self.handle_close()
  1325. return
  1326. self.sendbuf = self.sendbuf[sent:]
  1327. def got_data(self):
  1328. try:
  1329. while True:
  1330. if len(self.recvbuf) < 4:
  1331. return
  1332. if self.recvbuf[:4] != self.MAGIC_BYTES[self.network]:
  1333. raise ValueError("got garbage %s" % repr(self.recvbuf))
  1334. if self.ver_recv < 209:
  1335. if len(self.recvbuf) < 4 + 12 + 4:
  1336. return
  1337. command = self.recvbuf[4:4+12].split(b"\x00", 1)[0]
  1338. msglen = struct.unpack("<i", self.recvbuf[4+12:4+12+4])[0]
  1339. checksum = None
  1340. if len(self.recvbuf) < 4 + 12 + 4 + msglen:
  1341. return
  1342. msg = self.recvbuf[4+12+4:4+12+4+msglen]
  1343. self.recvbuf = self.recvbuf[4+12+4+msglen:]
  1344. else:
  1345. if len(self.recvbuf) < 4 + 12 + 4 + 4:
  1346. return
  1347. command = self.recvbuf[4:4+12].split(b"\x00", 1)[0]
  1348. msglen = struct.unpack("<i", self.recvbuf[4+12:4+12+4])[0]
  1349. checksum = self.recvbuf[4+12+4:4+12+4+4]
  1350. if len(self.recvbuf) < 4 + 12 + 4 + 4 + msglen:
  1351. return
  1352. msg = self.recvbuf[4+12+4+4:4+12+4+4+msglen]
  1353. th = sha256(msg)
  1354. h = sha256(th)
  1355. if checksum != h[:4]:
  1356. raise ValueError("got bad checksum " + repr(self.recvbuf))
  1357. self.recvbuf = self.recvbuf[4+12+4+4+msglen:]
  1358. if command in self.messagemap:
  1359. f = BytesIO(msg)
  1360. t = self.messagemap[command]()
  1361. t.deserialize(f)
  1362. self.got_message(t)
  1363. else:
  1364. self.show_debug_msg("Unknown command: '" + command + "' " +
  1365. repr(msg))
  1366. except Exception as e:
  1367. print('got_data:', repr(e))
  1368. # import traceback
  1369. # traceback.print_tb(sys.exc_info()[2])
  1370. def send_message(self, message, pushbuf=False):
  1371. if self.state != "connected" and not pushbuf:
  1372. raise IOError('Not connected, no pushbuf')
  1373. self.show_debug_msg("Send %s" % repr(message))
  1374. command = message.command
  1375. data = message.serialize()
  1376. tmsg = self.MAGIC_BYTES[self.network]
  1377. tmsg += command
  1378. tmsg += b"\x00" * (12 - len(command))
  1379. tmsg += struct.pack("<I", len(data))
  1380. if self.ver_send >= 209:
  1381. th = sha256(data)
  1382. h = sha256(th)
  1383. tmsg += h[:4]
  1384. tmsg += data
  1385. with mininode_lock:
  1386. self.sendbuf += tmsg
  1387. self.last_sent = time.time()
  1388. def got_message(self, message):
  1389. if message.command == b"version":
  1390. if message.nVersion <= BIP0031_VERSION:
  1391. self.messagemap[b'ping'] = msg_ping_prebip31
  1392. if self.last_sent + 30 * 60 < time.time():
  1393. self.send_message(self.messagemap[b'ping']())
  1394. self.show_debug_msg("Recv %s" % repr(message))
  1395. self.cb.deliver(self, message)
  1396. def disconnect_node(self):
  1397. self.disconnect = True
  1398. class NetworkThread(Thread):
  1399. def run(self):
  1400. while mininode_socket_map:
  1401. # We check for whether to disconnect outside of the asyncore
  1402. # loop to workaround the behavior of asyncore when using
  1403. # select
  1404. disconnected = []
  1405. for fd, obj in mininode_socket_map.items():
  1406. if obj.disconnect:
  1407. disconnected.append(obj)
  1408. [ obj.handle_close() for obj in disconnected ]
  1409. asyncore.loop(0.1, use_poll=True, map=mininode_socket_map, count=1)
  1410. # An exception we can raise if we detect a potential disconnect
  1411. # (p2p or rpc) before the test is complete
  1412. class EarlyDisconnectError(Exception):
  1413. def __init__(self, value):
  1414. self.value = value
  1415. def __str__(self):
  1416. return repr(self.value)