Advertisement
Guest User

Untitled

a guest
Sep 24th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. class CBlock(object):
  2. def __init__(self):
  3. self.nVersion = 1
  4. self.hashPrevBlock = 0
  5. self.hashMerkleRoot = 0
  6. self.nTime = 0
  7. self.nBits = 0
  8. self.nNonce = 0
  9. self.vtx = []
  10. self.sha256 = None
  11. self.hash = None
  12. def deserialize(self, f):
  13. self.nVersion = struct.unpack("<i", f.read(4))[0]
  14. self.hashPrevBlock = deser_uint256(f)
  15. self.hashMerkleRoot = deser_uint256(f)
  16. self.nTime = struct.unpack("<I", f.read(4))[0]
  17. self.nBits = struct.unpack("<I", f.read(4))[0]
  18. self.nNonce = struct.unpack("<I", f.read(4))[0]
  19. self.vtx = deser_vector(f, CTransaction)
  20. def serialize(self):
  21. r = ""
  22. r += struct.pack("<i", self.nVersion)
  23. r += ser_uint256(self.hashPrevBlock)
  24. r += ser_uint256(self.hashMerkleRoot)
  25. r += struct.pack("<I", self.nTime)
  26. r += struct.pack("<I", self.nBits)
  27. r += struct.pack("<I", self.nNonce)
  28. r += ser_vector(self.vtx)
  29. return r
  30. def calc_sha256(self):
  31. if self.sha256 is None:
  32. r = ""
  33. r += struct.pack("<i", self.nVersion)
  34. r += ser_uint256(self.hashPrevBlock)
  35. r += ser_uint256(self.hashMerkleRoot)
  36. r += struct.pack("<I", self.nTime)
  37. r += struct.pack("<I", self.nBits)
  38. r += struct.pack("<I", self.nNonce)
  39. self.sha256 = uint256_from_str(hash256(r))
  40. self.hash = hash256(r)[::-1].encode('hex_codec')
  41. def is_valid(self):
  42. self.calc_sha256()
  43. target = uint256_from_compact(self.nBits)
  44. if self.sha256 > target:
  45. return False
  46. hashes = []
  47. for tx in self.vtx:
  48. if not tx.is_valid():
  49. return False
  50. tx.calc_sha256()
  51. hashes.append(ser_uint256(tx.sha256))
  52. while len(hashes) > 1:
  53. newhashes = []
  54. for i in xrange(0, len(hashes), 2):
  55. i2 = min(i+1, len(hashes)-1)
  56. newhashes.append(hash256(hashes[i] + hashes[i2]))
  57. hashes = newhashes
  58. if uint256_from_str(hashes[0]) != self.hashMerkleRoot:
  59. return False
  60. return True
  61. def __repr__(self):
  62. return "CBlock(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nBits=%08x nNonce=%08x vtx=%s)" % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot, time.ctime(self.nTime), self.nBits, self.nNonce, repr(self.vtx))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement