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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276
  1. # mininode.py - Bitcoin P2P network half-a-node
  2. #
  3. # Distributed under the MIT/X11 software license, see the accompanying
  4. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #
  6. # This python code was modified from ArtForz' public domain half-a-node, as
  7. # found in the mini-node branch of http://github.com/jgarzik/pynode.
  8. #
  9. # NodeConn: an object which manages p2p connectivity to a bitcoin node
  10. # NodeConnCB: a base class that describes the interface for receiving
  11. # callbacks with network messages from a NodeConn
  12. # CBlock, CTransaction, CBlockHeader, CTxIn, CTxOut, etc....:
  13. # data structures that should map to corresponding structures in
  14. # bitcoin/primitives
  15. # msg_block, msg_tx, msg_headers, etc.:
  16. # data structures that represent network messages
  17. # ser_*, deser_*: functions that handle serialization/deserialization
  18. import struct
  19. import socket
  20. import asyncore
  21. import binascii
  22. import time
  23. import sys
  24. import random
  25. import cStringIO
  26. import hashlib
  27. from threading import RLock
  28. from threading import Thread
  29. import logging
  30. import copy
  31. BIP0031_VERSION = 60000
  32. MY_VERSION = 60001 # past bip-31 for ping/pong
  33. MY_SUBVERSION = "/python-mininode-tester:0.0.1/"
  34. MAX_INV_SZ = 50000
  35. MAX_BLOCK_SIZE = 1000000
  36. # Keep our own socket map for asyncore, so that we can track disconnects
  37. # ourselves (to workaround an issue with closing an asyncore socket when
  38. # using select)
  39. mininode_socket_map = dict()
  40. # One lock for synchronizing all data access between the networking thread (see
  41. # NetworkThread below) and the thread running the test logic. For simplicity,
  42. # NodeConn acquires this lock whenever delivering a message to to a NodeConnCB,
  43. # and whenever adding anything to the send buffer (in send_message()). This
  44. # lock should be acquired in the thread running the test logic to synchronize
  45. # access to any data shared with the NodeConnCB or NodeConn.
  46. mininode_lock = RLock()
  47. # Serialization/deserialization tools
  48. def sha256(s):
  49. return hashlib.new('sha256', s).digest()
  50. def hash256(s):
  51. return sha256(sha256(s))
  52. def deser_string(f):
  53. nit = struct.unpack("<B", f.read(1))[0]
  54. if nit == 253:
  55. nit = struct.unpack("<H", f.read(2))[0]
  56. elif nit == 254:
  57. nit = struct.unpack("<I", f.read(4))[0]
  58. elif nit == 255:
  59. nit = struct.unpack("<Q", f.read(8))[0]
  60. return f.read(nit)
  61. def ser_string(s):
  62. if len(s) < 253:
  63. return chr(len(s)) + s
  64. elif len(s) < 0x10000:
  65. return chr(253) + struct.pack("<H", len(s)) + s
  66. elif len(s) < 0x100000000L:
  67. return chr(254) + struct.pack("<I", len(s)) + s
  68. return chr(255) + struct.pack("<Q", len(s)) + s
  69. def deser_uint256(f):
  70. r = 0L
  71. for i in xrange(8):
  72. t = struct.unpack("<I", f.read(4))[0]
  73. r += t << (i * 32)
  74. return r
  75. def ser_uint256(u):
  76. rs = ""
  77. for i in xrange(8):
  78. rs += struct.pack("<I", u & 0xFFFFFFFFL)
  79. u >>= 32
  80. return rs
  81. def uint256_from_str(s):
  82. r = 0L
  83. t = struct.unpack("<IIIIIIII", s[:32])
  84. for i in xrange(8):
  85. r += t[i] << (i * 32)
  86. return r
  87. def uint256_from_compact(c):
  88. nbytes = (c >> 24) & 0xFF
  89. v = (c & 0xFFFFFFL) << (8 * (nbytes - 3))
  90. return v
  91. def deser_vector(f, c):
  92. nit = struct.unpack("<B", f.read(1))[0]
  93. if nit == 253:
  94. nit = struct.unpack("<H", f.read(2))[0]
  95. elif nit == 254:
  96. nit = struct.unpack("<I", f.read(4))[0]
  97. elif nit == 255:
  98. nit = struct.unpack("<Q", f.read(8))[0]
  99. r = []
  100. for i in xrange(nit):
  101. t = c()
  102. t.deserialize(f)
  103. r.append(t)
  104. return r
  105. def ser_vector(l):
  106. r = ""
  107. if len(l) < 253:
  108. r = chr(len(l))
  109. elif len(l) < 0x10000:
  110. r = chr(253) + struct.pack("<H", len(l))
  111. elif len(l) < 0x100000000L:
  112. r = chr(254) + struct.pack("<I", len(l))
  113. else:
  114. r = chr(255) + struct.pack("<Q", len(l))
  115. for i in l:
  116. r += i.serialize()
  117. return r
  118. def deser_uint256_vector(f):
  119. nit = struct.unpack("<B", f.read(1))[0]
  120. if nit == 253:
  121. nit = struct.unpack("<H", f.read(2))[0]
  122. elif nit == 254:
  123. nit = struct.unpack("<I", f.read(4))[0]
  124. elif nit == 255:
  125. nit = struct.unpack("<Q", f.read(8))[0]
  126. r = []
  127. for i in xrange(nit):
  128. t = deser_uint256(f)
  129. r.append(t)
  130. return r
  131. def ser_uint256_vector(l):
  132. r = ""
  133. if len(l) < 253:
  134. r = chr(len(l))
  135. elif len(l) < 0x10000:
  136. r = chr(253) + struct.pack("<H", len(l))
  137. elif len(l) < 0x100000000L:
  138. r = chr(254) + struct.pack("<I", len(l))
  139. else:
  140. r = chr(255) + struct.pack("<Q", len(l))
  141. for i in l:
  142. r += ser_uint256(i)
  143. return r
  144. def deser_string_vector(f):
  145. nit = struct.unpack("<B", f.read(1))[0]
  146. if nit == 253:
  147. nit = struct.unpack("<H", f.read(2))[0]
  148. elif nit == 254:
  149. nit = struct.unpack("<I", f.read(4))[0]
  150. elif nit == 255:
  151. nit = struct.unpack("<Q", f.read(8))[0]
  152. r = []
  153. for i in xrange(nit):
  154. t = deser_string(f)
  155. r.append(t)
  156. return r
  157. def ser_string_vector(l):
  158. r = ""
  159. if len(l) < 253:
  160. r = chr(len(l))
  161. elif len(l) < 0x10000:
  162. r = chr(253) + struct.pack("<H", len(l))
  163. elif len(l) < 0x100000000L:
  164. r = chr(254) + struct.pack("<I", len(l))
  165. else:
  166. r = chr(255) + struct.pack("<Q", len(l))
  167. for sv in l:
  168. r += ser_string(sv)
  169. return r
  170. def deser_int_vector(f):
  171. nit = struct.unpack("<B", f.read(1))[0]
  172. if nit == 253:
  173. nit = struct.unpack("<H", f.read(2))[0]
  174. elif nit == 254:
  175. nit = struct.unpack("<I", f.read(4))[0]
  176. elif nit == 255:
  177. nit = struct.unpack("<Q", f.read(8))[0]
  178. r = []
  179. for i in xrange(nit):
  180. t = struct.unpack("<i", f.read(4))[0]
  181. r.append(t)
  182. return r
  183. def ser_int_vector(l):
  184. r = ""
  185. if len(l) < 253:
  186. r = chr(len(l))
  187. elif len(l) < 0x10000:
  188. r = chr(253) + struct.pack("<H", len(l))
  189. elif len(l) < 0x100000000L:
  190. r = chr(254) + struct.pack("<I", len(l))
  191. else:
  192. r = chr(255) + struct.pack("<Q", len(l))
  193. for i in l:
  194. r += struct.pack("<i", i)
  195. return r
  196. # Objects that map to bitcoind objects, which can be serialized/deserialized
  197. class CAddress(object):
  198. def __init__(self):
  199. self.nServices = 1
  200. self.pchReserved = "\x00" * 10 + "\xff" * 2
  201. self.ip = "0.0.0.0"
  202. self.port = 0
  203. def deserialize(self, f):
  204. self.nServices = struct.unpack("<Q", f.read(8))[0]
  205. self.pchReserved = f.read(12)
  206. self.ip = socket.inet_ntoa(f.read(4))
  207. self.port = struct.unpack(">H", f.read(2))[0]
  208. def serialize(self):
  209. r = ""
  210. r += struct.pack("<Q", self.nServices)
  211. r += self.pchReserved
  212. r += socket.inet_aton(self.ip)
  213. r += struct.pack(">H", self.port)
  214. return r
  215. def __repr__(self):
  216. return "CAddress(nServices=%i ip=%s port=%i)" % (self.nServices,
  217. self.ip, self.port)
  218. class CInv(object):
  219. typemap = {
  220. 0: "Error",
  221. 1: "TX",
  222. 2: "Block"}
  223. def __init__(self, t=0, h=0L):
  224. self.type = t
  225. self.hash = h
  226. def deserialize(self, f):
  227. self.type = struct.unpack("<i", f.read(4))[0]
  228. self.hash = deser_uint256(f)
  229. def serialize(self):
  230. r = ""
  231. r += struct.pack("<i", self.type)
  232. r += ser_uint256(self.hash)
  233. return r
  234. def __repr__(self):
  235. return "CInv(type=%s hash=%064x)" \
  236. % (self.typemap[self.type], self.hash)
  237. class CBlockLocator(object):
  238. def __init__(self):
  239. self.nVersion = MY_VERSION
  240. self.vHave = []
  241. def deserialize(self, f):
  242. self.nVersion = struct.unpack("<i", f.read(4))[0]
  243. self.vHave = deser_uint256_vector(f)
  244. def serialize(self):
  245. r = ""
  246. r += struct.pack("<i", self.nVersion)
  247. r += ser_uint256_vector(self.vHave)
  248. return r
  249. def __repr__(self):
  250. return "CBlockLocator(nVersion=%i vHave=%s)" \
  251. % (self.nVersion, repr(self.vHave))
  252. class COutPoint(object):
  253. def __init__(self, hash=0, n=0):
  254. self.hash = hash
  255. self.n = n
  256. def deserialize(self, f):
  257. self.hash = deser_uint256(f)
  258. self.n = struct.unpack("<I", f.read(4))[0]
  259. def serialize(self):
  260. r = ""
  261. r += ser_uint256(self.hash)
  262. r += struct.pack("<I", self.n)
  263. return r
  264. def __repr__(self):
  265. return "COutPoint(hash=%064x n=%i)" % (self.hash, self.n)
  266. class CTxIn(object):
  267. def __init__(self, outpoint=None, scriptSig="", nSequence=0):
  268. if outpoint is None:
  269. self.prevout = COutPoint()
  270. else:
  271. self.prevout = outpoint
  272. self.scriptSig = scriptSig
  273. self.nSequence = nSequence
  274. def deserialize(self, f):
  275. self.prevout = COutPoint()
  276. self.prevout.deserialize(f)
  277. self.scriptSig = deser_string(f)
  278. self.nSequence = struct.unpack("<I", f.read(4))[0]
  279. def serialize(self):
  280. r = ""
  281. r += self.prevout.serialize()
  282. r += ser_string(self.scriptSig)
  283. r += struct.pack("<I", self.nSequence)
  284. return r
  285. def __repr__(self):
  286. return "CTxIn(prevout=%s scriptSig=%s nSequence=%i)" \
  287. % (repr(self.prevout), binascii.hexlify(self.scriptSig),
  288. self.nSequence)
  289. class CTxOut(object):
  290. def __init__(self, nValue=0, scriptPubKey=""):
  291. self.nValue = nValue
  292. self.scriptPubKey = scriptPubKey
  293. def deserialize(self, f):
  294. self.nValue = struct.unpack("<q", f.read(8))[0]
  295. self.scriptPubKey = deser_string(f)
  296. def serialize(self):
  297. r = ""
  298. r += struct.pack("<q", self.nValue)
  299. r += ser_string(self.scriptPubKey)
  300. return r
  301. def __repr__(self):
  302. return "CTxOut(nValue=%i.%08i scriptPubKey=%s)" \
  303. % (self.nValue // 100000000, self.nValue % 100000000,
  304. binascii.hexlify(self.scriptPubKey))
  305. class CTransaction(object):
  306. def __init__(self, tx=None):
  307. if tx is None:
  308. self.nVersion = 1
  309. self.vin = []
  310. self.vout = []
  311. self.nLockTime = 0
  312. self.sha256 = None
  313. self.hash = None
  314. else:
  315. self.nVersion = tx.nVersion
  316. self.vin = copy.deepcopy(tx.vin)
  317. self.vout = copy.deepcopy(tx.vout)
  318. self.nLockTime = tx.nLockTime
  319. self.sha256 = None
  320. self.hash = None
  321. def deserialize(self, f):
  322. self.nVersion = struct.unpack("<i", f.read(4))[0]
  323. self.vin = deser_vector(f, CTxIn)
  324. self.vout = deser_vector(f, CTxOut)
  325. self.nLockTime = struct.unpack("<I", f.read(4))[0]
  326. self.sha256 = None
  327. self.hash = None
  328. def serialize(self):
  329. r = ""
  330. r += struct.pack("<i", self.nVersion)
  331. r += ser_vector(self.vin)
  332. r += ser_vector(self.vout)
  333. r += struct.pack("<I", self.nLockTime)
  334. return r
  335. def rehash(self):
  336. self.sha256 = None
  337. self.calc_sha256()
  338. def calc_sha256(self):
  339. if self.sha256 is None:
  340. self.sha256 = uint256_from_str(hash256(self.serialize()))
  341. self.hash = hash256(self.serialize())[::-1].encode('hex_codec')
  342. def is_valid(self):
  343. self.calc_sha256()
  344. for tout in self.vout:
  345. if tout.nValue < 0 or tout.nValue > 21000000L * 100000000L:
  346. return False
  347. return True
  348. def __repr__(self):
  349. return "CTransaction(nVersion=%i vin=%s vout=%s nLockTime=%i)" \
  350. % (self.nVersion, repr(self.vin), repr(self.vout), self.nLockTime)
  351. class CBlockHeader(object):
  352. def __init__(self, header=None):
  353. if header is None:
  354. self.set_null()
  355. else:
  356. self.nVersion = header.nVersion
  357. self.hashPrevBlock = header.hashPrevBlock
  358. self.hashMerkleRoot = header.hashMerkleRoot
  359. self.nTime = header.nTime
  360. self.nBits = header.nBits
  361. self.nNonce = header.nNonce
  362. self.sha256 = header.sha256
  363. self.hash = header.hash
  364. self.calc_sha256()
  365. def set_null(self):
  366. self.nVersion = 1
  367. self.hashPrevBlock = 0
  368. self.hashMerkleRoot = 0
  369. self.nTime = 0
  370. self.nBits = 0
  371. self.nNonce = 0
  372. self.sha256 = None
  373. self.hash = None
  374. def deserialize(self, f):
  375. self.nVersion = struct.unpack("<i", f.read(4))[0]
  376. self.hashPrevBlock = deser_uint256(f)
  377. self.hashMerkleRoot = deser_uint256(f)
  378. self.nTime = struct.unpack("<I", f.read(4))[0]
  379. self.nBits = struct.unpack("<I", f.read(4))[0]
  380. self.nNonce = struct.unpack("<I", f.read(4))[0]
  381. self.sha256 = None
  382. self.hash = None
  383. def serialize(self):
  384. r = ""
  385. r += struct.pack("<i", self.nVersion)
  386. r += ser_uint256(self.hashPrevBlock)
  387. r += ser_uint256(self.hashMerkleRoot)
  388. r += struct.pack("<I", self.nTime)
  389. r += struct.pack("<I", self.nBits)
  390. r += struct.pack("<I", self.nNonce)
  391. return r
  392. def calc_sha256(self):
  393. if self.sha256 is None:
  394. r = ""
  395. r += struct.pack("<i", self.nVersion)
  396. r += ser_uint256(self.hashPrevBlock)
  397. r += ser_uint256(self.hashMerkleRoot)
  398. r += struct.pack("<I", self.nTime)
  399. r += struct.pack("<I", self.nBits)
  400. r += struct.pack("<I", self.nNonce)
  401. self.sha256 = uint256_from_str(hash256(r))
  402. self.hash = hash256(r)[::-1].encode('hex_codec')
  403. def rehash(self):
  404. self.sha256 = None
  405. self.calc_sha256()
  406. return self.sha256
  407. def __repr__(self):
  408. return "CBlockHeader(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nBits=%08x nNonce=%08x)" \
  409. % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot,
  410. time.ctime(self.nTime), self.nBits, self.nNonce)
  411. class CBlock(CBlockHeader):
  412. def __init__(self, header=None):
  413. super(CBlock, self).__init__(header)
  414. self.vtx = []
  415. def deserialize(self, f):
  416. super(CBlock, self).deserialize(f)
  417. self.vtx = deser_vector(f, CTransaction)
  418. def serialize(self):
  419. r = ""
  420. r += super(CBlock, self).serialize()
  421. r += ser_vector(self.vtx)
  422. return r
  423. def calc_merkle_root(self):
  424. hashes = []
  425. for tx in self.vtx:
  426. tx.calc_sha256()
  427. hashes.append(ser_uint256(tx.sha256))
  428. while len(hashes) > 1:
  429. newhashes = []
  430. for i in xrange(0, len(hashes), 2):
  431. i2 = min(i+1, len(hashes)-1)
  432. newhashes.append(hash256(hashes[i] + hashes[i2]))
  433. hashes = newhashes
  434. return uint256_from_str(hashes[0])
  435. def is_valid(self):
  436. self.calc_sha256()
  437. target = uint256_from_compact(self.nBits)
  438. if self.sha256 > target:
  439. return False
  440. for tx in self.vtx:
  441. if not tx.is_valid():
  442. return False
  443. if self.calc_merkle_root() != self.hashMerkleRoot:
  444. return False
  445. return True
  446. def solve(self):
  447. self.calc_sha256()
  448. target = uint256_from_compact(self.nBits)
  449. while self.sha256 > target:
  450. self.nNonce += 1
  451. self.rehash()
  452. def __repr__(self):
  453. return "CBlock(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nBits=%08x nNonce=%08x vtx=%s)" \
  454. % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot,
  455. time.ctime(self.nTime), self.nBits, self.nNonce, repr(self.vtx))
  456. class CUnsignedAlert(object):
  457. def __init__(self):
  458. self.nVersion = 1
  459. self.nRelayUntil = 0
  460. self.nExpiration = 0
  461. self.nID = 0
  462. self.nCancel = 0
  463. self.setCancel = []
  464. self.nMinVer = 0
  465. self.nMaxVer = 0
  466. self.setSubVer = []
  467. self.nPriority = 0
  468. self.strComment = ""
  469. self.strStatusBar = ""
  470. self.strReserved = ""
  471. def deserialize(self, f):
  472. self.nVersion = struct.unpack("<i", f.read(4))[0]
  473. self.nRelayUntil = struct.unpack("<q", f.read(8))[0]
  474. self.nExpiration = struct.unpack("<q", f.read(8))[0]
  475. self.nID = struct.unpack("<i", f.read(4))[0]
  476. self.nCancel = struct.unpack("<i", f.read(4))[0]
  477. self.setCancel = deser_int_vector(f)
  478. self.nMinVer = struct.unpack("<i", f.read(4))[0]
  479. self.nMaxVer = struct.unpack("<i", f.read(4))[0]
  480. self.setSubVer = deser_string_vector(f)
  481. self.nPriority = struct.unpack("<i", f.read(4))[0]
  482. self.strComment = deser_string(f)
  483. self.strStatusBar = deser_string(f)
  484. self.strReserved = deser_string(f)
  485. def serialize(self):
  486. r = ""
  487. r += struct.pack("<i", self.nVersion)
  488. r += struct.pack("<q", self.nRelayUntil)
  489. r += struct.pack("<q", self.nExpiration)
  490. r += struct.pack("<i", self.nID)
  491. r += struct.pack("<i", self.nCancel)
  492. r += ser_int_vector(self.setCancel)
  493. r += struct.pack("<i", self.nMinVer)
  494. r += struct.pack("<i", self.nMaxVer)
  495. r += ser_string_vector(self.setSubVer)
  496. r += struct.pack("<i", self.nPriority)
  497. r += ser_string(self.strComment)
  498. r += ser_string(self.strStatusBar)
  499. r += ser_string(self.strReserved)
  500. return r
  501. def __repr__(self):
  502. return "CUnsignedAlert(nVersion %d, nRelayUntil %d, nExpiration %d, nID %d, nCancel %d, nMinVer %d, nMaxVer %d, nPriority %d, strComment %s, strStatusBar %s, strReserved %s)" \
  503. % (self.nVersion, self.nRelayUntil, self.nExpiration, self.nID,
  504. self.nCancel, self.nMinVer, self.nMaxVer, self.nPriority,
  505. self.strComment, self.strStatusBar, self.strReserved)
  506. class CAlert(object):
  507. def __init__(self):
  508. self.vchMsg = ""
  509. self.vchSig = ""
  510. def deserialize(self, f):
  511. self.vchMsg = deser_string(f)
  512. self.vchSig = deser_string(f)
  513. def serialize(self):
  514. r = ""
  515. r += ser_string(self.vchMsg)
  516. r += ser_string(self.vchSig)
  517. return r
  518. def __repr__(self):
  519. return "CAlert(vchMsg.sz %d, vchSig.sz %d)" \
  520. % (len(self.vchMsg), len(self.vchSig))
  521. # Objects that correspond to messages on the wire
  522. class msg_version(object):
  523. command = "version"
  524. def __init__(self):
  525. self.nVersion = MY_VERSION
  526. self.nServices = 1
  527. self.nTime = time.time()
  528. self.addrTo = CAddress()
  529. self.addrFrom = CAddress()
  530. self.nNonce = random.getrandbits(64)
  531. self.strSubVer = MY_SUBVERSION
  532. self.nStartingHeight = -1
  533. def deserialize(self, f):
  534. self.nVersion = struct.unpack("<i", f.read(4))[0]
  535. if self.nVersion == 10300:
  536. self.nVersion = 300
  537. self.nServices = struct.unpack("<Q", f.read(8))[0]
  538. self.nTime = struct.unpack("<q", f.read(8))[0]
  539. self.addrTo = CAddress()
  540. self.addrTo.deserialize(f)
  541. if self.nVersion >= 106:
  542. self.addrFrom = CAddress()
  543. self.addrFrom.deserialize(f)
  544. self.nNonce = struct.unpack("<Q", f.read(8))[0]
  545. self.strSubVer = deser_string(f)
  546. if self.nVersion >= 209:
  547. self.nStartingHeight = struct.unpack("<i", f.read(4))[0]
  548. else:
  549. self.nStartingHeight = None
  550. else:
  551. self.addrFrom = None
  552. self.nNonce = None
  553. self.strSubVer = None
  554. self.nStartingHeight = None
  555. def serialize(self):
  556. r = ""
  557. r += struct.pack("<i", self.nVersion)
  558. r += struct.pack("<Q", self.nServices)
  559. r += struct.pack("<q", self.nTime)
  560. r += self.addrTo.serialize()
  561. r += self.addrFrom.serialize()
  562. r += struct.pack("<Q", self.nNonce)
  563. r += ser_string(self.strSubVer)
  564. r += struct.pack("<i", self.nStartingHeight)
  565. return r
  566. def __repr__(self):
  567. return 'msg_version(nVersion=%i nServices=%i nTime=%s addrTo=%s addrFrom=%s nNonce=0x%016X strSubVer=%s nStartingHeight=%i)' \
  568. % (self.nVersion, self.nServices, time.ctime(self.nTime),
  569. repr(self.addrTo), repr(self.addrFrom), self.nNonce,
  570. self.strSubVer, self.nStartingHeight)
  571. class msg_verack(object):
  572. command = "verack"
  573. def __init__(self):
  574. pass
  575. def deserialize(self, f):
  576. pass
  577. def serialize(self):
  578. return ""
  579. def __repr__(self):
  580. return "msg_verack()"
  581. class msg_addr(object):
  582. command = "addr"
  583. def __init__(self):
  584. self.addrs = []
  585. def deserialize(self, f):
  586. self.addrs = deser_vector(f, CAddress)
  587. def serialize(self):
  588. return ser_vector(self.addrs)
  589. def __repr__(self):
  590. return "msg_addr(addrs=%s)" % (repr(self.addrs))
  591. class msg_alert(object):
  592. command = "alert"
  593. def __init__(self):
  594. self.alert = CAlert()
  595. def deserialize(self, f):
  596. self.alert = CAlert()
  597. self.alert.deserialize(f)
  598. def serialize(self):
  599. r = ""
  600. r += self.alert.serialize()
  601. return r
  602. def __repr__(self):
  603. return "msg_alert(alert=%s)" % (repr(self.alert), )
  604. class msg_inv(object):
  605. command = "inv"
  606. def __init__(self, inv=None):
  607. if inv is None:
  608. self.inv = []
  609. else:
  610. self.inv = inv
  611. def deserialize(self, f):
  612. self.inv = deser_vector(f, CInv)
  613. def serialize(self):
  614. return ser_vector(self.inv)
  615. def __repr__(self):
  616. return "msg_inv(inv=%s)" % (repr(self.inv))
  617. class msg_getdata(object):
  618. command = "getdata"
  619. def __init__(self, inv=None):
  620. self.inv = inv if inv != None else []
  621. def deserialize(self, f):
  622. self.inv = deser_vector(f, CInv)
  623. def serialize(self):
  624. return ser_vector(self.inv)
  625. def __repr__(self):
  626. return "msg_getdata(inv=%s)" % (repr(self.inv))
  627. class msg_getblocks(object):
  628. command = "getblocks"
  629. def __init__(self):
  630. self.locator = CBlockLocator()
  631. self.hashstop = 0L
  632. def deserialize(self, f):
  633. self.locator = CBlockLocator()
  634. self.locator.deserialize(f)
  635. self.hashstop = deser_uint256(f)
  636. def serialize(self):
  637. r = ""
  638. r += self.locator.serialize()
  639. r += ser_uint256(self.hashstop)
  640. return r
  641. def __repr__(self):
  642. return "msg_getblocks(locator=%s hashstop=%064x)" \
  643. % (repr(self.locator), self.hashstop)
  644. class msg_tx(object):
  645. command = "tx"
  646. def __init__(self, tx=CTransaction()):
  647. self.tx = tx
  648. def deserialize(self, f):
  649. self.tx.deserialize(f)
  650. def serialize(self):
  651. return self.tx.serialize()
  652. def __repr__(self):
  653. return "msg_tx(tx=%s)" % (repr(self.tx))
  654. class msg_block(object):
  655. command = "block"
  656. def __init__(self, block=None):
  657. if block is None:
  658. self.block = CBlock()
  659. else:
  660. self.block = block
  661. def deserialize(self, f):
  662. self.block.deserialize(f)
  663. def serialize(self):
  664. return self.block.serialize()
  665. def __repr__(self):
  666. return "msg_block(block=%s)" % (repr(self.block))
  667. class msg_getaddr(object):
  668. command = "getaddr"
  669. def __init__(self):
  670. pass
  671. def deserialize(self, f):
  672. pass
  673. def serialize(self):
  674. return ""
  675. def __repr__(self):
  676. return "msg_getaddr()"
  677. class msg_ping_prebip31(object):
  678. command = "ping"
  679. def __init__(self):
  680. pass
  681. def deserialize(self, f):
  682. pass
  683. def serialize(self):
  684. return ""
  685. def __repr__(self):
  686. return "msg_ping() (pre-bip31)"
  687. class msg_ping(object):
  688. command = "ping"
  689. def __init__(self, nonce=0L):
  690. self.nonce = nonce
  691. def deserialize(self, f):
  692. self.nonce = struct.unpack("<Q", f.read(8))[0]
  693. def serialize(self):
  694. r = ""
  695. r += struct.pack("<Q", self.nonce)
  696. return r
  697. def __repr__(self):
  698. return "msg_ping(nonce=%08x)" % self.nonce
  699. class msg_pong(object):
  700. command = "pong"
  701. def __init__(self, nonce=0L):
  702. self.nonce = nonce
  703. def deserialize(self, f):
  704. self.nonce = struct.unpack("<Q", f.read(8))[0]
  705. def serialize(self):
  706. r = ""
  707. r += struct.pack("<Q", self.nonce)
  708. return r
  709. def __repr__(self):
  710. return "msg_pong(nonce=%08x)" % self.nonce
  711. class msg_mempool(object):
  712. command = "mempool"
  713. def __init__(self):
  714. pass
  715. def deserialize(self, f):
  716. pass
  717. def serialize(self):
  718. return ""
  719. def __repr__(self):
  720. return "msg_mempool()"
  721. class msg_sendheaders(object):
  722. command = "sendheaders"
  723. def __init__(self):
  724. pass
  725. def deserialize(self, f):
  726. pass
  727. def serialize(self):
  728. return ""
  729. def __repr__(self):
  730. return "msg_sendheaders()"
  731. # getheaders message has
  732. # number of entries
  733. # vector of hashes
  734. # hash_stop (hash of last desired block header, 0 to get as many as possible)
  735. class msg_getheaders(object):
  736. command = "getheaders"
  737. def __init__(self):
  738. self.locator = CBlockLocator()
  739. self.hashstop = 0L
  740. def deserialize(self, f):
  741. self.locator = CBlockLocator()
  742. self.locator.deserialize(f)
  743. self.hashstop = deser_uint256(f)
  744. def serialize(self):
  745. r = ""
  746. r += self.locator.serialize()
  747. r += ser_uint256(self.hashstop)
  748. return r
  749. def __repr__(self):
  750. return "msg_getheaders(locator=%s, stop=%064x)" \
  751. % (repr(self.locator), self.hashstop)
  752. # headers message has
  753. # <count> <vector of block headers>
  754. class msg_headers(object):
  755. command = "headers"
  756. def __init__(self):
  757. self.headers = []
  758. def deserialize(self, f):
  759. # comment in bitcoind indicates these should be deserialized as blocks
  760. blocks = deser_vector(f, CBlock)
  761. for x in blocks:
  762. self.headers.append(CBlockHeader(x))
  763. def serialize(self):
  764. blocks = [CBlock(x) for x in self.headers]
  765. return ser_vector(blocks)
  766. def __repr__(self):
  767. return "msg_headers(headers=%s)" % repr(self.headers)
  768. class msg_reject(object):
  769. command = "reject"
  770. def __init__(self):
  771. self.message = ""
  772. self.code = ""
  773. self.reason = ""
  774. self.data = 0L
  775. def deserialize(self, f):
  776. self.message = deser_string(f)
  777. self.code = struct.unpack("<B", f.read(1))[0]
  778. self.reason = deser_string(f)
  779. if (self.message == "block" or self.message == "tx"):
  780. self.data = deser_uint256(f)
  781. def serialize(self):
  782. r = ser_string(self.message)
  783. r += struct.pack("<B", self.code)
  784. r += ser_string(self.reason)
  785. if (self.message == "block" or self.message == "tx"):
  786. r += ser_uint256(self.data)
  787. return r
  788. def __repr__(self):
  789. return "msg_reject: %s %d %s [%064x]" \
  790. % (self.message, self.code, self.reason, self.data)
  791. # This is what a callback should look like for NodeConn
  792. # Reimplement the on_* functions to provide handling for events
  793. class NodeConnCB(object):
  794. def __init__(self):
  795. self.verack_received = False
  796. # deliver_sleep_time is helpful for debugging race conditions in p2p
  797. # tests; it causes message delivery to sleep for the specified time
  798. # before acquiring the global lock and delivering the next message.
  799. self.deliver_sleep_time = None
  800. def set_deliver_sleep_time(self, value):
  801. with mininode_lock:
  802. self.deliver_sleep_time = value
  803. def get_deliver_sleep_time(self):
  804. with mininode_lock:
  805. return self.deliver_sleep_time
  806. # Spin until verack message is received from the node.
  807. # Tests may want to use this as a signal that the test can begin.
  808. # This can be called from the testing thread, so it needs to acquire the
  809. # global lock.
  810. def wait_for_verack(self):
  811. while True:
  812. with mininode_lock:
  813. if self.verack_received:
  814. return
  815. time.sleep(0.05)
  816. def deliver(self, conn, message):
  817. deliver_sleep = self.get_deliver_sleep_time()
  818. if deliver_sleep is not None:
  819. time.sleep(deliver_sleep)
  820. with mininode_lock:
  821. try:
  822. getattr(self, 'on_' + message.command)(conn, message)
  823. except:
  824. print "ERROR delivering %s (%s)" % (repr(message),
  825. sys.exc_info()[0])
  826. def on_version(self, conn, message):
  827. if message.nVersion >= 209:
  828. conn.send_message(msg_verack())
  829. conn.ver_send = min(MY_VERSION, message.nVersion)
  830. if message.nVersion < 209:
  831. conn.ver_recv = conn.ver_send
  832. def on_verack(self, conn, message):
  833. conn.ver_recv = conn.ver_send
  834. self.verack_received = True
  835. def on_inv(self, conn, message):
  836. want = msg_getdata()
  837. for i in message.inv:
  838. if i.type != 0:
  839. want.inv.append(i)
  840. if len(want.inv):
  841. conn.send_message(want)
  842. def on_addr(self, conn, message): pass
  843. def on_alert(self, conn, message): pass
  844. def on_getdata(self, conn, message): pass
  845. def on_getblocks(self, conn, message): pass
  846. def on_tx(self, conn, message): pass
  847. def on_block(self, conn, message): pass
  848. def on_getaddr(self, conn, message): pass
  849. def on_headers(self, conn, message): pass
  850. def on_getheaders(self, conn, message): pass
  851. def on_ping(self, conn, message):
  852. if conn.ver_send > BIP0031_VERSION:
  853. conn.send_message(msg_pong(message.nonce))
  854. def on_reject(self, conn, message): pass
  855. def on_close(self, conn): pass
  856. def on_mempool(self, conn): pass
  857. def on_pong(self, conn, message): pass
  858. # The actual NodeConn class
  859. # This class provides an interface for a p2p connection to a specified node
  860. class NodeConn(asyncore.dispatcher):
  861. messagemap = {
  862. "version": msg_version,
  863. "verack": msg_verack,
  864. "addr": msg_addr,
  865. "alert": msg_alert,
  866. "inv": msg_inv,
  867. "getdata": msg_getdata,
  868. "getblocks": msg_getblocks,
  869. "tx": msg_tx,
  870. "block": msg_block,
  871. "getaddr": msg_getaddr,
  872. "ping": msg_ping,
  873. "pong": msg_pong,
  874. "headers": msg_headers,
  875. "getheaders": msg_getheaders,
  876. "reject": msg_reject,
  877. "mempool": msg_mempool
  878. }
  879. MAGIC_BYTES = {
  880. "mainnet": "\xf9\xbe\xb4\xd9", # mainnet
  881. "testnet3": "\x0b\x11\x09\x07", # testnet3
  882. "regtest": "\xfa\xbf\xb5\xda" # regtest
  883. }
  884. def __init__(self, dstaddr, dstport, rpc, callback, net="regtest", services=1):
  885. asyncore.dispatcher.__init__(self, map=mininode_socket_map)
  886. self.log = logging.getLogger("NodeConn(%s:%d)" % (dstaddr, dstport))
  887. self.dstaddr = dstaddr
  888. self.dstport = dstport
  889. self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
  890. self.sendbuf = ""
  891. self.recvbuf = ""
  892. self.ver_send = 209
  893. self.ver_recv = 209
  894. self.last_sent = 0
  895. self.state = "connecting"
  896. self.network = net
  897. self.cb = callback
  898. self.disconnect = False
  899. # stuff version msg into sendbuf
  900. vt = msg_version()
  901. vt.nServices = services
  902. vt.addrTo.ip = self.dstaddr
  903. vt.addrTo.port = self.dstport
  904. vt.addrFrom.ip = "0.0.0.0"
  905. vt.addrFrom.port = 0
  906. self.send_message(vt, True)
  907. print 'MiniNode: Connecting to Bitcoin Node IP # ' + dstaddr + ':' \
  908. + str(dstport)
  909. try:
  910. self.connect((dstaddr, dstport))
  911. except:
  912. self.handle_close()
  913. self.rpc = rpc
  914. def show_debug_msg(self, msg):
  915. self.log.debug(msg)
  916. def handle_connect(self):
  917. self.show_debug_msg("MiniNode: Connected & Listening: \n")
  918. self.state = "connected"
  919. def handle_close(self):
  920. self.show_debug_msg("MiniNode: Closing Connection to %s:%d... "
  921. % (self.dstaddr, self.dstport))
  922. self.state = "closed"
  923. self.recvbuf = ""
  924. self.sendbuf = ""
  925. try:
  926. self.close()
  927. except:
  928. pass
  929. self.cb.on_close(self)
  930. def handle_read(self):
  931. try:
  932. t = self.recv(8192)
  933. if len(t) > 0:
  934. self.recvbuf += t
  935. self.got_data()
  936. except:
  937. pass
  938. def readable(self):
  939. return True
  940. def writable(self):
  941. with mininode_lock:
  942. length = len(self.sendbuf)
  943. return (length > 0)
  944. def handle_write(self):
  945. with mininode_lock:
  946. try:
  947. sent = self.send(self.sendbuf)
  948. except:
  949. self.handle_close()
  950. return
  951. self.sendbuf = self.sendbuf[sent:]
  952. def got_data(self):
  953. while True:
  954. if len(self.recvbuf) < 4:
  955. return
  956. if self.recvbuf[:4] != self.MAGIC_BYTES[self.network]:
  957. raise ValueError("got garbage %s" % repr(self.recvbuf))
  958. if self.ver_recv < 209:
  959. if len(self.recvbuf) < 4 + 12 + 4:
  960. return
  961. command = self.recvbuf[4:4+12].split("\x00", 1)[0]
  962. msglen = struct.unpack("<i", self.recvbuf[4+12:4+12+4])[0]
  963. checksum = None
  964. if len(self.recvbuf) < 4 + 12 + 4 + msglen:
  965. return
  966. msg = self.recvbuf[4+12+4:4+12+4+msglen]
  967. self.recvbuf = self.recvbuf[4+12+4+msglen:]
  968. else:
  969. if len(self.recvbuf) < 4 + 12 + 4 + 4:
  970. return
  971. command = self.recvbuf[4:4+12].split("\x00", 1)[0]
  972. msglen = struct.unpack("<i", self.recvbuf[4+12:4+12+4])[0]
  973. checksum = self.recvbuf[4+12+4:4+12+4+4]
  974. if len(self.recvbuf) < 4 + 12 + 4 + 4 + msglen:
  975. return
  976. msg = self.recvbuf[4+12+4+4:4+12+4+4+msglen]
  977. th = sha256(msg)
  978. h = sha256(th)
  979. if checksum != h[:4]:
  980. raise ValueError("got bad checksum " + repr(self.recvbuf))
  981. self.recvbuf = self.recvbuf[4+12+4+4+msglen:]
  982. if command in self.messagemap:
  983. f = cStringIO.StringIO(msg)
  984. t = self.messagemap[command]()
  985. t.deserialize(f)
  986. self.got_message(t)
  987. else:
  988. self.show_debug_msg("Unknown command: '" + command + "' " +
  989. repr(msg))
  990. def send_message(self, message, pushbuf=False):
  991. if self.state != "connected" and not pushbuf:
  992. return
  993. self.show_debug_msg("Send %s" % repr(message))
  994. command = message.command
  995. data = message.serialize()
  996. tmsg = self.MAGIC_BYTES[self.network]
  997. tmsg += command
  998. tmsg += "\x00" * (12 - len(command))
  999. tmsg += struct.pack("<I", len(data))
  1000. if self.ver_send >= 209:
  1001. th = sha256(data)
  1002. h = sha256(th)
  1003. tmsg += h[:4]
  1004. tmsg += data
  1005. with mininode_lock:
  1006. self.sendbuf += tmsg
  1007. self.last_sent = time.time()
  1008. def got_message(self, message):
  1009. if message.command == "version":
  1010. if message.nVersion <= BIP0031_VERSION:
  1011. self.messagemap['ping'] = msg_ping_prebip31
  1012. if self.last_sent + 30 * 60 < time.time():
  1013. self.send_message(self.messagemap['ping']())
  1014. self.show_debug_msg("Recv %s" % repr(message))
  1015. self.cb.deliver(self, message)
  1016. def disconnect_node(self):
  1017. self.disconnect = True
  1018. class NetworkThread(Thread):
  1019. def run(self):
  1020. while mininode_socket_map:
  1021. # We check for whether to disconnect outside of the asyncore
  1022. # loop to workaround the behavior of asyncore when using
  1023. # select
  1024. disconnected = []
  1025. for fd, obj in mininode_socket_map.items():
  1026. if obj.disconnect:
  1027. disconnected.append(obj)
  1028. [ obj.handle_close() for obj in disconnected ]
  1029. asyncore.loop(0.1, use_poll=True, map=mininode_socket_map, count=1)
  1030. # An exception we can raise if we detect a potential disconnect
  1031. # (p2p or rpc) before the test is complete
  1032. class EarlyDisconnectError(Exception):
  1033. def __init__(self, value):
  1034. self.value = value
  1035. def __str__(self):
  1036. return repr(self.value)