| 1181 | assert_equal(BLOCK_HEADER_SIZE, 79) |
| 1182 | |
| 1183 | class CBlock(CBlockHeader): |
| 1184 | __slots__ = ("vtx",) |
| 1185 | |
| 1186 | def __init__(self, header=None): |
| 1187 | super().__init__(header) |
| 1188 | self.vtx = [] |
| 1189 | |
| 1190 | def deserialize(self, f): |
| 1191 | super().deserialize(f) |
| 1192 | self.vtx = deser_vector(f, CTransaction) |
| 1193 | |
| 1194 | def serialize(self, with_witness=True): |
| 1195 | r = b"" |
| 1196 | r += super().serialize() |
| 1197 | if with_witness: |
| 1198 | r += ser_vector(self.vtx, "serialize_with_witness") |
| 1199 | else: |
| 1200 | r += ser_vector(self.vtx, "serialize_without_witness") |
| 1201 | return r |
| 1202 | |
| 1203 | # Calculate the merkle root given a vector of transaction hashes |
| 1204 | @classmethod |
| 1205 | def get_merkle_root(cls, hashes): |
| 1206 | while len(hashes) > 1: |
| 1207 | newhashes = [] |
| 1208 | for i in range(0, len(hashes), 2): |
| 1209 | i2 = min(i+1, len(hashes)-1) |
| 1210 | newhashes.append(hash256(hashes[i] + hashes[i2])) |
| 1211 | hashes = newhashes |
| 1212 | return uint256_from_str(hashes[0]) |
| 1213 | |
| 1214 | def calc_merkle_root(self): |
| 1215 | hashes = [] |
| 1216 | for tx in self.vtx: |
| 1217 | tx.calc_sha256() |
| 1218 | hashes.append(ser_uint256(tx.sha256)) |
| 1219 | return self.get_merkle_root(hashes) |
| 1220 | |
| 1221 | def calc_witness_merkle_root(self): |
| 1222 | hashes = [] |
| 1223 | for tx in self.vtx: |
| 1224 | # Calculate the hashes with witness data |
| 1225 | hashes.append(tx.calc_witness_hash()) |
| 1226 | |
| 1227 | # returns bitcoin hash print order hex string |
| 1228 | return calcfastmerkleroot(hashes) |
| 1229 | |
| 1230 | def is_valid(self): |
| 1231 | self.calc_sha256() |
| 1232 | # TODO: check signatures |
| 1233 | # target = uint256_from_compact(self.nBits) |
| 1234 | # if self.sha256 > target: |
| 1235 | # return False |
| 1236 | for tx in self.vtx: |
| 1237 | if not tx.is_valid(): |
| 1238 | return False |
| 1239 | if self.calc_merkle_root() != self.hashMerkleRoot: |
| 1240 | return False |
no outgoing calls