def add_header(self, header):

        # Calculate the block hash
        binary_header = header.binary()[:80]

        block_hash = util.sha256d(binary_header)

        # Already exists and nothing new
        existing = self.get(block_hash, orphans = True)
        if existing:
            return False

        # @TODO: Calculate the expected target and make sure the block matches

        # @TODO: Calculate the valid time range and make sure the block matches

        # verify the block hits the target
        if not util.verify_target(self.coin, header):
            raise InvalidBlockException('block proof-of-work is greater than target')

        # find the previous block
        previous_block = self.get(header.prev_block, orphans = True)
        if not previous_block:
            raise InvalidBlockException('previous block does not exist')

        cursor = self._cursor()
        cursor.execute('begin immediate transaction')

        # find the top block
        cursor.execute(self.sql_select + ' where mainchain = 1 order by height desc limit 1')
        top_block = Block(self, cursor.fetchone())

        height = previous_block.height + 1

        mainchain = bool(height > top_block.height)

        # we building off of a sidechain that will become the mainchain?
        if mainchain and not previous_block.mainchain:

            # update all blocks from previous_block to the fork as mainchain
            cur = previous_block
            while not cur.mainchain:
                cursor.execute('update blocks set mainchain = 1 where id = ?', (cur._blockid, ))
                cur = cur.previous_block

            forked_at = cur.hash

            # update all blocks from the old top (now orphan) to the fork as not mainchain
            cur = top_block
            while cur.hash != forked_at:
                cursor.execute('update blocks set mainchain = 0 where id = ?', (cur._blockid, ))
                cur = cur.previous_block

        # add the block to the database
        cursor = self._cursor()
        row = (previous_block._blockid, buffer(block_hash), header.version,
               buffer(header.merkle_root), header.timestamp, header.bits,
               header.nonce, height, 0, mainchain)
        cursor.execute(self.sql_insert, row)
        #lastrowid = cursor.lastrowid
        self._connection.commit()

        return True
Adds a block to the database (if not present) and returns it.
dataset/ETHPy150Open ricmoo/pycoind/pycoind/blockchain/block.py/Database.add_header