def __init__(self, data=None): if not data: return if re.match('^[0-9a-fA-F]*$', data): data = data.decode('hex') header, transaction_list, self.uncles = rlp.decode(data) [self.number, self.prevhash, self.uncles_root, self.coinbase, state_root, self.transactions_root, self.difficulty, self.timestamp, self.nonce, self.extra] = header self.transactions = [Transaction(x) for x in transaction_list] self.state = Trie('statedb', state_root) self.reward = 0 # Verifications if self.state.root != '' and self.state.db.get(self.state.root) == '': raise Exception("State Merkle root not found in database!") if bin_sha256(rlp.encode(transaction_list)) != self.transactions_root: raise Exception("Transaction list root hash does not match!") if bin_sha256(rlp.encode(self.uncles)) != self.uncles_root: raise Exception("Uncle root hash does not match!")
def serialize(self): txlist = [x.serialize() for x in self.transactions] header = [self.number, self.prevhash, bin_sha256(rlp.encode(self.uncles)), self.coinbase, self.state.root, bin_sha256(rlp.encode(txlist)), self.difficulty, self.timestamp, self.nonce, self.extra] return rlp.encode([header, txlist, self.uncles])
def parse(self, data): if re.match('^[0-9a-fA-F]*$', data): data = data.decode('hex') o = rlp.decode(data) self.nonce = o[0] self.to = o[1] self.value = o[2] self.fee = o[3] self.data = o[4] self.v = o[5] self.r = o[6] self.s = o[7] rawhash = sha256( rlp.encode([self.nonce, self.to, self.value, self.fee, self.data])) pub = encode_pubkey( ecdsa_raw_recover(rawhash, (self.v, self.r, self.s)), 'bin') self.sender = bin_sha256(pub[1:])[-20:] return self
def hash(self): return bin_sha256(self.serialize())
def sign(self, key): rawhash = sha256( rlp.encode([self.nonce, self.to, self.value, self.fee, self.data])) self.v, self.r, self.s = ecdsa_raw_sign(rawhash, key) self.sender = bin_sha256(privtopub(key)[1:])[-20:] return self