def hash(self):
        """Returns the transaction's id. Equivalent to the hash for non SegWit transactions,
        it differs from it for SegWit ones. """
        if self._hash is None:
            self._hash = format_hash(double_sha256(self.hex))

        return self._hash
Exemplo n.º 2
0
 def serialize(self):
     result = NETWORK_MAGIC
     result += encode_command(self.command)
     result += int_to_little_endian(len(self.payload), 4)
     result += double_sha256(self.payload)[:4]
     result += self.payload
     return result
Exemplo n.º 3
0
    def parse_from_hex(self, raw_hex):
        offset = 4
        self._version = decode_uint32(raw_hex[:4])
        input_cnt, varint_size = decode_varint(raw_hex[offset:])
        self.input_cnt = input_cnt
        offset += varint_size
        self._inputs = []
        for i in range(input_cnt):
            tx_input = TransactionInput().parse_from_hex(raw_hex[offset:])
            print tx_input.__repr__()
            offset += tx_input.size
            self._inputs.append(input)

        output_cnt, varint_size = decode_varint(raw_hex[offset:])
        offset += varint_size
        self.output_cnt = output_cnt
        self._outputs = []
        for i in range(output_cnt):
            tx_output = TransactionOutput().parse_from_hex(raw_hex[offset:])
            print tx_output.__repr__()
            offset += tx_output.size
            self._outputs.append(tx_output)

        self.size = offset + 4
        self.hash = format_hash(double_sha256(raw_hex[:self.size]))
        return self
Exemplo n.º 4
0
 def hash(self):
     '''Returns the double-sha256 interpreted little endian of the block'''
     # serialize
     s = self.serialize()
     # double-sha256
     sha = double_sha256(s)
     # reverse
     return sha[::-1]
Exemplo n.º 5
0
    def address(self):
        """Returns the base58 encoded representation of this address"""
        if self._address is None:
            version = b'\x00' if self.type == "normal" else b'\x05'
            checksum = double_sha256(version + self.hash)

            self._address = base58.encode(version + self.hash + checksum[:4])
        return self._address
Exemplo n.º 6
0
async def read_message(reader):
    magic = await reader.read(4)
    if magic != NETWORK_MAGIC:
        raise RuntimeError("Network Magic not at beginning of stream")
    command = await reader.read(12)
    payload_length = little_endian_to_int(await reader.read(4))
    checksum = await reader.read(4)
    payload = await reader.read(payload_length)
    if double_sha256(payload)[:4] != checksum:
        raise RuntimeError("Payload and Checksum do not match")
    return Message(command, payload)
Exemplo n.º 7
0
    def verify_block(self, block):
        """
        1. hash (block header + nonce) to see if the hash is correct
        - also verify merkel hash
        2. input txns should exist as UTXO 
            2.1 check scripting signatures and pubkeyscript
            2.2 diff of output and input amount == reward in coinbase txn of block
        this means: block is correct.
        """
        serial = block.get_serialized_block_header(block.nonce)
        
        # verifying hash of block
        hash_hex = double_sha256(serial)
        if not (hash_hex == block.hash and 
            block.merkle_root == block.get_merkle_root_hash()):
            return False

        # block.txns[0] is coinbase [ASSUMPTION]
        coinbase_future_reward = 0.0
        for txn in block.txns[1:]:
            input_amount = 0.0
            for inp_txn in txn.inp_txns:
                if not self.UTXOdb.search_by_txnid(inp_txn.txnid, inp_txn.vout):
                    return False

                output_txn = self.UTXOdb.get_txn_by_txnid(inp_txn.txnid).out_txns[inp_txn.vout]
                if not ScriptInterpreter.verify_pay_to_pubkey_hash(
                    inp_txn.signature_script,
                    output_txn.script_pub_key,
                    inp_txn.txnid
                    ):
                    return False

                input_amount += output_txn.amount 

            output_amount = 0.0
            for out_txn in txn.out_txns:
                output_amount += out_txn.amount

            if output_amount > input_amount:
                return False
            coinbase_future_reward += (input_amount - output_amount)

        # verify coinbase
        coinbase = block.txns[0]
        if not ((len(coinbase.inp_txns) == 1) and (int(coinbase.inp_txns[0].txnid, 16) == 0)
                        and (int(coinbase.inp_txns[0].vout) == -1)
                        and (len(coinbase.out_txns) == 1)):
            return False
        
        if coinbase.out_txns[0].amount > coinbase_future_reward + config.reward:
            return False

        return True
Exemplo n.º 8
0
 def parse_from_hex(self, raw_hex):
     assert (len(raw_hex) == 80)
     self._version = decode_uint32(raw_hex[:4])
     self._previous_block_hash = format_hash(raw_hex[4:36])
     self._merkle_root = format_hash(raw_hex[36:68])
     self._timestamp = decode_uint32(raw_hex[68:72])
     self._bits = decode_uint32(raw_hex[72:76])
     self._nonce = decode_uint32(raw_hex[76:80])
     self._difficulty = self.calc_difficulty(self._bits)
     self.hash = format_hash(double_sha256(raw_hex))
     print self.__repr__()
     return self
    def hash(self):
        """Returns the transaction's hash"""
        if self._hash is None:
            # segwit transactions have two transaction ids/hashes, txid and wtxid
            # txid is a hash of all of the legacy transaction fields only
            if self.is_segwit:
                txid = self.hex[:4] + self.hex[
                    6:self._offset_before_tx_witnesses] + self.hex[-4:]
            else:
                txid = self.hex
            self._hash = format_hash(double_sha256(txid))

        return self._hash
Exemplo n.º 10
0
    def txid(self):
        """Returns the transaction's id. Equivalent to the hash for non SegWit transactions,
        it differs from it for SegWit ones. """
        if self._txid is None:
            # segwit transactions have two transaction ids/hashes, txid and wtxid
            # txid is a hash of all of the legacy transaction fields only
            if self.is_segwit:
                txid_data = self.hex[:4] + self.hex[
                    6:self._offset_before_tx_witnesses] + self.hex[-4:]
            else:
                txid_data = self.hex
            self._txid = format_hash(double_sha256(txid_data))

        return self._txid
Exemplo n.º 11
0
 def parse_from_hex(self, raw_hex):
     assert (len(raw_hex) == 80)
     self._version = decode_uint32(raw_hex[:4])
     self._previous_block_hash = format_hash(raw_hex[4:36])
     self._merkle_root = format_hash(raw_hex[36:68])
     self._timestamp = decode_uint32(raw_hex[68:72])
     # time_local = decode_uint32(raw_hex[68:72])
     # time_local = time.localtime(time_local)
     # self._timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
     self._bits = decode_uint32(raw_hex[72:76])
     self._nonce = decode_uint32(raw_hex[76:80])
     self._difficulty = self.calc_difficulty(self._bits)
     self.hash = format_hash(double_sha256(raw_hex))
     # print(self.__repr__())
     return self
Exemplo n.º 12
0
def sign_vote(votestr, mnprivkey):
    privatekey = utils.wifToPrivateKey(mnprivkey)
    signingkey = Bip62SigningKey.from_string(privatekey.decode('hex'),
                                             curve=ecdsa.SECP256k1)
    public_key = signingkey.get_verifying_key()
    key = Key.from_text(mnprivkey)
    address = key.address(use_uncompressed=True)
    msghash = utils.double_sha256(utils.msg_magic(votestr))
    signature = signingkey.sign_digest_deterministic(
        msghash,
        hashfunc=hashlib.sha256,
        sigencode=ecdsa.util.sigencode_string)
    assert public_key.verify_digest(signature,
                                    msghash,
                                    sigdecode=ecdsa.util.sigdecode_string)
    for i in range(4):
        sig = base64.b64encode(chr(27 + i) + signature)
        if verify_dash_signature(generator_secp256k1, address, msghash, sig):
            return sig
Exemplo n.º 13
0
    def parse(cls, s):
        magic = consume_stream(s, 4)
        if magic != NETWORK_MAGIC:
            raise ValueError('magic is not right')

        command = parse_command(consume_stream(s, 12))
        payload_length = little_endian_to_int(consume_stream(s, 4))
        checksum = consume_stream(s, 4)
        payload = consume_stream(s, payload_length)
        calculated_checksum = double_sha256(payload)[:4]

        if calculated_checksum != checksum:
            raise RuntimeError('checksum does not match')

        if payload_length != len(payload):
            raise RuntimeError(
                "Tried to read {payload_length} bytes, only received {len(payload)} bytes"
            )

        return cls(command, payload)
Exemplo n.º 14
0
	def create_txid(self):
		data = self.get_txn_data()
		return double_sha256(data)
Exemplo n.º 15
0
 def get_hash(self, nonce):
     return double_sha256(self.block.get_serialized_block_header(nonce))
Exemplo n.º 16
0
 def pow(self):
     s = self.serialize()
     sha = double_sha256(s)
     return little_endian_to_int(sha)
Exemplo n.º 17
0
 def hash(self):
     """Returns the block's hash (double sha256 of its 80 bytes header"""
     if self._hash is None:
         self._hash = format_hash(double_sha256(self.hex[:80]))
     return self._hash