Recent palaeomagnetic observations1report the existence of a magnetic field on Earth that is at least 3.45 billion years old. Compositional buoyancy caused by inner-core growth2is the primary driver of Earth's present-day geodynamo3,4,5, but the inner core is too young6to explain the existence of a magnetic field before about one billion years ago. Theoretical models7propose that the exsolution of magnesium oxide—the major constituent of Earth's mantle—from the core provided a major source of the energy required to drive an early dynamo, but experimental evidence for the incorporation of mantle components into the core has been lacking. Indeed, terrestrial core formation occurred in the early molten Earth by gravitational segregation of immiscible metal and silicate melts, transporting iron-loving (siderophile) elements from the silicate mantle to the metallic core8,9,10and leaving rock-loving (lithophile) mantle components behind. Here we present experiments showing that magnesium oxide dissolves in core-forming iron melt at very high temperatures. Using core-formation models11, we show that extreme events during Earth's accretion (such as the Moon-forming giant impact12) could have contributed large amounts of magnesium to the early core. As the core subsequently cooled, exsolution7of buoyant magnesium oxide would have taken place at the core-mantle boundary, generating a substantial amount of gravitational energy as a result of compositional buoyancy. This amount of energy is comparable to, if not more than, that produced by inner-core growth, resolving the conundrum posed by the existence of an ancient magnetic field prior to the formation of the inner core.