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 54KB

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