We study how to design an optimal government loan program for risky R&D projects with positive externalities. With adverse selection, the optimal government contract involves a high interest rate but nearly zero co-financing by the entrepreneur. This contrasts sharply with observed loan schemes. With adverse selection and moral hazard (two effort levels), the optimal policy consists of a menu of at most two contracts, one with high interest and zero self-financing, and a second with a lower interest plus co-financing. Calibrated simulations assess welfare gains from the optimal policy, observed loan programs, and a direct subsidy to private venture capital firms. The gains vary with the size of the externalities, cost of public funds, and effectiveness of the private VC industry.