Gunpowder was invented in China not by people seeking better weapons or even explosives, but by alchemists seeking the elixir of immortality. Ancient Chinese alchemists believed that by putting different elements in a big pot and heat it over a long period of time, 50+ years, there's a possibility that they can create an element which can led to immority. Before Gunpowder can be developed, first it was necessary to recognize and obtain the most important of its three ingredients. This is saltpeter, the chemical name for which is potassium nitrate. It generally forms natural deposits only in hot climates there is a considerable shortagte of it in Europe. Long before anyone had any idea that saltpeter could be used as an ingredient of the then still unknown gunpowder mixture, it was prized for its ability to liquefy ores and to dissolve otherwise indissoluble minerals. Saltpeter was used for this purpose at least by the second century BC, as well as acting as a flux to promote metallurgical processes. Since the name Solving-stone goes back to the fourth century BC, it is likely that saltpeter's uses were appreciated then, though they were not specified in surving texts until the second century BC.
Another essential constituent of gunpowder is sulfur, and this too the Chinese were able to purify it before the Second Century BC. With saltpeter, sulfure and the readily available carbon of charcoal and other substances all in Chinese's hands continually, it was for sure that the alchemists would eventually put the three together and stumble upon gunpowder. Indeed, by the third century AD we find evidence that saltpeter and sulfur were being combined in the search for artificial gold and immortality. Though the gunpowder was invented around the Third Century BC, the true gunpowder formula was firstly published in the history around the year 1040 by Tseng Kung-Liang. It was then used in Warfare.