<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def build_import_keychain( cls, keychain_dir, namespace_id, pubkey_hex ):
 """ Generate all possible NAME_IMPORT addresses from the NAMESPACE_REVEAL public key """


        pubkey_addr = virtualchain.BitcoinPublicKey(str(pubkey_hex)).address()

        # do we have a cached one on disk?
        cached_keychain = cls.get_import_keychain_path(keychain_dir, namespace_id)
        if os.path.exists( cached_keychain ):

            child_addrs = []
            try:
                lines = []
                with open(cached_keychain, "r") as f:
                    lines = f.readlines()

                child_attrs = [l.strip() for l in lines]

                log.debug("Loaded cached import keychain for '%s' (%s)" % (pubkey_hex, pubkey_addr))
                return child_attrs

            except Exception, e:
                log.exception(e)
                pass

        pubkey_hex = str(pubkey_hex)
        public_keychain = keychain.PublicKeychain.from_public_key( pubkey_hex )
        child_addrs = []

        for i in xrange(0, NAME_IMPORT_KEYRING_SIZE):
            public_child = public_keychain.child(i)
            public_child_address = public_child.address()

            # if we're on testnet, then re-encode as a testnet address 
            if virtualchain.version_byte == 111:
                old_child_address = public_child_address
                public_child_address = virtualchain.hex_hash160_to_address( virtualchain.address_to_hex_hash160( public_child_address ) )
                log.debug("Re-encode '%s' to '%s'" % (old_child_address, public_child_address))

            child_addrs.append( public_child_address )

            if i % 20 == 0 and i != 0:
                log.debug("%s children..." % i)

        # include this address
        child_addrs.append( pubkey_addr )

        log.debug("Done building import keychain for '%s' (%s)" % (pubkey_hex, pubkey_addr))

        # cache
        try:
            with open(cached_keychain, "w+") as f:
                for addr in child_addrs:
                    f.write("%s\n" % addr)

                f.flush()

            log.debug("Cached keychain to '%s'" % cached_keychain)
        except Exception, e:
            log.exception(e)
            log.error("Unable to cache keychain for '%s' (%s)" % (pubkey_hex, pubkey_addr))

        return child_addrs